Debian Codegraph @

CodeLite/ctags_manager.cpp

raw
1 //////////////////////////////////////////////////////////////////////////////
2 //////////////////////////////////////////////////////////////////////////////
3 //
4 // copyright : (C) 2008 by Eran Ifrah
5 // file name : ctags_manager.cpp
6 //
7 // -------------------------------------------------------------------------
8 // A
9 // _____ _ _ _ _
10 // / __ \ | | | | (_) |
11 // | / \/ ___ __| | ___| | _| |_ ___
12 // | | / _ \ / _ |/ _ \ | | | __/ _ )
13 // | \__/\ (_) | (_| | __/ |___| | || __/
14 // \____/\___/ \__,_|\___\_____/_|\__\___|
15 //
16 // F i l e
17 //
18 // This program is free software; you can redistribute it and/or modify
19 // it under the terms of the GNU General Public License as published by
20 // the Free Software Foundation; either version 2 of the License, or
21 // (at your option) any later version.
22 //
23 //////////////////////////////////////////////////////////////////////////////
24 //////////////////////////////////////////////////////////////////////////////
25 #include "ctags_manager.h"
26
27 #include "CTags.hpp"
28 #include "CxxTemplateFunction.h"
29 #include "CxxVariable.h"
30 #include "CxxVariableScanner.h"
31 #include "asyncprocess.h"
32 #include "cl_command_event.h"
33 #include "cl_standard_paths.h"
34 #include "code_completion_api.h"
35 #include "codelite_events.h"
36 #include "codelite_exports.h"
37 #include "cpp_comment_creator.h"
38 #include "cppwordscanner.h"
39 #include "event_notifier.h"
40 #include "file_logger.h"
41 #include "fileextmanager.h"
42 #include "fileutils.h"
43 #include "precompiled_header.h"
44 #include "processreaderthread.h"
45 #include "procutils.h"
46 #include "tags_options_data.h"
47 #include "tags_storage_sqlite3.h"
48 #include "wx/filename.h"
49 #include "wx/timer.h"
50 #include "wx/tokenzr.h"
51 #include "wxStringHash.h"
52
53 #include <algorithm>
54 #include <set>
55 #include <sstream>
56 #include <wx/app.h>
57 #include <wx/busyinfo.h>
58 #include <wx/file.h>
59 #if wxUSE_GUI
60 #include <wx/frame.h>
61 #include <wx/msgdlg.h>
62 #include <wx/progdlg.h>
63 #include <wx/sizer.h>
64 #include <wx/xrc/xmlres.h>
65 #endif
66 #include <wx/log.h>
67 #include <wx/stdpaths.h>
68 #include <wx/string.h>
69 #include <wx/txtstrm.h>
70 #include <wx/wfstream.h>
71
72 //#define __PERFORMANCE
73 #include "performance.h"
74
75 //---------------------------------------------------------------------------
76 // Misc
77
78 // Descending sorting function
79 struct SDescendingSort {
80 bool operator()(const TagEntryPtr& rStart, const TagEntryPtr& rEnd)
81 {
82 return rStart->GetName().CmpNoCase(rEnd->GetName()) > 0;
83 }
84 };
85
86 /// Ascending sorting function
87 struct SAscendingSort {
88 bool operator()(const TagEntryPtr& rStart, const TagEntryPtr& rEnd)
89 {
90 return rEnd->GetName().CmpNoCase(rStart->GetName()) > 0;
91 }
92 };
93
94 struct tagParseResult {
95 TagTreePtr tree;
96 std::vector<CommentPtr>* comments;
97 wxString fileName;
98 };
99
100 //////////////////////////////////////
101 // Adapter class to TagsManager
102 //////////////////////////////////////
103 static TagsManager* gs_TagsManager = NULL;
104
105 void TagsManagerST::Free()
106 {
107 if(gs_TagsManager) {
108 delete gs_TagsManager;
109 }
110 gs_TagsManager = NULL;
111 }
112
113 TagsManager* TagsManagerST::Get()
114 {
115 if(gs_TagsManager == NULL)
116 gs_TagsManager = new TagsManager();
117
118 return gs_TagsManager;
119 }
120
121 //------------------------------------------------------------------------------
122 // CTAGS Manager
123 //------------------------------------------------------------------------------
124
125 TagsManager::TagsManager()
126 : wxEvtHandler()
127 , m_lang(NULL)
128 , m_evtHandler(NULL)
129 , m_encoding(wxFONTENCODING_DEFAULT)
130 {
131 m_db = new TagsStorageSQLite();
132 m_db->SetSingleSearchLimit(MAX_SEARCH_LIMIT);
133
134 // CPP keywords that are usually followed by open brace '('
135 m_CppIgnoreKeyWords.insert(wxT("while"));
136 m_CppIgnoreKeyWords.insert(wxT("if"));
137 m_CppIgnoreKeyWords.insert(wxT("for"));
138 m_CppIgnoreKeyWords.insert(wxT("switch"));
139 }
140
141 TagsManager::~TagsManager() {}
142
143 void TagsManager::OpenDatabase(const wxFileName& fileName)
144 {
145 m_dbFile = fileName;
146 m_db->OpenDatabase(m_dbFile);
147 m_db->SetEnableCaseInsensitive(true);
148 m_db->SetSingleSearchLimit(m_tagsOptions.GetCcNumberOfDisplayItems());
149 }
150
151 TagTreePtr TagsManager::ParseSourceFile2(const wxFileName& fp, const wxString& tags, std::vector<CommentPtr>* comments)
152 {
153 // return ParseTagsFile(tags, project);
154 int count(0);
155 TagTreePtr ttp = TagTreePtr(TreeFromTags(tags, count));
156
157 if(comments && GetParseComments()) {
158 // parse comments
159 GetLanguage()->ParseComments(fp, comments);
160 }
161 return ttp;
162 }
163
164 //-----------------------------------------------------------
165 // Database operations
166 //-----------------------------------------------------------
167
168 TagTreePtr TagsManager::Load(const wxFileName& fileName, TagEntryPtrVector_t* tags)
169 {
170 TagTreePtr tree;
171 TagEntryPtrVector_t tagsByFile;
172
173 if(tags) {
174 tagsByFile.insert(tagsByFile.end(), tags->begin(), tags->end());
175
176 } else {
177 GetDatabase()->SelectTagsByFile(fileName.GetFullPath(), tagsByFile);
178 }
179
180 // Load the records and build a language tree
181 TagEntry root;
182 root.SetName(wxT("<ROOT>"));
183 tree.Reset(new TagTree(wxT("<ROOT>"), root));
184 for(size_t i = 0; i < tagsByFile.size(); i++) {
185 tree->AddEntry(*(tagsByFile.at(i)));
186 }
187 return tree;
188 }
189
190 void TagsManager::Delete(const wxFileName& path, const wxString& fileName)
191 {
192 GetDatabase()->DeleteByFileName(path, fileName);
193 }
194
195 //---------------------------------------------------------------------
196 // Parsing
197 //---------------------------------------------------------------------
198 TagTreePtr TagsManager::TreeFromTags(const wxArrayString& tags, int& count)
199 {
200 // Load the records and build a language tree
201 TagEntry root;
202 root.SetName(wxT("<ROOT>"));
203
204 TagTreePtr tree(new TagTree(wxT("<ROOT>"), root));
205
206 for(const wxString& line : tags) {
207 TagEntry tag;
208
209 // Construct the tag from the line
210 tag.FromLine(line);
211
212 // Add the tag to the tree, locals are not added to the
213 // tree
214 if(tag.GetKind() != wxT("local")) {
215 count++;
216 tree->AddEntry(tag);
217 }
218 }
219 return tree;
220 }
221
222 TagTreePtr TagsManager::TreeFromTags(const wxString& tags, int& count)
223 {
224 // Load the records and build a language tree
225 wxArrayString lines = ::wxStringTokenize(tags, "\r\n", wxTOKEN_STRTOK);
226 return TreeFromTags(lines, count);
227 }
228
229 bool TagsManager::IsValidCtagsFile(const wxFileName& filename) const
230 {
231 wxLogNull PreventMissingFileLogErrorMessages;
232 return FileExtManager::IsCxxFile(filename) || FileUtils::WildMatch(m_tagsOptions.GetFileSpec(), filename);
233 }
234
235 //-----------------------------------------------------------------------------
236 // >>>>>>>>>>>>>>>>>>>>> Code Completion API START
237 //-----------------------------------------------------------------------------
238
239 void TagsManager::TagsByScopeAndName(const wxString& scope, const wxString& name, std::vector<TagEntryPtr>& tags,
240 size_t flags)
241 {
242 std::vector<std::pair<wxString, int>> derivationList;
243 // add this scope as well to the derivation list
244
245 wxString _scopeName = DoReplaceMacros(scope);
246 derivationList.push_back({ _scopeName, 0 });
247 std::unordered_set<wxString> visited;
248 GetDerivationList(_scopeName, NULL, derivationList, visited, 1);
249
250 // make enough room for max of 500 elements in the vector
251 tags.reserve(500);
252 wxArrayString scopes;
253
254 for(size_t i = 0; i < derivationList.size(); i++) {
255 // try the worksapce database for match
256 scopes.Add(derivationList.at(i).first);
257 }
258
259 GetDatabase()->GetTagsByScopeAndName(scopes, name, flags & PartialMatch, tags);
260
261 // and finally sort the results
262 std::sort(tags.begin(), tags.end(), SAscendingSort());
263 }
264
265 void TagsManager::TagsByScope(const wxString& scope, std::vector<TagEntryPtr>& tags)
266 {
267 std::vector<std::pair<wxString, int>> derivationList;
268 // add this scope as well to the derivation list
269 wxString _scopeName = DoReplaceMacros(scope);
270 derivationList.push_back({ _scopeName, 0 });
271 std::unordered_set<wxString> visited;
272 GetDerivationList(_scopeName, NULL, derivationList, visited, 1);
273
274 // make enough room for max of 500 elements in the vector
275 tags.reserve(500);
276
277 for(size_t i = 0; i < derivationList.size(); i++) {
278 wxString tmpScope(derivationList.at(i).first);
279 tmpScope = DoReplaceMacros(tmpScope);
280
281 // try the external database for match
282 GetDatabase()->GetTagsByScope(derivationList.at(i).first, tags);
283 }
284
285 // and finally sort the results
286 std::sort(tags.begin(), tags.end(), SAscendingSort());
287 }
288
289 void TagsManager::DoFilterDuplicatesBySignature(std::vector<TagEntryPtr>& src, std::vector<TagEntryPtr>& target)
290 {
291 // filter out all entries with the same signature (we do keep declaration overa an implenetation
292 // since usually the declaration contains more useful information)
293 std::map<wxString, TagEntryPtr> others, impls;
294
295 for(size_t i = 0; i < src.size(); i++) {
296 const TagEntryPtr& t = src.at(i);
297 if(t->IsMethod()) {
298 wxString strippedSignature = NormalizeFunctionSig(t->GetSignature(), 0);
299 strippedSignature.Prepend(t->GetName());
300
301 if(t->IsPrototype()) {
302 // keep declaration in the output map
303 others[strippedSignature] = t;
304 } else {
305 // keep the signature in a different map
306 impls[strippedSignature] = t;
307 }
308 } else {
309 // keep all other entries
310 others[t->GetName()] = t;
311 }
312 }
313
314 // unified the two multimaps
315 std::map<wxString, TagEntryPtr>::iterator iter = impls.begin();
316 for(; iter != impls.end(); iter++) {
317 if(others.find(iter->first) == others.end()) {
318 others[iter->first] = iter->second;
319 }
320 }
321
322 target.clear();
323 // convert the map into vector
324 iter = others.begin();
325 for(; iter != others.end(); iter++) {
326 target.push_back(iter->second);
327 }
328 }
329
330 void TagsManager::DoFilterDuplicatesByTagID(std::vector<TagEntryPtr>& src, std::vector<TagEntryPtr>& target)
331 {
332 std::map<int, TagEntryPtr> mapTags;
333 std::map<wxString, TagEntryPtr> localTags;
334
335 for(size_t i = 0; i < src.size(); i++) {
336 const TagEntryPtr& t = src.at(i);
337 int tagId = t->GetId();
338 if(t->GetParent() == wxT("<local>")) {
339 if(localTags.find(t->GetName()) == localTags.end()) {
340 localTags[t->GetName()] = t;
341 }
342
343 } else if(mapTags.find(tagId) == mapTags.end()) {
344 mapTags[tagId] = t;
345
346 } else {
347 tagId = -1;
348 }
349 }
350
351 // Add the real entries (fetched from the database)
352 std::map<int, TagEntryPtr>::iterator iter = mapTags.begin();
353 for(; iter != mapTags.end(); iter++) {
354 target.push_back(iter->second);
355 }
356
357 // Add the locals (collected from the current scope)
358 std::map<wxString, TagEntryPtr>::iterator iter2 = localTags.begin();
359 for(; iter2 != localTags.end(); iter2++) {
360 target.push_back(iter2->second);
361 }
362 }
363
364 void TagsManager::RemoveDuplicatesTips(std::vector<TagEntryPtr>& src, std::vector<TagEntryPtr>& target)
365 {
366 std::map<wxString, TagEntryPtr> unique_tags;
367
368 for(size_t i = 0; i < src.size(); i++) {
369
370 wxString raw_sig(src.at(i)->GetSignature().Trim().Trim(false));
371 wxString sig;
372 if(raw_sig.empty() == false) {
373 sig = NormalizeFunctionSig(raw_sig, 0);
374 }
375
376 // the signature that we want to keep is one with name & default values, so try and get the maximum out of the
377 // function signature
378 bool hasDefaultValues = (raw_sig.Find(wxT("=")) != wxNOT_FOUND);
379
380 wxString name = src.at(i)->GetName();
381 wxString key = name + sig;
382
383 std::map<wxString, TagEntryPtr>::iterator iter = unique_tags.find(key);
384 if(iter == unique_tags.end()) {
385 // does not exist
386 unique_tags[key] = src.at(i);
387 } else {
388 // an entry with this key already exist
389 if(hasDefaultValues) {
390 // this entry has a default values, it means that we probably prefer this signature over the other
391 TagEntryPtr t = iter->second;
392 t->SetSignature(raw_sig);
393 unique_tags[key] = t;
394 }
395 }
396 }
397
398 // conver the map back to std::vector
399 std::map<wxString, TagEntryPtr>::iterator iter = unique_tags.begin();
400 target.clear();
401
402 for(; iter != unique_tags.end(); iter++) {
403 target.push_back(iter->second);
404 }
405 }
406
407 void TagsManager::GetGlobalTags(const wxString& name, std::vector<TagEntryPtr>& tags, size_t flags)
408 {
409 // Make enough room for max of 500 elements in the vector
410 tags.reserve(500);
411 GetDatabase()->GetTagsByScopeAndName(wxT("<global>"), name, flags & PartialMatch, tags);
412 std::sort(tags.begin(), tags.end(), SAscendingSort());
413 }
414
415 void TagsManager::GetLocalTags(const wxString& name, const wxString& scope, std::vector<TagEntryPtr>& tags,
416 bool isFuncSignature, size_t flags)
417 {
418 // collect tags from the current scope text
419 GetLanguage()->GetLocalVariables(scope, tags, isFuncSignature, name, flags);
420 }
421
422 void TagsManager::GetHoverTip(const wxFileName& fileName, int lineno, const wxString& expr, const wxString& word,
423 const wxString& text, std::vector<wxString>& tips)
424 {
425 wxString path;
426 wxString typeName, typeScope, tmp;
427 std::vector<TagEntryPtr> tmpCandidates, candidates;
428
429 // remove the word from the expression
430 wxString expression(expr);
431
432 // Trim whitespace from right and left
433 static wxString trimLeftString(wxT("{};\r\n\t\v "));
434 static wxString trimRightString(wxT("({};\r\n\t\v "));
435 expression.erase(0, expression.find_first_not_of(trimLeftString));
436 expression.erase(expression.find_last_not_of(trimRightString) + 1);
437
438 tmp = expression;
439 expression.EndsWith(word, &tmp);
440 tmp.Trim().Trim(false);
441 expression = tmp;
442
443 wxString curFunctionBody;
444 wxString scope = GetLanguage()->OptimizeScope(text, -1, curFunctionBody);
445 wxString scopeName = GetLanguage()->GetScopeName(scope, NULL);
446 if(expression.IsEmpty()) {
447 // collect all the tags from the current scope, and
448 // from the global scope
449
450 GetGlobalTags(word, tmpCandidates, ExactMatch);
451 GetLocalTags(word, scope, tmpCandidates, false, ExactMatch);
452 TagsByScopeAndName(scopeName, word, tmpCandidates);
453 RemoveDuplicatesTips(tmpCandidates, candidates);
454
455 // we now have a list of tags that matches our word
456 TipsFromTags(candidates, word, tips);
457 } else if(expression == "::") {
458 // global scope resolution operator
459
460 GetGlobalTags(word, candidates, ExactMatch);
461 TipsFromTags(candidates, word, tips);
462 } else {
463 wxString typeName, typeScope;
464 wxString oper, dummy;
465 bool res = ProcessExpression(fileName, lineno, expression, text, typeName, typeScope, oper, dummy);
466 if(!res) {
467 return;
468 }
469
470 // get all symbols realted to this scope
471 scope = wxT("");
472 if(typeScope == wxT("<global>"))
473 scope << typeName;
474 else
475 scope << typeScope << wxT("::") << typeName;
476
477 std::vector<TagEntryPtr> tmpCandidates;
478 TagsByScopeAndName(scope, word, tmpCandidates);
479 RemoveDuplicatesTips(tmpCandidates, candidates);
480
481 // we now have a list of tags that matches our word
482 TipsFromTags(candidates, word, tips);
483 }
484 }
485
486 void TagsManager::TryReducingScopes(const wxString& scope, const wxString& word, bool imp,
487 std::vector<TagEntryPtr>& tags)
488 {
489 if(scope == wxT("<global>") || scope.IsEmpty())
490 return;
491
492 // if we are here, it means that the the 'word' was not found in the 'scope'
493 // and we already tried the 'TryFindImplDeclUsingNS' method.
494 // What is left to be done is to reduce the 'scope' until we find a match.
495 // Example:
496 // OuterScope::Foo::Bar::Method()
497 // However the entry in the database is stored only with as 'Bar::Method()'
498 // we will reduce the scope and will try the following scopes:
499 // Foo::Bar
500 // Bar
501 std::vector<wxString> visibleScopes;
502 wxArrayString scopes = wxStringTokenize(scope, wxT(":"), wxTOKEN_STRTOK);
503 for(size_t i = 1; i < scopes.GetCount(); i++) {
504 wxString newScope;
505 for(size_t j = i; j < scopes.GetCount(); j++) {
506 newScope << scopes.Item(j) << wxT("::");
507 }
508 if(newScope.Len() >= 2) {
509 newScope.RemoveLast(2);
510 }
511 visibleScopes.push_back(newScope);
512 }
513 std::vector<TagEntryPtr> tmpCandidates;
514 if(visibleScopes.empty() == false) {
515 for(size_t i = 0; i < visibleScopes.size(); i++) {
516 TagsByScopeAndName(visibleScopes.at(i), word, tmpCandidates, ExactMatch);
517 }
518
519 if(!imp) {
520 // collect only implementation
521 FilterImplementation(tmpCandidates, tags);
522 } else {
523 FilterDeclarations(tmpCandidates, tags);
524 }
525 }
526 }
527
528 void TagsManager::TryFindImplDeclUsingNS(const wxString& scope, const wxString& word, bool imp,
529 const std::vector<wxString>& visibleScopes, std::vector<TagEntryPtr>& tags)
530 {
531 std::vector<TagEntryPtr> tmpCandidates;
532 // if we got here and the tags.empty() is true,
533 // there is another option to try:
534 // sometimes people tend to write code similar to:
535 // using namespace Foo;
536 // void Bar::func(){}
537 // this will make the entry in the tags database to have a scope of 'Bar' without
538 // the Foo scope, however the ProcessExpression() method does take into consideration
539 // the 'using namespace' statement, we attempt to fix this here
540 if(visibleScopes.empty() == false) {
541 tmpCandidates.clear();
542 for(size_t i = 0; i < visibleScopes.size(); i++) {
543 wxString newScope(scope);
544 if(newScope.StartsWith(visibleScopes.at(i) + wxT("::"))) {
545 newScope.Remove(0, visibleScopes.at(i).Len() + 2);
546 }
547 TagsByScopeAndName(newScope, word, tmpCandidates, ExactMatch);
548 }
549
550 if(!imp) {
551 // collect only implementation
552 FilterImplementation(tmpCandidates, tags);
553 } else {
554 FilterDeclarations(tmpCandidates, tags);
555 }
556 }
557 }
558
559 void TagsManager::FilterImplementation(const std::vector<TagEntryPtr>& src, std::vector<TagEntryPtr>& tags)
560 {
561 // remove all implementations and leave only declarations
562 std::map<wxString, TagEntryPtr> tmpMap;
563 for(size_t i = 0; i < src.size(); i++) {
564 TagEntryPtr tag = src.at(i);
565 if(tag->GetKind() != wxT("function")) {
566 wxString key;
567 key << tag->GetFile() << tag->GetLine();
568 tmpMap[key] = tag;
569 }
570 }
571
572 std::map<wxString, TagEntryPtr>::iterator iter = tmpMap.begin();
573 for(; iter != tmpMap.end(); iter++) {
574 tags.push_back(iter->second);
575 }
576 }
577
578 void TagsManager::FilterDeclarations(const std::vector<TagEntryPtr>& src, std::vector<TagEntryPtr>& tags)
579 {
580 std::map<wxString, TagEntryPtr> tmpMap;
581 for(size_t i = 0; i < src.size(); i++) {
582 TagEntryPtr tag = src.at(i);
583 if(tag->GetKind() != wxT("prototype")) {
584 wxString key;
585 key << tag->GetFile() << tag->GetLine();
586 tmpMap[key] = tag;
587 }
588 }
589 std::map<wxString, TagEntryPtr>::iterator iter = tmpMap.begin();
590 for(; iter != tmpMap.end(); iter++) {
591 tags.push_back(iter->second);
592 }
593 }
594
595 //-----------------------------------------------------------------------------
596 // <<<<<<<<<<<<<<<<<<< Code Completion API END
597 //-----------------------------------------------------------------------------
598 void TagsManager::OpenType(std::vector<TagEntryPtr>& tags)
599 {
600 wxArrayString kinds;
601 kinds.Add(wxT("class"));
602 kinds.Add(wxT("namespace"));
603 kinds.Add(wxT("struct"));
604 kinds.Add(wxT("union"));
605 kinds.Add(wxT("enum"));
606 kinds.Add(wxT("typedef"));
607
608 GetDatabase()->GetTagsByKind(kinds, wxT("name"), ITagsStorage::OrderDesc, tags);
609 }
610
611 void TagsManager::FindSymbol(const wxString& name, std::vector<TagEntryPtr>& tags)
612 {
613 // since we dont get a scope, we better user a search that only uses the
614 // name (GetTagsByScopeAndName) is optimized to search the global tags table
615 GetDatabase()->GetTagsByName(name, tags, true);
616 }
617
618 void TagsManager::DeleteFilesTags(const wxArrayString& files)
619 {
620 std::vector<wxFileName> files_;
621 for(size_t i = 0; i < files.GetCount(); i++) {
622 files_.push_back(files.Item(i));
623 }
624 DeleteFilesTags(files_);
625 }
626
627 void TagsManager::DeleteFilesTags(const std::vector<wxFileName>& projectFiles) { wxUnusedVar(projectFiles); }
628
629 void TagsManager::FindByNameAndScope(const wxString& name, const wxString& scope, std::vector<TagEntryPtr>& tags)
630 {
631 wxString _name = DoReplaceMacros(name);
632 wxString _scope = DoReplaceMacros(scope);
633 DoFindByNameAndScope(_name, _scope, tags);
634
635 // Sort the results base on their name
636 std::sort(tags.begin(), tags.end(), SAscendingSort());
637 }
638
639 void TagsManager::FindByPath(const wxString& path, std::vector<TagEntryPtr>& tags)
640 {
641 GetDatabase()->GetTagsByPath(path, tags);
642 }
643
644 void TagsManager::DoFindByNameAndScope(const wxString& name, const wxString& scope, std::vector<TagEntryPtr>& tags)
645 {
646 wxString sql;
647 if(scope == wxT("<global>")) {
648 // try the workspace database for match
649 GetDatabase()->GetTagsByNameAndParent(name, wxT("<global>"), tags);
650 } else {
651 std::vector<std::pair<wxString, int>> derivationList;
652 derivationList.push_back({ scope, 0 });
653 std::unordered_set<wxString> visited;
654 GetDerivationList(scope, NULL, derivationList, visited, 1);
655 wxArrayString paths;
656 for(size_t i = 0; i < derivationList.size(); i++) {
657 wxString path_;
658 path_ << derivationList.at(i).first << wxT("::") << name;
659 paths.Add(path_);
660 }
661
662 // try the workspace database for match
663 GetDatabase()->GetTagsByPath(paths, tags);
664 }
665 }
666
667 bool TagsManager::IsTypeAndScopeContainer(wxString& typeName, wxString& scope)
668 {
669 wxString cacheKey;
670 cacheKey << typeName << wxT("@") << scope;
671
672 // we search the cache first, note that the cache
673 // is used only for the external database
674 std::map<wxString, bool>::iterator iter = m_typeScopeContainerCache.find(cacheKey);
675 if(iter != m_typeScopeContainerCache.end()) {
676 return iter->second;
677 }
678
679 // replace macros:
680 // replace the provided typeName and scope with user defined macros as appeared in the PreprocessorMap
681 wxString _typeName = DoReplaceMacros(typeName);
682 wxString _scope = DoReplaceMacros(scope);
683
684 bool res = GetDatabase()->IsTypeAndScopeContainer(_typeName, _scope);
685 if(res) {
686 typeName = _typeName;
687 scope = _scope;
688 }
689 return res;
690 }
691
692 bool TagsManager::IsTypeAndScopeExists(wxString& typeName, wxString& scope)
693 {
694 wxString cacheKey;
695 cacheKey << typeName << wxT("@") << scope;
696
697 // we search the cache first, note that the cache
698 // is used only for the external database
699 std::map<wxString, bool>::iterator iter = m_typeScopeCache.find(cacheKey);
700 if(iter != m_typeScopeCache.end()) {
701 return iter->second;
702 }
703
704 // First try the fast query to save some time
705 if(GetDatabase()->IsTypeAndScopeExistLimitOne(typeName, scope)) {
706 return true;
707 }
708
709 // replace macros:
710 // replace the provided typeName and scope with user defined macros as appeared in the PreprocessorMap
711 typeName = DoReplaceMacros(typeName);
712 scope = DoReplaceMacros(scope);
713
714 return GetDatabase()->IsTypeAndScopeExist(typeName, scope);
715 }
716
717 bool TagsManager::GetDerivationList(const wxString& path, TagEntryPtr derivedClassTag,
718 std::vector<std::pair<wxString, int>>& derivationList,
719 std::unordered_set<wxString>& visited, int depth)
720 {
721 bool res = GetDerivationListInternal(path, derivedClassTag, derivationList, visited, depth);
722 std::sort(
723 derivationList.begin(), derivationList.end(),
724 [](const std::pair<wxString, size_t>& a, const std::pair<wxString, size_t>& b) { return a.second < b.second; });
725 return res;
726 }
727
728 bool TagsManager::GetDerivationListInternal(const wxString& path, TagEntryPtr derivedClassTag,
729 std::vector<std::pair<wxString, int>>& derivationList,
730 std::unordered_set<wxString>& visited, int depth)
731 {
732 std::vector<TagEntryPtr> tags;
733 TagEntryPtr tag;
734
735 wxArrayString kind;
736 kind.Add(wxT("class"));
737 kind.Add(wxT("struct"));
738
739 GetDatabase()->GetTagsByKindAndPath(kind, path, tags);
740
741 if(tags.size() == 1) {
742 tag = tags.at(0);
743 } else {
744 return false;
745 }
746
747 if(tag && tag->IsOk()) {
748
749 // Get the template instantiation list from the child class
750 wxArrayString ineheritsList = tag->GetInheritsAsArrayNoTemplates();
751
752 wxString templateInstantiationLine;
753 if(derivedClassTag) {
754 wxArrayString p_ineheritsListT = derivedClassTag->GetInheritsAsArrayWithTemplates();
755 wxArrayString p_ineheritsList = derivedClassTag->GetInheritsAsArrayNoTemplates();
756
757 for(size_t i = 0; i < p_ineheritsList.GetCount(); i++) {
758 if(p_ineheritsList.Item(i) == tag->GetName()) {
759 templateInstantiationLine = p_ineheritsListT.Item(i);
760 templateInstantiationLine = templateInstantiationLine.AfterFirst(wxT('<'));
761 templateInstantiationLine.Prepend(wxT("<"));
762 break;
763 }
764 }
765 }
766
767 for(size_t i = 0; i < ineheritsList.GetCount(); i++) {
768 wxString inherits = ineheritsList.Item(i);
769 wxString tagName = tag->GetName();
770 wxString tmpInhr = inherits;
771
772 bool isTempplate = (tag->GetPattern().Find(wxT("template")) != wxNOT_FOUND);
773 tagName.MakeLower();
774 tmpInhr.MakeLower();
775
776 // Make sure that inherits != the current name or we will end up in an infinite loop
777 if(tmpInhr != tagName) {
778 wxString possibleScope(wxT("<global>"));
779
780 // if the 'inherits' already contains a scope
781 // dont attempt to fix it
782 if(inherits.Contains(wxT("::")) == false) {
783
784 // Correc the type/scope
785 bool testForTemplate = !IsTypeAndScopeExists(inherits, possibleScope);
786
787 // If the type does not exists, check for templates
788 if(testForTemplate && derivedClassTag && isTempplate) {
789 TemplateHelper th;
790
791 // e.g. template<typename T> class MyClass
792 wxArrayString templateArgs = GetLanguage()->DoExtractTemplateDeclarationArgs(tag);
793 th.SetTemplateDeclaration(templateArgs); // <typename T>
794 th.SetTemplateInstantiation(templateInstantiationLine); // e.g. MyClass<wxString>
795
796 wxString newType = th.Substitute(inherits);
797
798 // Locate the new type by name in the database
799 // this is done to make sure that the new type is not a macro...
800 if(!newType.IsEmpty() && newType != inherits) {
801
802 // check the user defined types for a replcement token
803 wxString replacement = DoReplaceMacros(newType);
804 if(replacement == newType) {
805 // No match was found in the user defined replacements
806 // try the database
807 replacement = DoReplaceMacrosFromDatabase(newType);
808 }
809 inherits = replacement;
810 }
811 }
812
813 if(possibleScope != wxT("<global>")) {
814 inherits = possibleScope + wxT("::") + inherits;
815 }
816 }
817
818 // Make sure that this parent was not scanned already
819 if(visited.count(inherits) == 0) {
820 visited.insert(inherits);
821 derivationList.push_back({ inherits, depth });
822 GetDerivationList(inherits, tag, derivationList, visited, depth + 1);
823 }
824 }
825 }
826 }
827 return true;
828 }
829
830 void TagsManager::TipsFromTags(const std::vector<TagEntryPtr>& tags, const wxString& word, std::vector<wxString>& tips)
831 {
832 }
833
834 void TagsManager::GetFunctionTipFromTags(const std::vector<TagEntryPtr>& tags, const wxString& word,
835 std::vector<TagEntryPtr>& tips)
836 {
837 std::map<wxString, TagEntryPtr> tipsMap;
838 std::vector<TagEntryPtr> ctor_tags;
839
840 for(size_t i = 0; i < tags.size(); i++) {
841 if(tags.at(i)->GetName() != word)
842 continue;
843
844 TagEntryPtr t;
845 TagEntryPtr curtag = tags.at(i);
846
847 // try to replace the current tag with a macro replacement.
848 // we dont temper with 'curtag' content since we dont want
849 // to modify cached items
850 t = curtag->ReplaceSimpleMacro();
851 if(!t) {
852 t = curtag;
853 }
854
855 wxString pat = t->GetPattern();
856
857 if(t->IsMethod()) {
858 wxString tip;
859 tip << wxT("function:") << t->GetSignature();
860
861 // collect each signature only once, we do this by using
862 // map
863 tipsMap[tip] = t;
864
865 } else if(t->IsClass()) {
866
867 // this tag is a class declaration that matches the word
868 // user is probably is typing something like
869 // Class *a = new Class(
870 // or even Class a = Class(
871 // the steps to take from here:
872 // - lookup in the tables for tags that matches path of: WordScope::Word::Word and of type
873 // prototype/function
874 wxString scope;
875 if(t->GetScope().IsEmpty() == false && t->GetScope() != wxT("<global>")) {
876 scope << t->GetScope() << wxT("::");
877 }
878
879 scope << t->GetName();
880 ctor_tags.clear();
881 TagsByScopeAndName(scope, t->GetName(), ctor_tags, ExactMatch);
882
883 for(size_t i = 0; i < ctor_tags.size(); i++) {
884 TagEntryPtr ctor_tag = ctor_tags.at(i);
885 if(ctor_tag->IsMethod()) {
886 wxString tip;
887 tip << wxT("function:") << ctor_tag->GetSignature();
888 tipsMap[ctor_tag->GetSignature()] = ctor_tag;
889 }
890 }
891
892 } else if(t->IsMacro()) {
893
894 wxString tip;
895 wxString macroName = t->GetName();
896 wxString pattern = t->GetPattern();
897
898 int where = pattern.Find(macroName);
899 if(where != wxNOT_FOUND) {
900 // remove the #define <name> from the pattern
901 pattern = pattern.Mid(where + macroName.Length());
902 pattern = pattern.Trim().Trim(false);
903 if(pattern.StartsWith(wxT("("))) {
904 // this macro has the form of a function
905 pattern = pattern.BeforeFirst(wxT(')'));
906 pattern.Append(wxT(')'));
907
908 tip << wxT("macro:") << pattern;
909
910 // collect each signature only once, we do this by using
911 // map
912 tipsMap[tip] = t;
913 }
914 }
915 }
916 }
917
918 for(std::map<wxString, TagEntryPtr>::iterator iter = tipsMap.begin(); iter != tipsMap.end(); iter++) {
919 tips.push_back(iter->second);
920 }
921 }
922
923 void TagsManager::CloseDatabase()
924 {
925 m_dbFile.Clear();
926 m_db = NULL; // Free the current database
927 m_db = new TagsStorageSQLite();
928 m_db->SetSingleSearchLimit(m_tagsOptions.GetCcNumberOfDisplayItems());
929 m_db->SetUseCache(false);
930 }
931
932 DoxygenComment TagsManager::GenerateDoxygenComment(const wxString& file, const int line, wxChar keyPrefix)
933 {
934 if(GetDatabase()->IsOpen()) {
935 TagEntryPtr tag = GetDatabase()->GetTagAboveFileAndLine(file, line);
936 if(!tag) {
937 return DoxygenComment();
938 }
939
940 // create a doxygen comment from the tag
941 return DoCreateDoxygenComment(tag, keyPrefix);
942 }
943 return DoxygenComment();
944 }
945
946 DoxygenComment TagsManager::DoCreateDoxygenComment(TagEntryPtr tag, wxChar keyPrefix)
947 {
948 CppCommentCreator commentCreator(tag, keyPrefix);
949 DoxygenComment dc;
950 dc.comment = commentCreator.CreateComment();
951 dc.name = tag->GetName();
952 return dc;
953 }
954
955 bool TagsManager::GetParseComments() { return m_parseComments; }
956
957 void TagsManager::SetCtagsOptions(const TagsOptionsData& options)
958 {
959 m_tagsOptions = options;
960 m_parseComments = m_tagsOptions.GetFlags() & CC_PARSE_COMMENTS ? true : false;
961 }
962
963 void TagsManager::GenerateSettersGetters(const wxString& scope, const SettersGettersData& data,
964 const std::vector<TagEntryPtr>& tags, wxString& impl, wxString* decl)
965 {
966 wxUnusedVar(scope);
967 wxUnusedVar(data);
968 wxUnusedVar(tags);
969 wxUnusedVar(impl);
970 wxUnusedVar(decl);
971 }
972
973 void TagsManager::TagsByScope(const wxString& scopeName, const wxString& kind, std::vector<TagEntryPtr>& tags,
974 bool includeInherits, bool applyLimit)
975 {
976 wxString sql;
977 std::vector<std::pair<wxString, int>> derivationList;
978 // add this scope as well to the derivation list
979 derivationList.push_back({ scopeName, 0 });
980 std::unordered_set<wxString> visited;
981 if(includeInherits) {
982 GetDerivationList(scopeName, NULL, derivationList, visited, 1);
983 }
984
985 // make enough room for max of 500 elements in the vector
986 tags.reserve(500);
987 wxArrayString kinds, scopes;
988 kinds.Add(kind);
989
990 for(size_t i = 0; i < derivationList.size(); i++) {
991 scopes.Add(derivationList.at(i).first);
992 }
993
994 clDEBUG() << "Reading symbols from scopes:" << scopes << endl;
995 if(applyLimit) {
996 GetDatabase()->GetTagsByScopesAndKind(scopes, kinds, tags);
997 } else {
998 GetDatabase()->GetTagsByScopesAndKindNoLimit(scopes, kinds, tags);
999 }
1000 }
1001
1002 wxString TagsManager::GetScopeName(const wxString& scope)
1003 {
1004 Language* lang = GetLanguage();
1005 return lang->GetScopeName(scope, NULL);
1006 }
1007
1008 bool TagsManager::ProcessExpression(const wxFileName& filename, int lineno, const wxString& expr,
1009 const wxString& scopeText, wxString& typeName, wxString& typeScope, wxString& oper,
1010 wxString& scopeTempalteInitiList)
1011 {
1012 return GetLanguage()->ProcessExpression(expr, scopeText, filename, lineno, typeName, typeScope, oper,
1013 scopeTempalteInitiList);
1014 }
1015
1016 bool TagsManager::GetMemberType(const wxString& scope, const wxString& name, wxString& type, wxString& typeScope)
1017 {
1018 wxString expression(scope);
1019 expression << wxT("::") << name << wxT(".");
1020 wxString dummy;
1021 return GetLanguage()->ProcessExpression(expression, wxEmptyString, wxFileName(), wxNOT_FOUND, type, typeScope,
1022 dummy, dummy);
1023 }
1024
1025 void TagsManager::GetFiles(const wxString& partialName, std::vector<FileEntryPtr>& files)
1026 {
1027 if(GetDatabase()) {
1028 GetDatabase()->GetFiles(partialName, files);
1029 }
1030 }
1031
1032 void TagsManager::GetFiles(const wxString& partialName, std::vector<wxFileName>& files)
1033 {
1034 std::vector<FileEntryPtr> f;
1035 GetFiles(partialName, f);
1036
1037 for(size_t i = 0; i < f.size(); i++) {
1038 files.push_back(wxFileName(f.at(i)->GetFile()));
1039 }
1040 }
1041
1042 TagEntryPtr TagsManager::FunctionFromBufferLine(const wxString& buffer, int lineno, const wxString& file_name)
1043 {
1044 auto tags = ParseBuffer(buffer, file_name);
1045 if(tags.empty()) {
1046 return nullptr;
1047 }
1048
1049 TagEntryPtr matched_tag;
1050 for(TagEntryPtr tag : tags) {
1051 if(tag->IsMethod() && tag->GetLine() <= lineno) {
1052 matched_tag = tag;
1053 } else if(tag->GetLine() > lineno) {
1054 break;
1055 }
1056 }
1057 return matched_tag;
1058 }
1059
1060 TagEntryPtr TagsManager::FunctionFromFileLine(const wxFileName& fileName, int lineno, bool nextFunction /*false*/)
1061 {
1062 if(!GetDatabase()) {
1063 return NULL;
1064 }
1065
1066 if(!IsFileCached(fileName.GetFullPath())) {
1067 CacheFile(fileName.GetFullPath());
1068 }
1069
1070 TagEntryPtr foo = NULL;
1071 for(size_t i = 0; i < m_cachedFileFunctionsTags.size(); i++) {
1072 TagEntryPtr t = m_cachedFileFunctionsTags.at(i);
1073
1074 if(nextFunction && t->GetLine() > lineno) {
1075 // keep the last non matched method
1076 foo = t;
1077 } else if(t->GetLine() <= lineno) {
1078 if(nextFunction) {
1079 return foo;
1080 } else {
1081 return t;
1082 }
1083 }
1084 }
1085 return foo;
1086 }
1087
1088 void TagsManager::GetScopesFromFile(const wxFileName& fileName, std::vector<wxString>& scopes)
1089 {
1090 if(!GetDatabase()) {
1091 return;
1092 }
1093
1094 GetDatabase()->GetScopesFromFileAsc(fileName, scopes);
1095 }
1096
1097 void TagsManager::TagsFromFileAndScope(const wxFileName& fileName, const wxString& scopeName,
1098 std::vector<TagEntryPtr>& tags)
1099 {
1100 if(!GetDatabase()) {
1101 return;
1102 }
1103
1104 wxArrayString kind;
1105 kind.Add(wxT("function"));
1106 kind.Add(wxT("prototype"));
1107 kind.Add(wxT("enum"));
1108
1109 GetDatabase()->GetTagsByFileScopeAndKind(fileName, scopeName, kind, tags);
1110 std::sort(tags.begin(), tags.end(), SAscendingSort());
1111 }
1112
1113 bool TagsManager::GetFunctionDetails(const wxFileName& fileName, int lineno, TagEntryPtr& tag, clFunction& func)
1114 {
1115 tag = FunctionFromFileLine(fileName, lineno);
1116 if(tag) {
1117 GetLanguage()->FunctionFromPattern(tag, func);
1118 return true;
1119 }
1120 return false;
1121 }
1122
1123 TagEntryPtr TagsManager::FirstFunctionOfFile(const wxFileName& fileName)
1124 {
1125 if(!GetDatabase()) {
1126 return NULL;
1127 }
1128
1129 std::vector<TagEntryPtr> tags;
1130 wxArrayString kind;
1131 kind.Add(wxT("function"));
1132 GetDatabase()->GetTagsByKindAndFile(kind, fileName.GetFullPath(), wxT("line"), ITagsStorage::OrderAsc, tags);
1133
1134 if(tags.empty())
1135 return NULL;
1136 return tags.at(0);
1137 }
1138
1139 TagEntryPtr TagsManager::FirstScopeOfFile(const wxFileName& fileName)
1140 {
1141 if(!GetDatabase()) {
1142 return NULL;
1143 }
1144 std::vector<TagEntryPtr> tags;
1145 wxArrayString kind;
1146 kind.Add(wxT("struct"));
1147 kind.Add(wxT("class"));
1148 kind.Add(wxT("namespace"));
1149 GetDatabase()->GetTagsByKindAndFile(kind, fileName.GetFullPath(), wxT("line"), ITagsStorage::OrderAsc, tags);
1150
1151 if(tags.empty())
1152 return NULL;
1153 return tags.at(0);
1154 }
1155
1156 wxString TagsManager::FormatFunction(TagEntryPtr tag, size_t flags, const wxString& scope)
1157 {
1158 clFunction foo;
1159 if(!GetLanguage()->FunctionFromPattern(tag, foo)) {
1160 return wxEmptyString;
1161 }
1162
1163 wxString body;
1164 // add virtual keyword to declarations only && if the flags is set
1165 if(foo.m_isVirtual && (flags & FunctionFormat_WithVirtual) && !(flags & FunctionFormat_Impl)) {
1166 body << wxT("virtual\n");
1167 }
1168
1169 if(tag->IsTemplateFunction()) {
1170 // a template function, add the template definition
1171 body << "template <";
1172 CxxTemplateFunction helper(tag);
1173 helper.ParseDefinitionList();
1174 for(size_t i = 0; i < helper.GetList().GetCount(); ++i) {
1175 body << " typename " << helper.GetList().Item(i) << ", \n";
1176 }
1177 if(body.EndsWith(", \n")) {
1178 body.RemoveLast(3);
1179 }
1180 body << ">\n";
1181 }
1182
1183 wxString retValue = tag->GetTypename();
1184 if(retValue.IsEmpty() == false) {
1185 body << retValue << wxT(" ");
1186 }
1187
1188 if(flags & FunctionFormat_Impl) {
1189 if(scope.IsEmpty()) {
1190 if(tag->GetScope() != wxT("<global>")) {
1191 body << tag->GetScope() << wxT("::");
1192 }
1193 } else {
1194 body << scope << wxT("::");
1195 }
1196 }
1197
1198 // Build the flags required by the NormalizeFunctionSig() method
1199 size_t tmpFlags(0);
1200 if(flags & FunctionFormat_Impl) {
1201 tmpFlags |= Normalize_Func_Name;
1202 } else {
1203 tmpFlags |= Normalize_Func_Name | Normalize_Func_Default_value;
1204 }
1205
1206 if(flags & FunctionFormat_Arg_Per_Line)
1207 tmpFlags |= Normalize_Func_Arg_Per_Line;
1208
1209 if(flags & FunctionFormat_Arg_Per_Line)
1210 body << wxT("\n");
1211
1212 body << tag->GetName();
1213 if(tag->GetFlags() & TagEntry::Tag_No_Signature_Format) {
1214 body << tag->GetSignature();
1215
1216 } else {
1217 body << NormalizeFunctionSig(tag->GetSignature(), tmpFlags);
1218 }
1219
1220 if(foo.m_isConst) {
1221 body << wxT(" const");
1222 }
1223
1224 if(!foo.m_throws.empty()) {
1225 body << wxT(" throw (") << wxString(foo.m_throws.c_str(), wxConvUTF8) << wxT(")");
1226 }
1227
1228 if(flags & FunctionFormat_Impl) {
1229 body << wxT("\n{\n}\n");
1230 } else {
1231 if(foo.m_isVirtual && (flags & FunctionFormat_WithOverride)) {
1232 body << wxT(" override");
1233 }
1234 body << wxT(";\n");
1235 }
1236
1237 // convert \t to spaces
1238 body.Replace(wxT("\t"), wxT(" "));
1239
1240 // remove any extra spaces from the tip
1241 while(body.Replace(wxT(" "), wxT(" "))) {}
1242 return body;
1243 }
1244
1245 bool TagsManager::IsPureVirtual(TagEntryPtr tag)
1246 {
1247 clFunction foo;
1248 if(!GetLanguage()->FunctionFromPattern(tag, foo)) {
1249 return false;
1250 }
1251 return foo.m_isPureVirtual;
1252 }
1253
1254 bool TagsManager::IsVirtual(TagEntryPtr tag)
1255 {
1256 clFunction foo;
1257 if(!GetLanguage()->FunctionFromPattern(tag, foo)) {
1258 return false;
1259 }
1260 return foo.m_isVirtual;
1261 }
1262
1263 bool TagsManager::GetVirtualProperty(TagEntryPtr tag, bool& isVirtual, bool& isPureVirtual, bool& isFinal)
1264 {
1265 clFunction foo;
1266 if(!GetLanguage()->FunctionFromPattern(tag, foo)) {
1267 return false;
1268 }
1269 isVirtual = foo.m_isVirtual;
1270 isPureVirtual = foo.m_isPureVirtual;
1271 isFinal = foo.m_isFinal;
1272 return true;
1273 }
1274 void TagsManager::SetLanguage(Language* lang) { m_lang = lang; }
1275
1276 Language* TagsManager::GetLanguage()
1277 {
1278 if(!m_lang) {
1279 // for backward compatibility allows access to the tags manager using
1280 // the singleton call
1281 return LanguageST::Get();
1282 } else {
1283 return m_lang;
1284 }
1285 }
1286
1287 bool TagsManager::ProcessExpression(const wxString& expression, wxString& type, wxString& typeScope)
1288 {
1289 wxString oper, dummy;
1290 return ProcessExpression(wxFileName(), wxNOT_FOUND, expression, wxEmptyString, type, typeScope, oper, dummy);
1291 }
1292
1293 void TagsManager::GetClasses(std::vector<TagEntryPtr>& tags, bool onlyWorkspace)
1294 {
1295 wxArrayString kind;
1296 kind.Add(wxT("class"));
1297 kind.Add(wxT("struct"));
1298 kind.Add(wxT("union"));
1299
1300 GetDatabase()->GetTagsByKind(kind, wxT("name"), ITagsStorage::OrderAsc, tags);
1301 }
1302
1303 void TagsManager::StripComments(const wxString& text, wxString& stippedText)
1304 {
1305 CppScanner scanner;
1306 scanner.SetText(_C(text));
1307
1308 bool changedLine = false;
1309 bool prepLine = false;
1310 int curline = 0;
1311
1312 while(true) {
1313 int type = scanner.yylex();
1314 if(type == 0) {
1315 break;
1316 }
1317
1318 // eat up all tokens until next line
1319 if(prepLine && scanner.lineno() == curline) {
1320 continue;
1321 }
1322
1323 prepLine = false;
1324
1325 // Get the current line number, it will help us detect preprocessor lines
1326 changedLine = (scanner.lineno() > curline);
1327 if(changedLine) {
1328 stippedText << wxT("\n");
1329 }
1330
1331 curline = scanner.lineno();
1332 if(type == '#') {
1333 if(changedLine) {
1334 // We are at the start of a new line
1335 // consume everything until new line is found or end of text
1336 prepLine = true;
1337 continue;
1338 }
1339 }
1340 stippedText << _U(scanner.YYText()) << wxT(" ");
1341 }
1342 }
1343
1344 void TagsManager::GetFunctions(std::vector<TagEntryPtr>& tags, const wxString& fileName, bool onlyWorkspace)
1345 {
1346 wxArrayString kind;
1347 kind.Add(wxT("function"));
1348 kind.Add(wxT("prototype"));
1349 GetDatabase()->GetTagsByKindAndFile(kind, fileName, wxT("name"), ITagsStorage::OrderAsc, tags);
1350 }
1351
1352 void TagsManager::TagsByScope(const wxString& scopeName, const wxArrayString& kind, std::vector<TagEntryPtr>& tags,
1353 bool include_anon)
1354 {
1355 wxUnusedVar(include_anon);
1356
1357 wxArrayString scopes;
1358 GetScopesByScopeName(scopeName, scopes);
1359 // make enough room for max of 500 elements in the vector
1360 tags.reserve(500);
1361 GetDatabase()->GetTagsByScopesAndKind(scopes, kind, tags);
1362
1363 // and finally sort the results
1364 std::sort(tags.begin(), tags.end(), SAscendingSort());
1365 }
1366
1367 void TagsManager::TagsByTyperef(const wxString& scopeName, const wxArrayString& kind, std::vector<TagEntryPtr>& tags,
1368 bool include_anon)
1369 {
1370 wxUnusedVar(include_anon);
1371
1372 wxArrayString scopes;
1373 GetScopesByScopeName(scopeName, scopes);
1374 // make enough room for max of 500 elements in the vector
1375 tags.reserve(500);
1376
1377 GetDatabase()->GetTagsByTyperefAndKind(scopes, kind, tags);
1378
1379 // and finally sort the results
1380 std::sort(tags.begin(), tags.end(), SAscendingSort());
1381 }
1382
1383 wxString TagsManager::NormalizeFunctionSig(const wxString& sig, size_t flags,
1384 std::vector<std::pair<int, int>>* paramLen)
1385 {
1386 // FIXME: make the standard configurable
1387 CxxVariableScanner varScanner(sig, eCxxStandard::kCxx11, {}, true);
1388 CxxVariable::Vec_t vars = varScanner.ParseFunctionArguments();
1389
1390 // construct a function signature from the results
1391 wxString str_output;
1392 str_output << wxT("(");
1393
1394 if(paramLen) {
1395 paramLen->clear();
1396 }
1397 if(flags & Normalize_Func_Arg_Per_Line && !vars.empty()) {
1398 str_output << wxT("\n ");
1399 }
1400
1401 for(const auto& var : vars) {
1402 int start_offset = str_output.length();
1403
1404 // FIXME: the standard should be configurable
1405 size_t toStringFlags = CxxVariable::kToString_None;
1406 if(flags & Normalize_Func_Name) {
1407 toStringFlags |= CxxVariable::kToString_Name;
1408 }
1409 if(flags & Normalize_Func_Default_value) {
1410 toStringFlags |= CxxVariable::kToString_DefaultValue;
1411 }
1412
1413 str_output << var->ToString(toStringFlags, {});
1414 // keep the length of this argument
1415 if(paramLen) {
1416 paramLen->push_back({ start_offset, str_output.length() - start_offset });
1417 }
1418
1419 str_output << ", ";
1420 if((flags & Normalize_Func_Arg_Per_Line) && !vars.empty()) {
1421 str_output << wxT("\n ");
1422 }
1423 }
1424
1425 if(vars.empty() == false) {
1426 str_output = str_output.BeforeLast(',');
1427 }
1428
1429 str_output << ")";
1430 return str_output;
1431 }
1432
1433 void TagsManager::GetUnImplementedFunctions(const wxString& scopeName, std::map<wxString, TagEntryPtr>& protos)
1434 {
1435 // get list of all prototype functions from the database
1436 std::vector<TagEntryPtr> vproto;
1437 std::vector<TagEntryPtr> vimpl;
1438
1439 // currently we want to add implementation only for workspace classes
1440 TagsByScope(scopeName, wxT("prototype"), vproto, false, false);
1441 TagsByScope(scopeName, wxT("function"), vimpl, false, false);
1442
1443 // filter out functions which already has implementation
1444 for(size_t i = 0; i < vproto.size(); i++) {
1445 TagEntryPtr tag = vproto.at(i);
1446 wxString key = tag->GetName();
1447
1448 // override the scope to be our scope...
1449 tag->SetScope(scopeName);
1450
1451 key << NormalizeFunctionSig(tag->GetSignature(), 0);
1452 protos[key] = tag;
1453 }
1454
1455 // std::map<std::string, std::string> ignoreTokens = GetCtagsOptions().GetTokensMap();
1456
1457 // remove functions with implementation
1458 for(size_t i = 0; i < vimpl.size(); i++) {
1459 TagEntryPtr tag = vimpl.at(i);
1460 wxString key = tag->GetName();
1461 key << NormalizeFunctionSig(tag->GetSignature(), 0);
1462 std::map<wxString, TagEntryPtr>::iterator iter = protos.find(key);
1463
1464 if(iter != protos.end()) {
1465 protos.erase(iter);
1466 }
1467 }
1468
1469 std::map<wxString, TagEntryPtr> tmpMap(protos);
1470 std::map<wxString, TagEntryPtr>::iterator it = tmpMap.begin();
1471 protos.clear();
1472
1473 // collect only non-pure virtual methods
1474 for(; it != tmpMap.end(); it++) {
1475 TagEntryPtr tag = it->second;
1476 clFunction f;
1477 if(GetLanguage()->FunctionFromPattern(tag, f)) {
1478 if(!f.m_isPureVirtual) {
1479 // incude this function
1480 protos[it->first] = it->second;
1481 }
1482 } else {
1483 // parsing failed
1484 protos[it->first] = it->second;
1485 }
1486 }
1487 }
1488
1489 void TagsManager::CacheFile(const wxString& fileName)
1490 {
1491 if(!GetDatabase()) {
1492 return;
1493 }
1494
1495 m_cachedFile = fileName;
1496 m_cachedFileFunctionsTags.clear();
1497
1498 wxArrayString kinds;
1499 kinds.Add(wxT("function"));
1500 kinds.Add(wxT("prototype"));
1501 // disable the cache
1502 GetDatabase()->SetUseCache(false);
1503 GetDatabase()->GetTagsByKindAndFile(kinds, fileName, wxT("line"), ITagsStorage::OrderDesc,
1504 m_cachedFileFunctionsTags);
1505 // re-enable it
1506 GetDatabase()->SetUseCache(true);
1507 }
1508
1509 void TagsManager::ClearCachedFile(const wxString& fileName)
1510 {
1511 if(fileName == m_cachedFile) {
1512 m_cachedFile.Clear();
1513 m_cachedFileFunctionsTags.clear();
1514 }
1515 }
1516
1517 bool TagsManager::IsFileCached(const wxString& fileName) const { return fileName == m_cachedFile; }
1518
1519 wxString TagsManager::DoReplaceMacros(const wxString& name)
1520 {
1521 // replace macros:
1522 // replace the provided typeName and scope with user defined macros as appeared in the PreprocessorMap
1523 wxString _name(name);
1524
1525 const wxStringTable_t& iTokens = GetCtagsOptions().GetTokensWxMap();
1526 wxStringTable_t::const_iterator it;
1527
1528 it = iTokens.find(_name);
1529 if(it != iTokens.end()) {
1530 if(it->second.empty() == false) {
1531 _name = it->second;
1532 }
1533 }
1534 return _name;
1535 }
1536
1537 void TagsManager::DeleteTagsByFilePrefix(const wxString& dbfileName, const wxString& filePrefix)
1538 {
1539 ITagsStorage* db = new TagsStorageSQLite();
1540 db->OpenDatabase(wxFileName(dbfileName));
1541 db->Begin();
1542
1543 // delete the tags
1544 db->DeleteByFilePrefix(db->GetDatabaseFileName(), filePrefix);
1545
1546 // deelete the FILES entries
1547 db->DeleteFromFilesByPrefix(db->GetDatabaseFileName(), filePrefix);
1548 db->Commit();
1549
1550 delete db;
1551 }
1552
1553 void TagsManager::UpdateFilesRetagTimestamp(const wxArrayString& files, ITagsStoragePtr db)
1554 {
1555 db->Begin();
1556 for(size_t i = 0; i < files.GetCount(); i++) {
1557 db->InsertFileEntry(files.Item(i), (int)time(NULL));
1558 }
1559 db->Commit();
1560 }
1561
1562 void TagsManager::FilterNonNeededFilesForRetaging(wxArrayString& strFiles, ITagsStoragePtr db)
1563 {
1564 std::vector<FileEntryPtr> files_entries;
1565 db->GetFiles(files_entries);
1566 std::unordered_set<wxString> files_set;
1567
1568 for(size_t i = 0; i < strFiles.GetCount(); i++) {
1569 files_set.insert(strFiles.Item(i));
1570 }
1571
1572 for(size_t i = 0; i < files_entries.size(); i++) {
1573 FileEntryPtr fe = files_entries.at(i);
1574
1575 // does the file exist in both lists?
1576 std::unordered_set<wxString>::iterator iter = files_set.find(fe->GetFile());
1577 if(iter != files_set.end()) {
1578 // get the actual modifiaction time of the file from the disk
1579 struct stat buff;
1580 int modified(0);
1581
1582 const wxCharBuffer cname = _C((*iter));
1583 if(stat(cname.data(), &buff) == 0) {
1584 modified = (int)buff.st_mtime;
1585 }
1586
1587 // if the timestamp from the database < then the actual timestamp, re-tag the file
1588 if(fe->GetLastRetaggedTimestamp() >= modified) {
1589 files_set.erase(iter);
1590 }
1591 }
1592 }
1593
1594 // copy back the files to the array
1595 std::unordered_set<wxString>::iterator iter = files_set.begin();
1596 strFiles.Clear();
1597 strFiles.Alloc(files_set.size());
1598 for(; iter != files_set.end(); iter++) {
1599 strFiles.Add(*iter);
1600 }
1601 }
1602
1603 void TagsManager::DoFilterNonNeededFilesForRetaging(wxArrayString& strFiles, ITagsStoragePtr db)
1604 {
1605 FilterNonNeededFilesForRetaging(strFiles, db);
1606 }
1607
1608 wxString TagsManager::GetFunctionReturnValueFromPattern(TagEntryPtr tag)
1609 {
1610 // evaluate the return value of the tag
1611 clFunction foo;
1612 wxString return_value;
1613 if(GetLanguage()->FunctionFromPattern(tag, foo)) {
1614 if(foo.m_retrunValusConst.empty() == false) {
1615 return_value << _U(foo.m_retrunValusConst.c_str()) << wxT(" ");
1616 }
1617
1618 if(foo.m_returnValue.m_typeScope.empty() == false) {
1619 return_value << _U(foo.m_returnValue.m_typeScope.c_str()) << wxT("::");
1620 }
1621
1622 if(foo.m_returnValue.m_type.empty() == false) {
1623 return_value << _U(foo.m_returnValue.m_type.c_str());
1624 if(foo.m_returnValue.m_templateDecl.empty() == false) {
1625 return_value << wxT("<") << _U(foo.m_returnValue.m_templateDecl.c_str()) << wxT(">");
1626 }
1627 return_value << _U(foo.m_returnValue.m_starAmp.c_str());
1628 return_value << wxT(" ");
1629 }
1630
1631 if(!foo.m_returnValue.m_rightSideConst.empty()) {
1632 return_value << foo.m_returnValue.m_rightSideConst << " ";
1633 }
1634 }
1635 return return_value;
1636 }
1637
1638 void TagsManager::GetTagsByKind(std::vector<TagEntryPtr>& tags, const wxArrayString& kind, const wxString& partName)
1639 {
1640 wxUnusedVar(partName);
1641 GetDatabase()->GetTagsByKind(kind, wxEmptyString, ITagsStorage::OrderNone, tags);
1642 }
1643
1644 void TagsManager::GetTagsByKindLimit(std::vector<TagEntryPtr>& tags, const wxArrayString& kind, int limit,
1645 const wxString& partName)
1646 {
1647 GetDatabase()->GetTagsByKindLimit(kind, wxEmptyString, ITagsStorage::OrderNone, limit, partName, tags);
1648 }
1649
1650 void TagsManager::DoGetFunctionTipForEmptyExpression(const wxString& word, const wxString& text,
1651 std::vector<TagEntryPtr>& tips, bool globalScopeOnly /* = false*/)
1652 {
1653 std::vector<TagEntryPtr> candidates;
1654 std::vector<wxString> additionlScopes;
1655
1656 // we are probably examining a global function, or a scope function
1657 GetGlobalTags(word, candidates, ExactMatch);
1658
1659 if(!globalScopeOnly) {
1660 wxString scopeName = GetLanguage()->GetScopeName(text, &additionlScopes);
1661 TagsByScopeAndName(scopeName, word, candidates);
1662 for(size_t i = 0; i < additionlScopes.size(); i++) {
1663 TagsByScopeAndName(additionlScopes.at(i), word, candidates);
1664 }
1665 }
1666 GetFunctionTipFromTags(candidates, word, tips);
1667 }
1668
1669 void TagsManager::GetUnOverridedParentVirtualFunctions(const wxString& scopeName, bool onlyPureVirtual,
1670 std::vector<TagEntryPtr>& protos)
1671 {
1672 std::vector<TagEntryPtr> tags;
1673 std::map<wxString, TagEntryPtr> parentSignature2tag;
1674 std::map<wxString, TagEntryPtr> classSignature2tag;
1675
1676 GetDatabase()->GetTagsByPath(scopeName, tags);
1677 if(tags.size() != 1) {
1678 return;
1679 }
1680
1681 TagEntryPtr classTag = tags.at(0);
1682 if(classTag->GetKind() != wxT("class") && classTag->GetKind() != wxT("struct"))
1683 return;
1684
1685 // Step 1:
1686 // ========
1687 // Compoze a list of all virtual functions from the direct parent(s)
1688 // class (there could be a multiple inheritance...)
1689 wxArrayString parents = classTag->GetInheritsAsArrayNoTemplates();
1690 wxArrayString kind;
1691
1692 tags.clear();
1693 kind.Add(wxT("prototype"));
1694 kind.Add(wxT("function"));
1695 for(wxArrayString::size_type i = 0; i < parents.GetCount(); i++) {
1696 GetDatabase()->GetTagsByScopeAndKind(parents.Item(i), kind, tags, false);
1697 }
1698
1699 for(wxArrayString::size_type i = 0; i < tags.size(); i++) {
1700 TagEntryPtr t = tags.at(i);
1701
1702 // Skip c-tors/d-tors
1703 if(t->IsDestructor() || t->IsConstructor())
1704 continue;
1705
1706 bool isVirtual, isPureVirtual, isFinal;
1707 if(!GetVirtualProperty(t, isVirtual, isPureVirtual, isFinal))
1708 continue;
1709
1710 // Skip final virtual functions
1711 if(isFinal)
1712 continue;
1713
1714 if((!onlyPureVirtual && isVirtual) || isPureVirtual) {
1715 wxString sig = NormalizeFunctionSig(t->GetSignature(), 0);
1716 sig.Prepend(t->GetName());
1717 parentSignature2tag[sig] = t;
1718 }
1719 }
1720
1721 // Step 2:
1722 // ========
1723 // Collect a list of function prototypes from the class
1724 tags.clear();
1725 GetDatabase()->GetTagsByScopeAndKind(scopeName, kind, tags, false);
1726 for(size_t i = 0; i < tags.size(); i++) {
1727 TagEntryPtr t = tags.at(i);
1728 wxString sig = NormalizeFunctionSig(t->GetSignature(), 0);
1729 sig.Prepend(t->GetName());
1730 classSignature2tag[sig] = t;
1731 }
1732
1733 // Step 3:
1734 // =======
1735 // remove any entry from the parent tags which exists in the child tags
1736 std::map<wxString, TagEntryPtr>::iterator iter = classSignature2tag.begin();
1737 for(; iter != classSignature2tag.end(); iter++) {
1738 if(parentSignature2tag.find(iter->first) != parentSignature2tag.end()) {
1739 // the current signature exists both in the child and the parent,
1740 // remove it
1741 parentSignature2tag.erase(iter->first);
1742 }
1743 }
1744
1745 // Step 4:
1746 // =======
1747 // parentSignature2tag now contains map of signature/tags of virtual functions which exists
1748 // in the parent but could not be found in the child
1749 iter = parentSignature2tag.begin();
1750 for(; iter != parentSignature2tag.end(); iter++) {
1751 protos.push_back(iter->second);
1752 }
1753 }
1754
1755 void TagsManager::ClearTagsCache() { GetDatabase()->ClearCache(); }
1756
1757 void TagsManager::SetProjectPaths(const wxArrayString& paths)
1758 {
1759 m_projectPaths.Clear();
1760 m_projectPaths = paths;
1761 }
1762
1763 void TagsManager::GetDereferenceOperator(const wxString& scope, std::vector<TagEntryPtr>& tags)
1764 {
1765 std::vector<std::pair<wxString, int>> derivationList;
1766
1767 // add this scope as well to the derivation list
1768 wxString _scopeName = DoReplaceMacros(scope);
1769 derivationList.push_back({ _scopeName, 0 });
1770 std::unordered_set<wxString> visited;
1771 GetDerivationList(_scopeName, NULL, derivationList, visited, 1);
1772
1773 // make enough room for max of 500 elements in the vector
1774 for(size_t i = 0; i < derivationList.size(); i++) {
1775 wxString tmpScope(derivationList.at(i).first);
1776 tmpScope = DoReplaceMacros(tmpScope);
1777
1778 GetDatabase()->GetDereferenceOperator(tmpScope, tags);
1779 if(!tags.empty()) {
1780 // No need to further check
1781 break;
1782 }
1783 }
1784 }
1785
1786 void TagsManager::GetSubscriptOperator(const wxString& scope, std::vector<TagEntryPtr>& tags)
1787 {
1788 std::vector<std::pair<wxString, int>> derivationList;
1789
1790 // add this scope as well to the derivation list
1791 wxString _scopeName = DoReplaceMacros(scope);
1792 derivationList.push_back({ _scopeName, 0 });
1793 std::unordered_set<wxString> visited;
1794 GetDerivationList(_scopeName, NULL, derivationList, visited, 1);
1795
1796 // make enough room for max of 500 elements in the vector
1797 for(size_t i = 0; i < derivationList.size(); i++) {
1798 wxString tmpScope(derivationList.at(i).first);
1799 tmpScope = DoReplaceMacros(tmpScope);
1800
1801 GetDatabase()->GetSubscriptOperator(scope, tags);
1802 if(!tags.empty()) {
1803
1804 // No need to further check
1805 break;
1806 }
1807 }
1808 }
1809
1810 void TagsManager::ClearAllCaches()
1811 {
1812 m_cachedFile.Clear();
1813 m_cachedFileFunctionsTags.clear();
1814 GetDatabase()->ClearCache();
1815 }
1816
1817 CppToken TagsManager::FindLocalVariable(const wxFileName& fileName, int pos, int lineNumber, const wxString& word,
1818 const wxString& modifiedText)
1819 {
1820 // Load the file and get a state map + the text from the scanner
1821 TagEntryPtr tag(NULL);
1822 TextStatesPtr states(NULL);
1823 CppWordScanner scanner;
1824
1825 if(modifiedText.empty() == false) {
1826 // Parse the modified text
1827 std::vector<TagEntryPtr> tags;
1828 DoParseModifiedText(modifiedText, tags);
1829
1830 // It is safe to assume that the tags are sorted by line number
1831 // Loop over the tree and search for the a function closest to the given line number
1832 for(size_t i = 0; i < tags.size() && tags[i]->GetLine() <= lineNumber; i++) {
1833 if(tags[i]->IsFunction()) {
1834 tag = tags[i];
1835 }
1836 }
1837
1838 // Construct a scanner based on the modified text
1839 scanner = CppWordScanner(fileName.GetFullPath(), modifiedText.mb_str().data(), 0);
1840 states = scanner.states();
1841
1842 } else {
1843 // get the local by scanning from the current function's
1844 tag = FunctionFromFileLine(fileName, lineNumber + 1);
1845 scanner = CppWordScanner(fileName.GetFullPath().mb_str().data());
1846 states = scanner.states();
1847 }
1848
1849 if(!tag || !states)
1850 return CppToken();
1851
1852 // Get the line number of the function
1853 int funcLine = tag->GetLine() - 1;
1854
1855 // Convert the line number to offset
1856 int from = states->LineToPos(funcLine);
1857 int to = states->FunctionEndPos(from);
1858
1859 if(to == wxNOT_FOUND)
1860 return CppToken();
1861
1862 // get list of variables from the given scope
1863 CxxVariableScanner varscanner(states->text, eCxxStandard::kCxx11, {}, false);
1864 CxxVariable::Map_t varsMap = varscanner.GetVariablesMap();
1865
1866 bool isLocalVar = (varsMap.count(word) != 0);
1867 if(!isLocalVar)
1868 return CppToken();
1869
1870 // search for matches in the given range
1871 CppTokensMap l;
1872 scanner.Match(word.mb_str().data(), l, from, to);
1873
1874 std::vector<CppToken> tokens;
1875 l.findTokens(word.mb_str().data(), tokens);
1876 if(tokens.empty())
1877 return CppToken();
1878
1879 // return the first match
1880 return *tokens.begin();
1881 }
1882
1883 void TagsManager::DoParseModifiedText(const wxString& text, std::vector<TagEntryPtr>& tags)
1884 {
1885 auto _tags = ParseBuffer(text);
1886 tags.swap(_tags);
1887 }
1888
1889 bool TagsManager::IsBinaryFile(const wxString& filepath, const TagsOptionsData& tod)
1890 {
1891 // If the file is a C++ file, avoid testing the content return false based on the extension
1892 FileExtManager::FileType type = FileExtManager::GetType(filepath);
1893 if(type == FileExtManager::TypeHeader || type == FileExtManager::TypeSourceC ||
1894 type == FileExtManager::TypeSourceCpp)
1895 return false;
1896
1897 // If this file matches any of the c++ patterns defined in the configuration
1898 // don't consider it as a binary file
1899 if(FileUtils::WildMatch(tod.GetFileSpec(), filepath)) {
1900 return false;
1901 }
1902
1903 // examine the file based on the content of the first 4K (max) bytes
1904 FILE* fp = fopen(filepath.To8BitData(), "rb");
1905 if(fp) {
1906
1907 char buffer[1];
1908 int textLen(0);
1909 const int maxTextToExamine(4096);
1910
1911 // examine up to maxTextToExamine first chars in the file and search for '\0'
1912 while(fread(buffer, sizeof(char), sizeof(buffer), fp) == 1 && textLen < maxTextToExamine) {
1913 textLen++;
1914 // if we found a NULL, return true
1915 if(buffer[0] == 0) {
1916 fclose(fp);
1917 return true;
1918 }
1919 }
1920
1921 fclose(fp);
1922 return false;
1923 }
1924
1925 // if we could not open it, return true
1926 return true;
1927 }
1928
1929 wxString TagsManager::WrapLines(const wxString& str)
1930 {
1931 wxString wrappedString;
1932
1933 int curLineBytes(0);
1934 wxString::const_iterator iter = str.begin();
1935 for(; iter != str.end(); iter++) {
1936 if(*iter == wxT('\t')) {
1937 wrappedString << wxT(" ");
1938
1939 } else if(*iter == wxT('\n')) {
1940 wrappedString << wxT("\n");
1941 curLineBytes = 0;
1942
1943 } else if(*iter == wxT('\r')) {
1944 // Skip it
1945
1946 } else {
1947 wrappedString << *iter;
1948 }
1949 curLineBytes++;
1950
1951 if(curLineBytes == MAX_TIP_LINE_SIZE) {
1952
1953 // Wrap the lines
1954 if(wrappedString.IsEmpty() == false && wrappedString.Last() != wxT('\n')) {
1955 wrappedString << wxT("\n");
1956 }
1957 curLineBytes = 0;
1958 }
1959 }
1960 return wrappedString;
1961 }
1962
1963 void TagsManager::SetEncoding(const wxFontEncoding& encoding) { m_encoding = encoding; }
1964
1965 wxArrayString TagsManager::BreakToOuterScopes(const wxString& scope)
1966 {
1967 wxArrayString outerScopes;
1968 wxArrayString scopes = wxStringTokenize(scope, wxT(":"), wxTOKEN_STRTOK);
1969 for(size_t i = 1; i < scopes.GetCount(); i++) {
1970 wxString newScope;
1971 for(size_t j = 0; j < i; j++) {
1972 newScope << scopes.Item(j) << wxT("::");
1973 }
1974 if(newScope.Len() >= 2) {
1975 newScope.RemoveLast(2);
1976 }
1977 outerScopes.Add(newScope);
1978 }
1979 return outerScopes;
1980 }
1981
1982 ITagsStoragePtr TagsManager::GetDatabase() { return m_db; }
1983
1984 void TagsManager::GetTagsByName(const wxString& prefix, std::vector<TagEntryPtr>& tags)
1985 {
1986 GetDatabase()->GetTagsByName(prefix, tags);
1987 }
1988
1989 wxString TagsManager::DoReplaceMacrosFromDatabase(const wxString& name)
1990 {
1991 std::set<wxString> scannedMacros;
1992 wxString newName = name;
1993 while(true) {
1994 TagEntryPtr matchedTag = GetDatabase()->GetTagsByNameLimitOne(newName);
1995 if(matchedTag && matchedTag->IsMacro() && scannedMacros.find(matchedTag->GetName()) == scannedMacros.end()) {
1996 TagEntryPtr realTag = matchedTag->ReplaceSimpleMacro();
1997 if(realTag) {
1998
1999 newName = realTag->GetName();
2000 scannedMacros.insert(newName);
2001 continue;
2002
2003 } else {
2004 break;
2005 }
2006 } else {
2007 break;
2008 }
2009 }
2010 return newName;
2011 }
2012
2013 void TagsManager::GetTagsByPartialName(const wxString& partialName, std::vector<TagEntryPtr>& tags)
2014 {
2015 GetDatabase()->GetTagsByPartName(partialName, tags);
2016 }
2017
2018 bool TagsManager::AreTheSame(const TagEntryPtrVector_t& v1, const TagEntryPtrVector_t& v2) const { return false; }
2019
2020 bool TagsManager::InsertFunctionDecl(const wxString& clsname, const wxString& functionDecl, wxString& sourceContent,
2021 int visibility)
2022 {
2023 return GetLanguage()->InsertFunctionDecl(clsname, functionDecl, sourceContent, visibility);
2024 }
2025
2026 void TagsManager::DoSortByVisibility(TagEntryPtrVector_t& tags)
2027 {
2028 TagEntryPtrVector_t publicTags;
2029 TagEntryPtrVector_t protectedTags;
2030 TagEntryPtrVector_t privateTags;
2031 TagEntryPtrVector_t locals;
2032 TagEntryPtrVector_t members;
2033
2034 for(size_t i = 0; i < tags.size(); ++i) {
2035
2036 TagEntryPtr tag = tags.at(i);
2037 wxString access = tag->GetAccess();
2038 wxString kind = tag->GetKind();
2039
2040 if(kind == "variable") {
2041 locals.push_back(tag);
2042
2043 } else if(kind == "member") {
2044 members.push_back(tag);
2045
2046 } else if(access == "private") {
2047 privateTags.push_back(tag);
2048
2049 } else if(access == "protected") {
2050 protectedTags.push_back(tag);
2051
2052 } else if(access == "public") {
2053 if(tag->GetName().StartsWith("_")) {
2054 // methods starting with _ usually are meant to be private
2055 privateTags.push_back(tag);
2056 } else {
2057 publicTags.push_back(tag);
2058 }
2059 } else {
2060 // assume private
2061 privateTags.push_back(tag);
2062 }
2063 }
2064
2065 std::sort(privateTags.begin(), privateTags.end(), SAscendingSort());
2066 std::sort(publicTags.begin(), publicTags.end(), SAscendingSort());
2067 std::sort(protectedTags.begin(), protectedTags.end(), SAscendingSort());
2068 std::sort(members.begin(), members.end(), SAscendingSort());
2069 std::sort(locals.begin(), locals.end(), SAscendingSort());
2070 tags.clear();
2071 tags.insert(tags.end(), locals.begin(), locals.end());
2072 tags.insert(tags.end(), publicTags.begin(), publicTags.end());
2073 tags.insert(tags.end(), protectedTags.begin(), protectedTags.end());
2074 tags.insert(tags.end(), privateTags.begin(), privateTags.end());
2075 tags.insert(tags.end(), members.begin(), members.end());
2076 }
2077
2078 void TagsManager::GetScopesByScopeName(const wxString& scopeName, wxArrayString& scopes)
2079 {
2080 std::vector<std::pair<wxString, int>> derivationList;
2081
2082 // add this scope as well to the derivation list
2083 wxString _scopeName = DoReplaceMacros(scopeName);
2084 derivationList.push_back({ _scopeName, 0 });
2085 std::unordered_set<wxString> visited;
2086 GetDerivationList(_scopeName, NULL, derivationList, visited, 1);
2087
2088 for(size_t i = 0; i < derivationList.size(); i++) {
2089 wxString tmpScope(derivationList.at(i).first);
2090 tmpScope = DoReplaceMacros(tmpScope);
2091 scopes.Add(tmpScope);
2092 }
2093 }
2094
2095 void TagsManager::InsertForwardDeclaration(const wxString& classname, const wxString& fileContent, wxString& lineToAdd,
2096 int& line, const wxString& impExpMacro)
2097 {
2098 lineToAdd << "class ";
2099 if(!impExpMacro.IsEmpty()) {
2100 lineToAdd << impExpMacro << " ";
2101 }
2102 lineToAdd << classname << ";";
2103 line = GetLanguage()->GetBestLineForForwardDecl(fileContent);
2104 }
2105
2106 void TagsManager::GetFilesForCC(const wxString& userTyped, wxArrayString& matches)
2107 {
2108 GetDatabase()->GetFilesForCC(userTyped, matches);
2109 }
2110
2111 void TagsManager::GetCXXKeywords(wxStringSet_t& words)
2112 {
2113 wxArrayString arr;
2114 GetCXXKeywords(arr);
2115 words.clear();
2116 words.insert(arr.begin(), arr.end());
2117 }
2118
2119 void TagsManager::GetCXXKeywords(wxArrayString& words)
2120 {
2121 words.Clear();
2122 words.Add("alignas");
2123 words.Add("alignof");
2124 words.Add("and");
2125 words.Add("and_eq");
2126 words.Add("asm");
2127 words.Add("auto");
2128 words.Add("bitand");
2129 words.Add("bitor");
2130 words.Add("bool");
2131 words.Add("break");
2132 words.Add("case");
2133 words.Add("catch");
2134 words.Add("char");
2135 words.Add("char16_t");
2136 words.Add("char32_t");
2137 words.Add("class");
2138 words.Add("compl");
2139 words.Add("const");
2140 words.Add("constexpr");
2141 words.Add("const_cast");
2142 words.Add("continue");
2143 words.Add("decltype");
2144 words.Add("default");
2145 words.Add("delete");
2146 words.Add("do");
2147 words.Add("double");
2148 words.Add("dynamic_cast");
2149 words.Add("else");
2150 words.Add("enum");
2151 words.Add("explicit");
2152 words.Add("export");
2153 words.Add("extern");
2154 words.Add("false");
2155 words.Add("final");
2156 words.Add("float");
2157 words.Add("for");
2158 words.Add("friend");
2159 words.Add("goto");
2160 words.Add("if");
2161 words.Add("inline");
2162 words.Add("int");
2163 words.Add("long");
2164 words.Add("mutable");
2165 words.Add("namespace");
2166 words.Add("new");
2167 words.Add("noexcept");
2168 words.Add("not");
2169 words.Add("not_eq");
2170 words.Add("nullptr");
2171 words.Add("operator");
2172 words.Add("or");
2173 words.Add("or_eq");
2174 words.Add("override");
2175 words.Add("private");
2176 words.Add("protected");
2177 words.Add("public");
2178 words.Add("register");
2179 words.Add("reinterpret_cast");
2180 words.Add("return");
2181 words.Add("short");
2182 words.Add("signed");
2183 words.Add("sizeof");
2184 words.Add("static");
2185 words.Add("static_assert");
2186 words.Add("static_cast");
2187 words.Add("struct");
2188 words.Add("switch");
2189 words.Add("template");
2190 words.Add("this");
2191 words.Add("thread_local");
2192 words.Add("throw");
2193 words.Add("true");
2194 words.Add("try");
2195 words.Add("typedef");
2196 words.Add("typeid");
2197 words.Add("typename");
2198 words.Add("union");
2199 words.Add("unsigned");
2200 words.Add("using");
2201 words.Add("virtual");
2202 words.Add("void");
2203 words.Add("volatile");
2204 words.Add("wchar_t");
2205 words.Add("while");
2206 words.Add("xor");
2207 words.Add("xor_eq");
2208 }
2209
2210 TagEntryPtrVector_t TagsManager::ParseBuffer(const wxString& content, const wxString& filename, const wxString& kinds)
2211 {
2212 TagEntryPtrVector_t tagsVec;
2213 CTags::ParseBuffer(filename, content, clStandardPaths::Get().GetBinaryFullPath("codelite-ctags"),
2214 GetCtagsOptions().GetTokensWxMap(), tagsVec);
2215 return tagsVec;
2216 }
2217
2218 void TagsManager::GetKeywordsTagsForLanguage(const wxString& filter, eLanguage lang, std::vector<TagEntryPtr>& tags)
2219 {
2220 wxString keywords;
2221 if(lang == kCxx) {
2222 keywords = wxT(" alignas"
2223 " alignof"
2224 " and"
2225 " and_eq"
2226 " asm"
2227 " auto"
2228 " bitand"
2229 " bitor"
2230 " bool"
2231 " break"
2232 " case"
2233 " catch"
2234 " char"
2235 " char16_t"
2236 " char32_t"
2237 " class"
2238 " compl"
2239 " concept"
2240 " const"
2241 " constexpr"
2242 " const_cast"
2243 " continue"
2244 " decltype"
2245 " default"
2246 " delete"
2247 " do"
2248 " double"
2249 " dynamic_cast"
2250 " else"
2251 " enum"
2252 " explicit"
2253 " export"
2254 " extern"
2255 " false"
2256 " final"
2257 " float"
2258 " for"
2259 " friend"
2260 " goto"
2261 " if"
2262 " inline"
2263 " int"
2264 " long"
2265 " mutable"
2266 " namespace"
2267 " new"
2268 " noexcept"
2269 " not"
2270 " not_eq"
2271 " nullptr"
2272 " once"
2273 " operator"
2274 " or"
2275 " or_eq"
2276 " override"
2277 " private"
2278 " protected"
2279 " public"
2280 " register"
2281 " reinterpret_cast"
2282 " requires"
2283 " return"
2284 " short"
2285 " signed"
2286 " sizeof"
2287 " static"
2288 " static_assert"
2289 " static_cast"
2290 " struct"
2291 " switch"
2292 " template"
2293 " this"
2294 " thread_local"
2295 " throw"
2296 " true"
2297 " try"
2298 " typedef"
2299 " typeid"
2300 " typename"
2301 " union"
2302 " unsigned"
2303 " using"
2304 " virtual"
2305 " void"
2306 " volatile"
2307 " wchar_t"
2308 " while"
2309 " xor"
2310 " xor_eq");
2311 } else if(lang == kJavaScript) {
2312 keywords = "abstract boolean break byte case catch char class "
2313 "const continue debugger default delete do double else enum export extends "
2314 "final finally float for function goto if implements import in instanceof "
2315 "int interface long native new package private protected public "
2316 "return short static super switch synchronized this throw throws "
2317 "transient try typeof var void volatile while with";
2318 }
2319
2320 std::set<wxString> uniqueWords;
2321 wxArrayString wordsArr = wxStringTokenize(keywords, wxT(" \r\t\n"));
2322 uniqueWords.insert(wordsArr.begin(), wordsArr.end());
2323 std::set<wxString>::iterator iter = uniqueWords.begin();
2324 for(; iter != uniqueWords.end(); ++iter) {
2325 if(iter->Contains(filter)) {
2326 TagEntryPtr tag(new TagEntry());
2327 tag->SetName(*iter);
2328 tag->SetKind(wxT("cpp_keyword"));
2329 tags.push_back(tag);
2330 }
2331 }
2332 }
2333
2334 void TagsManager::DoFilterCtorDtorIfNeeded(std::vector<TagEntryPtr>& tags, const wxString& oper)
2335 {
2336 if((oper == "->") || (oper == ".")) {
2337 // filter out the constructors / destructors
2338 std::vector<TagEntryPtr> candidatesNoCtorDtor;
2339 candidatesNoCtorDtor.reserve(tags.size());
2340 std::for_each(tags.begin(), tags.end(), [&](TagEntryPtr tag) {
2341 if(!tag->IsConstructor() && !tag->IsDestructor()) {
2342 candidatesNoCtorDtor.push_back(tag);
2343 }
2344 });
2345 tags.swap(candidatesNoCtorDtor);
2346 }
2347 }
2348
2349 void TagsManager::GetTagsByPartialNames(const wxArrayString& partialNames, std::vector<TagEntryPtr>& tags)
2350 {
2351 GetDatabase()->GetTagsByPartName(partialNames, tags);
2352 }
2353
2354 void TagsManager::DoTagsFromText(const wxString& text, std::vector<TagEntryPtr>& tags)
2355 {
2356 // Create tags from the string
2357 wxArrayString tagsLines = wxStringTokenize(text, "\n", wxTOKEN_STRTOK);
2358 tags.reserve(tagsLines.size());
2359 for(wxString& line : tagsLines) {
2360 line.Trim().Trim(false);
2361 if(line.IsEmpty()) {
2362 continue;
2363 }
2364
2365 TagEntryPtr tag(new TagEntry());
2366 tag->FromLine(line);
2367 tags.emplace_back(tag);
2368 }
2369 }
2370
2371 void TagsManager::ParseWorkspaceIncremental()
2372 {
2373 // restart ctagsd (this way we ensure that new settings are loaded)
2374 clLanguageServerEvent stop_event{ wxEVT_LSP_RESTART };
2375 stop_event.SetLspName("ctagsd");
2376 EventNotifier::Get()->AddPendingEvent(stop_event);
2377 }
2378
2379 void TagsManager::ParseWorkspaceFull(const wxString& workspace_dir)
2380 {
2381 // stop ctagsd
2382 clLanguageServerEvent stop_event{ wxEVT_LSP_STOP };
2383 stop_event.SetLspName("ctagsd");
2384 EventNotifier::Get()->ProcessEvent(stop_event);
2385
2386 // delete the tags.db file
2387 wxFileName tags_db{ workspace_dir, "tags.db" };
2388 tags_db.AppendDir(".ctagsd");
2389
2390 if(tags_db.FileExists()) {
2391 FileUtils::RemoveFile(tags_db, wxEmptyString);
2392 }
2393
2394 // start ctagsd again
2395 clLanguageServerEvent start_event{ wxEVT_LSP_START };
2396 start_event.SetLspName("ctagsd");
2397 EventNotifier::Get()->ProcessEvent(start_event);
2398 }