OSDN Git Service

Update license.
[qt-creator-jp/qt-creator-jp.git] / src / plugins / cpptools / cppfindreferences.cpp
1 /**************************************************************************
2 **
3 ** This file is part of Qt Creator
4 **
5 ** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
6 **
7 ** Contact: Nokia Corporation (info@qt.nokia.com)
8 **
9 **
10 ** GNU Lesser General Public License Usage
11 **
12 ** This file may be used under the terms of the GNU Lesser General Public
13 ** License version 2.1 as published by the Free Software Foundation and
14 ** appearing in the file LICENSE.LGPL included in the packaging of this file.
15 ** Please review the following information to ensure the GNU Lesser General
16 ** Public License version 2.1 requirements will be met:
17 ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
18 **
19 ** In addition, as a special exception, Nokia gives you certain additional
20 ** rights. These rights are described in the Nokia Qt LGPL Exception
21 ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
22 **
23 ** Other Usage
24 **
25 ** Alternatively, this file may be used in accordance with the terms and
26 ** conditions contained in a signed written agreement between you and Nokia.
27 **
28 ** If you have questions regarding the use of this file, please contact
29 ** Nokia at qt-info@nokia.com.
30 **
31 **************************************************************************/
32
33 #include "cppfindreferences.h"
34 #include "cpptoolsconstants.h"
35
36 #include <texteditor/basetexteditor.h>
37 #include <texteditor/basefilefind.h>
38 #include <find/searchresultwindow.h>
39 #include <extensionsystem/pluginmanager.h>
40 #include <utils/filesearch.h>
41 #include <coreplugin/progressmanager/progressmanager.h>
42 #include <coreplugin/progressmanager/futureprogress.h>
43 #include <coreplugin/editormanager/editormanager.h>
44 #include <coreplugin/icore.h>
45
46 #include <ASTVisitor.h>
47 #include <AST.h>
48 #include <Control.h>
49 #include <Literals.h>
50 #include <TranslationUnit.h>
51 #include <Symbols.h>
52 #include <Names.h>
53 #include <Scope.h>
54
55 #include <cplusplus/ModelManagerInterface.h>
56 #include <cplusplus/CppDocument.h>
57 #include <cplusplus/Overview.h>
58 #include <cplusplus/FindUsages.h>
59
60 #include <QtCore/QTime>
61 #include <QtCore/QTimer>
62 #include <QtCore/QtConcurrentRun>
63 #include <QtCore/QtConcurrentMap>
64 #include <QtCore/QDir>
65 #include <QtGui/QApplication>
66 #include <qtconcurrent/runextensions.h>
67
68 #include <functional>
69
70 using namespace CppTools::Internal;
71 using namespace CPlusPlus;
72
73 static QString getSource(const QString &fileName,
74                          const CppModelManagerInterface::WorkingCopy &workingCopy)
75 {
76     if (workingCopy.contains(fileName)) {
77         return workingCopy.source(fileName);
78     } else {
79         QFile file(fileName);
80         if (! file.open(QFile::ReadOnly))
81             return QString();
82
83         return QTextStream(&file).readAll(); // ### FIXME
84     }
85 }
86
87 namespace {
88
89 class ProcessFile: public std::unary_function<QString, QList<Usage> >
90 {
91     const CppModelManagerInterface::WorkingCopy workingCopy;
92     const Snapshot snapshot;
93     Document::Ptr symbolDocument;
94     Symbol *symbol;
95
96 public:
97     ProcessFile(const CppModelManagerInterface::WorkingCopy &workingCopy,
98                 const Snapshot snapshot,
99                 Document::Ptr symbolDocument,
100                 Symbol *symbol)
101         : workingCopy(workingCopy), snapshot(snapshot), symbolDocument(symbolDocument), symbol(symbol)
102     { }
103
104     QList<Usage> operator()(const QString &fileName)
105     {
106         QList<Usage> usages;
107         const Identifier *symbolId = symbol->identifier();
108
109         if (Document::Ptr previousDoc = snapshot.document(fileName)) {
110             Control *control = previousDoc->control();
111             if (! control->findIdentifier(symbolId->chars(), symbolId->size()))
112                 return usages; // skip this document, it's not using symbolId.
113         }
114
115         Document::Ptr doc;
116         QByteArray source;
117         const QString unpreprocessedSource = getSource(fileName, workingCopy);
118
119         if (symbolDocument && fileName == symbolDocument->fileName())
120             doc = symbolDocument;
121         else {
122             source = snapshot.preprocessedCode(unpreprocessedSource, fileName);
123             doc = snapshot.documentFromSource(source, fileName);
124             doc->tokenize();
125         }
126
127         Control *control = doc->control();
128         if (control->findIdentifier(symbolId->chars(), symbolId->size()) != 0) {
129             if (doc != symbolDocument)
130                 doc->check();
131
132             FindUsages process(unpreprocessedSource.toUtf8(), doc, snapshot);
133             process(symbol);
134
135             usages = process.usages();
136         }
137
138         return usages;
139     }
140 };
141
142 class UpdateUI: public std::binary_function<QList<Usage> &, QList<Usage>, void>
143 {
144     QFutureInterface<Usage> *future;
145
146 public:
147     UpdateUI(QFutureInterface<Usage> *future): future(future) {}
148
149     void operator()(QList<Usage> &, const QList<Usage> &usages)
150     {
151         foreach (const Usage &u, usages)
152             future->reportResult(u);
153
154         future->setProgressValue(future->progressValue() + 1);
155     }
156 };
157
158 } // end of anonymous namespace
159
160 CppFindReferences::CppFindReferences(CppModelManagerInterface *modelManager)
161     : QObject(modelManager),
162       _modelManager(modelManager),
163       _resultWindow(Find::SearchResultWindow::instance())
164 {
165     m_watcher.setPendingResultsLimit(1);
166     connect(&m_watcher, SIGNAL(resultsReadyAt(int,int)), this, SLOT(displayResults(int,int)));
167     connect(&m_watcher, SIGNAL(finished()), this, SLOT(searchFinished()));
168 }
169
170 CppFindReferences::~CppFindReferences()
171 {
172 }
173
174 QList<int> CppFindReferences::references(Symbol *symbol, const LookupContext &context) const
175 {
176     QList<int> references;
177
178     FindUsages findUsages(context);
179     findUsages(symbol);
180     references = findUsages.references();
181
182     return references;
183 }
184
185 static void find_helper(QFutureInterface<Usage> &future,
186                         const CppModelManagerInterface::WorkingCopy workingCopy,
187                         const LookupContext context,
188                         CppFindReferences *findRefs,
189                         Symbol *symbol)
190 {
191     const Identifier *symbolId = symbol->identifier();
192     Q_ASSERT(symbolId != 0);
193
194     const Snapshot snapshot = context.snapshot();
195
196     const QString sourceFile = QString::fromUtf8(symbol->fileName(), symbol->fileNameLength());
197     QStringList files(sourceFile);
198
199     if (symbol->isClass() || symbol->isForwardClassDeclaration() || (symbol->enclosingScope() && ! symbol->isStatic() &&
200                                                                      symbol->enclosingScope()->isNamespace())) {
201         foreach (const Document::Ptr &doc, context.snapshot()) {
202             if (doc->fileName() == sourceFile)
203                 continue;
204
205             Control *control = doc->control();
206
207             if (control->findIdentifier(symbolId->chars(), symbolId->size()))
208                 files.append(doc->fileName());
209         }
210     } else {
211         DependencyTable dependencyTable = findRefs->updateDependencyTable(snapshot);
212         files += dependencyTable.filesDependingOn(sourceFile);
213     }
214     files.removeDuplicates();
215
216     future.setProgressRange(0, files.size());
217
218     ProcessFile process(workingCopy, snapshot, context.thisDocument(), symbol);
219     UpdateUI reduce(&future);
220
221     QtConcurrent::blockingMappedReduced<QList<Usage> > (files, process, reduce);
222
223     future.setProgressValue(files.size());
224 }
225
226 void CppFindReferences::findUsages(CPlusPlus::Symbol *symbol, const CPlusPlus::LookupContext &context)
227 {
228     Find::SearchResult *search = _resultWindow->startNewSearch(Find::SearchResultWindow::SearchOnly);
229
230     connect(search, SIGNAL(activated(Find::SearchResultItem)),
231             this, SLOT(openEditor(Find::SearchResultItem)));
232
233     findAll_helper(symbol, context);
234 }
235
236 void CppFindReferences::renameUsages(CPlusPlus::Symbol *symbol, const CPlusPlus::LookupContext &context,
237                                      const QString &replacement)
238 {
239     if (const Identifier *id = symbol->identifier()) {
240         const QString textToReplace = replacement.isEmpty()
241                 ? QString::fromUtf8(id->chars(), id->size()) : replacement;
242
243         Find::SearchResult *search = _resultWindow->startNewSearch(Find::SearchResultWindow::SearchAndReplace);
244         _resultWindow->setTextToReplace(textToReplace);
245
246         connect(search, SIGNAL(activated(Find::SearchResultItem)),
247                 this, SLOT(openEditor(Find::SearchResultItem)));
248
249         connect(search, SIGNAL(replaceButtonClicked(QString,QList<Find::SearchResultItem>)),
250                 SLOT(onReplaceButtonClicked(QString,QList<Find::SearchResultItem>)));
251
252         findAll_helper(symbol, context);
253     }
254 }
255
256 void CppFindReferences::findAll_helper(Symbol *symbol, const LookupContext &context)
257 {
258     if (! (symbol && symbol->identifier()))
259         return;
260
261     _resultWindow->popup(true);
262
263     const CppModelManagerInterface::WorkingCopy workingCopy = _modelManager->workingCopy();
264
265     Core::ProgressManager *progressManager = Core::ICore::instance()->progressManager();
266
267     QFuture<Usage> result;
268
269     result = QtConcurrent::run(&find_helper, workingCopy, context, this, symbol);
270     m_watcher.setFuture(result);
271
272     Core::FutureProgress *progress = progressManager->addTask(result, tr("Searching"),
273                                                               CppTools::Constants::TASK_SEARCH);
274
275     connect(progress, SIGNAL(clicked()), _resultWindow, SLOT(popup()));
276 }
277
278 void CppFindReferences::onReplaceButtonClicked(const QString &text,
279                                                const QList<Find::SearchResultItem> &items)
280 {
281     Core::EditorManager::instance()->hideEditorInfoBar(QLatin1String("CppEditor.Rename"));
282
283     const QStringList fileNames = TextEditor::BaseFileFind::replaceAll(text, items);
284     if (!fileNames.isEmpty()) {
285         _modelManager->updateSourceFiles(fileNames);
286         _resultWindow->hide();
287     }
288 }
289
290 void CppFindReferences::displayResults(int first, int last)
291 {
292     for (int index = first; index != last; ++index) {
293         Usage result = m_watcher.future().resultAt(index);
294         _resultWindow->addResult(result.path,
295                                  result.line,
296                                  result.lineText,
297                                  result.col,
298                                  result.len);
299     }
300 }
301
302 void CppFindReferences::searchFinished()
303 {
304     _resultWindow->finishSearch();
305     emit changed();
306 }
307
308 void CppFindReferences::openEditor(const Find::SearchResultItem &item)
309 {
310     if (item.path.size() > 0) {
311         TextEditor::BaseTextEditorWidget::openEditorAt(item.path.first(), item.lineNumber, item.textMarkPos,
312                                                  QString(),
313                                                  Core::EditorManager::ModeSwitch);
314     } else {
315         Core::EditorManager::instance()->openEditor(item.text, QString(), Core::EditorManager::ModeSwitch);
316     }
317 }
318
319
320 namespace {
321
322 class FindMacroUsesInFile: public std::unary_function<QString, QList<Usage> >
323 {
324     const CppModelManagerInterface::WorkingCopy workingCopy;
325     const Snapshot snapshot;
326     const Macro &macro;
327
328 public:
329     FindMacroUsesInFile(const CppModelManagerInterface::WorkingCopy &workingCopy,
330                         const Snapshot snapshot,
331                         const Macro &macro)
332         : workingCopy(workingCopy), snapshot(snapshot), macro(macro)
333     { }
334
335     QList<Usage> operator()(const QString &fileName)
336     {
337         QList<Usage> usages;
338
339         const Document::Ptr &doc = snapshot.document(fileName);
340         QByteArray source;
341
342         foreach (const Document::MacroUse &use, doc->macroUses()) {
343             const Macro &useMacro = use.macro();
344             if (useMacro.line() == macro.line()
345                 && useMacro.fileName() == macro.fileName())
346                 {
347                 if (source.isEmpty())
348                     source = getSource(fileName, workingCopy).toLatin1(); // ### FIXME: Encoding?
349
350                 unsigned lineStart;
351                 const QString &lineSource = matchingLine(use.begin(), source, &lineStart);
352                 usages.append(Usage(fileName, lineSource, use.beginLine(),
353                                     use.begin() - lineStart, use.length()));
354             }
355         }
356
357         return usages;
358     }
359
360     // ### FIXME: Pretty close to FindUsages::matchingLine.
361     static QString matchingLine(unsigned position, const QByteArray &source,
362                                 unsigned *lineStart = 0)
363     {
364         const char *beg = source.constData();
365         const char *start = beg + position;
366         for (; start != beg - 1; --start) {
367             if (*start == '\n')
368                 break;
369         }
370
371         ++start;
372
373         const char *end = start + 1;
374         for (; *end; ++end) {
375             if (*end == '\n')
376                 break;
377         }
378
379         if (lineStart)
380             *lineStart = start - beg;
381
382         // ### FIXME: Encoding?
383         const QString matchingLine = QString::fromUtf8(start, end - start);
384         return matchingLine;
385     }
386 };
387
388 } // end of anonymous namespace
389
390 static void findMacroUses_helper(QFutureInterface<Usage> &future,
391                                  const CppModelManagerInterface::WorkingCopy workingCopy,
392                                  const Snapshot snapshot,
393                                  CppFindReferences *findRefs,
394                                  const Macro macro)
395 {
396     // ensure the dependency table is updated
397     DependencyTable dependencies = findRefs->updateDependencyTable(snapshot);
398
399     const QString& sourceFile = macro.fileName();
400     QStringList files(sourceFile);
401     files += dependencies.filesDependingOn(sourceFile);
402     files.removeDuplicates();
403
404     future.setProgressRange(0, files.size());
405
406     FindMacroUsesInFile process(workingCopy, snapshot, macro);
407     UpdateUI reduce(&future);
408     QtConcurrent::blockingMappedReduced<QList<Usage> > (files, process, reduce);
409
410     future.setProgressValue(files.size());
411 }
412
413 void CppFindReferences::findMacroUses(const Macro &macro)
414 {
415     Find::SearchResult *search = _resultWindow->startNewSearch(Find::SearchResultWindow::SearchOnly);
416
417     _resultWindow->popup(true);
418
419     connect(search, SIGNAL(activated(Find::SearchResultItem)),
420             this, SLOT(openEditor(Find::SearchResultItem)));
421
422     const Snapshot snapshot = _modelManager->snapshot();
423     const CppModelManagerInterface::WorkingCopy workingCopy = _modelManager->workingCopy();
424
425     // add the macro definition itself
426     {
427         // ### FIXME: Encoding?
428         const QByteArray &source = getSource(macro.fileName(), workingCopy).toLatin1();
429         _resultWindow->addResult(macro.fileName(), macro.line(),
430                                  source.mid(macro.offset(), macro.length()), 0, macro.length());
431     }
432
433     QFuture<Usage> result;
434     result = QtConcurrent::run(&findMacroUses_helper, workingCopy, snapshot, this, macro);
435     m_watcher.setFuture(result);
436
437     Core::ProgressManager *progressManager = Core::ICore::instance()->progressManager();
438     Core::FutureProgress *progress = progressManager->addTask(result, tr("Searching"),
439                                                               CppTools::Constants::TASK_SEARCH);
440     connect(progress, SIGNAL(clicked()), _resultWindow, SLOT(popup()));
441 }
442
443 DependencyTable CppFindReferences::updateDependencyTable(CPlusPlus::Snapshot snapshot)
444 {
445     DependencyTable oldDeps = dependencyTable();
446     if (oldDeps.isValidFor(snapshot))
447         return oldDeps;
448
449     DependencyTable newDeps;
450     newDeps.build(snapshot);
451     setDependencyTable(newDeps);
452     return newDeps;
453 }
454
455 DependencyTable CppFindReferences::dependencyTable() const
456 {
457     QMutexLocker locker(&m_depsLock);
458     Q_UNUSED(locker);
459     return m_deps;
460 }
461
462 void CppFindReferences::setDependencyTable(const CPlusPlus::DependencyTable &newTable)
463 {
464     QMutexLocker locker(&m_depsLock);
465     Q_UNUSED(locker);
466     m_deps = newTable;
467 }