File: missingdeclarationassistant.cpp

package info (click to toggle)
kdevelop 4%3A4.3.1-3
  • links: PTS, VCS
  • area: main
  • in suites: wheezy
  • size: 18,844 kB
  • sloc: cpp: 91,758; python: 1,095; lex: 422; ruby: 120; sh: 114; xml: 42; makefile: 38
file content (314 lines) | stat: -rw-r--r-- 13,093 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
/*
   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 {
public:
  // returns a full string representing the resulting declaration, without scope or access specifiers.
  virtual QString getDeclarationString() const = 0;
  // returns a full string representing the container of the resulting declaration (only if it is a class/struct)
  virtual QString getContainerString() const {
    return QString();
  }
};

class CreateLocalDeclarationAction : public MissingDeclarationAction {
    public:
        CreateLocalDeclarationAction(KSharedPtr< Cpp::MissingDeclarationProblem > _problem) : problem(_problem) {
        }
        virtual void execute() {
          DUChainReadLocker lock(DUChain::lock());
          if(/*DUContext* searchFrom = */problem->type->searchStartContext.data()) {
            KDevelop::DocumentChangeSet changes;
            changes.addChange(KDevelop::DocumentChange(problem->url(), SimpleRange(problem->rangeInCurrentRevision().start, problem->rangeInCurrentRevision().start), QString(),  typeString() + " "));
            lock.unlock();
            
            changes.setReplacementPolicy(KDevelop::DocumentChangeSet::WarnOnFailedChange);
            changes.applyAllChanges();
          }
        }
        virtual QString description() const {
          return i18n("<b>local</b> variable");
        }
        virtual QString toolTip() const {
          return i18n("Create local declaration %1", getDeclarationString());
        }
        
        virtual QString getDeclarationString() const {
          return typeString() + " " + problem->type->identifier().toString();
        }
        
        QString typeString(int maxSize = 10000) const {
          DUChainReadLocker lock(DUChain::lock());
          if(DUContext* searchFrom = problem->type->searchStartContext.data())
            return Cpp::shortenedTypeString(type(), searchFrom, maxSize);
          else
            return QString();
        }
        
    private:
      
        AbstractType::Ptr type() const {
          AbstractType::Ptr ret = TypeUtils::realTypeKeepAliases(TypeUtils::removeConstants(problem->type->assigned.type.abstractType(), problem->topContext()))->indexed().abstractType();
          if(ret)
            ret->setModifiers(ret->modifiers() & (~AbstractType::ConstModifier)); //Remove "const" modifier
          return ret;
        }
        KSharedPtr< Cpp::MissingDeclarationProblem > problem;
        QString m_description;
};

class CreateMemberDeclarationAction : public MissingDeclarationAction {
    public:
        CreateMemberDeclarationAction(KSharedPtr< Cpp::MissingDeclarationProblem > _problem, Declaration::AccessPolicy access = Declaration::Public) : problem(_problem), m_access(access) {
        }
        virtual void execute() {
          DUChainReadLocker lock(DUChain::lock());
          DUContext* searchFrom = problem->type->searchStartContext.data();
          DUContext* container = useContainer();
          
          if(searchFrom && container) {
            KUrl localUrl = searchFrom->url().toUrl();
            KUrl changeUrl = container->url().toUrl();
            Cpp::SourceCodeInsertion ins(container->topContext());
            ins.setContext(container);
            ins.setAccess(m_access);
            
            if(problem->type->isFunction) {
              QList<Cpp::SourceCodeInsertion::SignatureItem> signature;
              int num = 1;
              QSet<QString> hadNames;
              foreach(const OverloadResolver::Parameter& arg, 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(problem->type->identifier().identifier().identifier().last(), returnType(), signature);
            }else{
              ins.insertVariableDeclaration(problem->type->identifier().identifier().identifier().last(), returnType());
            }
            lock.unlock();
            
            ins.changes().setReplacementPolicy(KDevelop::DocumentChangeSet::WarnOnFailedChange);
            ins.changes().applyAllChanges();
            if(changeUrl != localUrl) {
              ICore::self()->languageController()->backgroundParser()->addDocument(changeUrl);
              ICore::self()->languageController()->backgroundParser()->addDocument(localUrl);
            }
          }
        }
        virtual QString description() const {
          if(problem->type->isFunction)
            return i18n("<b>%1</b> function in <i>%2</i>", accessString(), Qt::escape(getContainerString()));
          else
            return i18n("<b>%1</b> variable in <i>%2</i>", accessString(), Qt::escape(getContainerString()));
        }
        
        virtual QString getContainerString() const {
          DUChainReadLocker lock(DUChain::lock());
          DUContext* container = useContainer();
          if(container)
            return container->scopeIdentifier(true).toString();
          else
            return QString();
        }
        
        virtual QString getDeclarationString() const {
          DUChainReadLocker lock(DUChain::lock());
          DUContext* container = useContainer();
          if(container)
            return QString("%2 %3").arg(returnString(), problem->type->identifier().toString() + signatureString());
          else
            return QString();
        }
        
        virtual QString toolTip() const {
          return QString("Declare %2 %3").arg(returnString(), getContainerString() + "::" + problem->type->identifier().toString() + signatureString());
        }
    private:
        QString accessString() const {
          switch(m_access) {
            case Declaration::Protected:
              return "protected";
            case Declaration::Private:
              return "private";
            case Declaration::Public:
              return "public";
            default:
              return QString();
          }      
        }
      
        DUContext* useContainer() const {
          DUContext* container = problem->type->containerContext.data();
          if(!container) {
            Declaration* classDecl = Cpp::localClassFromCodeContext(problem->type->searchStartContext.data());
            if(classDecl)
              container = classDecl->internalContext();
          }
          return container;
        }
      
        QString typeString(AbstractType::Ptr type) const {
          DUChainReadLocker lock(DUChain::lock());
          if(!type)
            return "<no type>";
          if(DUContext* container = useContainer())
            return Cpp::shortenedTypeString(type, container, 30);
          else
            return QString();
        }
      
        QString returnString() const {
          if(returnType()){
            return typeString(returnType());
          }else {
            return QString();
          }
        }
        
        QString signatureString() const {
          if(problem->type->isFunction) {
            QString ret = "(";
            bool first = true;
            foreach(const OverloadResolver::Parameter& arg, problem->type->arguments) {
              if(!first)
                ret += ", ";
              else
                first = false;
              ret += typeString(arg.type);
            }
            ret += ")";
            return ret;
          }
          return QString();
        }
        
        AbstractType::Ptr returnType() const {
          AbstractType::Ptr r = type(problem->type->convertedTo.type.abstractType());
          if(r)
            return r;
          
          r = type(problem->type->assigned.type.abstractType());
          if(r) {
            if(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;
          }
          
          KDevelop::IntegralType* i = new KDevelop::IntegralType;
          i->setDataType(KDevelop::IntegralType::TypeVoid);
          return AbstractType::Ptr(i);
        }
        
        AbstractType::Ptr type(AbstractType::Ptr base) const {
          DUChainReadLocker lock;
          AbstractType::Ptr ret = TypeUtils::realTypeKeepAliases(TypeUtils::removeConstants(base, problem->topContext()))->indexed().abstractType();
          if(ret)
            ret->setModifiers(ret->modifiers() & (~AbstractType::ConstModifier)); //Remove "const" modifier
          return ret;
        }
      
        KSharedPtr< Cpp::MissingDeclarationProblem > problem;
        QString m_description;
        Declaration::AccessPolicy m_access;
};

MissingDeclarationAssistant::MissingDeclarationAssistant(KSharedPtr< Cpp::MissingDeclarationProblem > p) : problem(p), type(p->type) {
  DUChainReadLocker lock(DUChain::lock());
  if(p->type->identifier().identifier().identifier().isEmpty())
    return;
  kDebug() << "creating assistant for" << type->toString() << "assigned:" << type->assigned.toString();
  
  if(DUContext* searchFrom = type->searchStartContext.data()) {
    if(!type->containerContext.data() && searchFrom->type() == DUContext::Other && (type->assigned.type.abstractType() || type->isFunction))
    {
      //Action to just copy in the type
      if(!type->assigned.type.type<KDevelop::DelayedType>() && !type->isFunction && !type->convertedTo.isValid())
        addAction(KDevelop::IAssistantAction::Ptr(new CreateLocalDeclarationAction(problem)));
      
      Declaration* localClass = Cpp::localClassFromCodeContext(searchFrom);
      
      //Action to create a declaration within the local class
      if(localClass && localClass->internalContext()) {
        addAction(KDevelop::IAssistantAction::Ptr(new CreateMemberDeclarationAction(problem, Declaration::Public)));
        addAction(KDevelop::IAssistantAction::Ptr(new CreateMemberDeclarationAction(problem, Declaration::Private)));
      }
    }
    if(type->containerContext.data() && (type->convertedTo.isValid() || type->assigned.isValid() || type->isFunction)) {
      KUrl url = type->containerContext.data()->url().toUrl();
      if(KDevelop::ICore::self()->projectController()->findProjectForUrl(url) || KDevelop::ICore::self()->documentController()->documentForUrl(url))
        addAction(KDevelop::IAssistantAction::Ptr(new CreateMemberDeclarationAction(problem)));
    }
  }
  
  if(!actions().isEmpty())
  {
    MissingDeclarationAction* action = dynamic_cast<MissingDeclarationAction*>(actions().last().data());
    Q_ASSERT(action);
    m_title = i18n("Declare <big><tt>'%1'</tt></big> as", action->getDeclarationString());
  }
}