Debian Codegraph @

CodeLite/language.cpp

raw
1 //////////////////////////////////////////////////////////////////////////////
2 //////////////////////////////////////////////////////////////////////////////
3 //
4 // copyright : (C) 2008 by Eran Ifrah
5 // file name : language.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 "language.h"
26
27 #include "CompletionHelper.hpp"
28 #include "CxxLexerAPI.h"
29 #include "CxxPreProcessor.h"
30 #include "CxxScannerTokens.h"
31 #include "CxxTemplateFunction.h"
32 #include "CxxUsingNamespaceCollector.h"
33 #include "CxxVariableScanner.h"
34 #include "crawler_include.h"
35 #include "ctags_manager.h"
36 #include "file_logger.h"
37 #include "function.h"
38 #include "map"
39 #include "pptable.h"
40 #include "precompiled_header.h"
41 #include "variable.h"
42 #include "y.tab.h"
43
44 #include <algorithm>
45 #include <wx/ffile.h>
46 #include <wx/regex.h>
47 #include <wx/stopwatch.h>
48 #include <wx/tokenzr.h>
49
50 //#define __PERFORMANCE
51 #include "code_completion_api.h"
52 #include "performance.h"
53 #include "scope_optimizer.h"
54
55 static wxString PathFromNameAndScope(const wxString& typeName, const wxString& typeScope)
56 {
57 wxString path;
58 if(typeScope != wxT("<global>"))
59 path << typeScope << wxT("::");
60
61 path << typeName;
62 return path;
63 }
64
65 static wxString NameFromPath(const wxString& path)
66 {
67 wxString name = path.AfterLast(wxT(':'));
68 return name;
69 }
70
71 static wxString ScopeFromPath(const wxString& path)
72 {
73 wxString scope = path.BeforeLast(wxT(':'));
74 if(scope.IsEmpty())
75 return wxT("<global>");
76
77 if(scope.EndsWith(wxT(":"))) {
78 scope.RemoveLast();
79 }
80
81 if(scope.IsEmpty())
82 return wxT("<global>");
83
84 return scope;
85 }
86
87 Language::Language()
88 : m_expression(wxEmptyString)
89 , m_scanner(new CppScanner())
90 , m_tm(NULL)
91 {
92 // Initialise the braces map
93 m_braces['<'] = '>';
94 m_braces['('] = ')';
95 m_braces['['] = ']';
96 m_braces['{'] = '}';
97
98 // C++ / C auto complete delimiters for tokens
99 std::vector<wxString> delimArr;
100 delimArr.push_back(_T("::"));
101 delimArr.push_back(_T("->"));
102 delimArr.push_back(_T("."));
103 delimArr.push_back(wxT("@"));
104 SetAutoCompDeliemters(delimArr);
105 }
106
107 /// Destructor
108 Language::~Language() {}
109
110 #define SCP_STATE_NORMAL 0
111 #define SCP_STATE_IN_IF 1
112 #define SCP_STATE_IN_WHILE 2
113 #define SCP_STATE_IN_FOR 3
114 #define SCP_STATE_IN_CATCH 4
115 #define SCP_STATE_IN_FOR_NO_SEMICOLON 5
116
117 /// Return the visible scope until pchStopWord is encountered
118 wxString Language::OptimizeScope(const wxString& srcString, int lastFuncLine, wxString& localsScope)
119 {
120 CxxTokenizer tokenizer;
121 std::stack<wxString> scopes;
122 tokenizer.Reset(srcString);
123
124 CxxLexerToken token;
125 wxString currentScope;
126 int parenthesisDepth = 0;
127 int state = SCP_STATE_NORMAL;
128 while(tokenizer.NextToken(token)) {
129 if(tokenizer.IsInPreProcessorSection())
130 continue;
131 switch(state) {
132 case SCP_STATE_NORMAL:
133 switch(token.GetType()) {
134 case '{':
135 currentScope << "{";
136 scopes.push(currentScope);
137 currentScope.clear();
138 break;
139 case '}':
140 if(scopes.empty())
141 return ""; // Invalid braces count
142 currentScope = scopes.top();
143 scopes.pop();
144 currentScope << "} ";
145 break;
146 case T_IF:
147 state = SCP_STATE_IN_IF;
148 currentScope << " if ";
149 break;
150 case T_WHILE:
151 state = SCP_STATE_IN_WHILE;
152 currentScope << " while ";
153 break;
154 case T_FOR:
155 state = SCP_STATE_IN_FOR_NO_SEMICOLON;
156 currentScope << ";";
157 break;
158 case T_CATCH:
159 state = SCP_STATE_IN_CATCH;
160 currentScope << ";";
161 break;
162 case '(':
163 parenthesisDepth++;
164 currentScope << "(";
165 // Handle lambda
166 // If we are enterting lamda function defenition, collect the locals
167 // this is exactly what we in 'catch' hence the state change to SCP_STATE_IN_CATCH
168 if(tokenizer.GetLastToken().GetType() == ']') {
169 state = SCP_STATE_IN_CATCH;
170 }
171 break;
172 case ')':
173 parenthesisDepth--;
174 currentScope << ")";
175 break;
176 default:
177 if(parenthesisDepth == 0) {
178 currentScope << " " << token.GetWXString();
179 }
180 break;
181 }
182 break;
183 case SCP_STATE_IN_WHILE:
184 case SCP_STATE_IN_IF:
185 switch(token.GetType()) {
186 case '(':
187 parenthesisDepth++;
188 currentScope << "(";
189 break;
190 case ')':
191 parenthesisDepth--;
192 currentScope << ")";
193 if(parenthesisDepth == 0) {
194 state = SCP_STATE_NORMAL;
195 }
196 break;
197 }
198 break;
199 case SCP_STATE_IN_FOR_NO_SEMICOLON:
200 switch(token.GetType()) {
201 case '(':
202 parenthesisDepth++;
203 currentScope << "(";
204 break;
205 case ')':
206 parenthesisDepth--;
207 currentScope << ")";
208 if(parenthesisDepth == 0) {
209 state = SCP_STATE_NORMAL;
210 }
211 break;
212 case ';':
213 currentScope << ";";
214 state = SCP_STATE_IN_FOR;
215 break;
216 default:
217 currentScope << " " << token.GetWXString();
218 break;
219 }
220 break;
221 case SCP_STATE_IN_FOR:
222 switch(token.GetType()) {
223 case '(':
224 parenthesisDepth++;
225 currentScope << "(";
226 break;
227 case ')':
228 parenthesisDepth--;
229 currentScope << ")";
230 if(parenthesisDepth == 0) {
231 state = SCP_STATE_NORMAL;
232 }
233 break;
234 default:
235 break;
236 }
237 break;
238 case SCP_STATE_IN_CATCH:
239 switch(token.GetType()) {
240 case '(':
241 currentScope << "(";
242 parenthesisDepth++;
243 break;
244 case ')':
245 parenthesisDepth--;
246 currentScope << ")";
247 if(parenthesisDepth == 0) {
248 state = SCP_STATE_NORMAL;
249 }
250 break;
251 default:
252 currentScope << " " << token.GetWXString();
253 break;
254 }
255 break;
256 default:
257 break;
258 }
259 }
260
261 wxString s;
262 while(!scopes.empty()) {
263 s.Prepend(scopes.top());
264 scopes.pop();
265 }
266 s << currentScope;
267 localsScope = s;
268 return s;
269 }
270
271 ParsedToken* Language::ParseTokens(const wxString& scopeName)
272 {
273 wxString token;
274 wxString delim;
275 bool subscript;
276 ParsedToken* header(NULL);
277 ParsedToken* currentToken(header);
278 wxString funcArgList;
279
280 while(NextToken(token, delim, subscript, funcArgList)) {
281 ParsedToken* pt = new ParsedToken;
282 pt->SetSubscriptOperator(subscript);
283 pt->SetOperator(delim);
284 pt->SetPrev(currentToken);
285 pt->SetCurrentScopeName(scopeName);
286 pt->SetArgumentList(funcArgList);
287
288 ExpressionResult result = ParseExpression(token);
289 if(result.m_name.empty() && result.m_isGlobalScope == false) {
290 ParsedToken::DeleteTokens(header);
291 return NULL;
292 }
293
294 if(result.m_isGlobalScope && pt->GetOperator() != wxT("::")) {
295 ParsedToken::DeleteTokens(header);
296 return NULL;
297 }
298
299 if(result.m_isaType) {
300 pt->SetTypeScope(result.m_scope.empty() ? wxString(wxT("<global>"))
301 : wxString::From8BitData(result.m_scope.c_str()));
302 pt->SetTypeName(wxString::From8BitData(result.m_name.c_str()));
303
304 } else if(result.m_isGlobalScope) {
305 pt->SetTypeScope(wxT("<global>"));
306 pt->SetTypeName(wxT("<global>"));
307
308 } else if(result.m_isThis) {
309 //-----------------------------------------
310 // special handle for 'this' keyword
311 //-----------------------------------------
312
313 pt->SetTypeScope(result.m_scope.empty() ? wxString(wxT("<global>"))
314 : wxString::From8BitData(result.m_scope.c_str()));
315 if(scopeName == wxT("<global>")) {
316 ParsedToken::DeleteTokens(header);
317 return NULL;
318 }
319
320 if(pt->GetOperator() == wxT("::")) {
321 ParsedToken::DeleteTokens(header);
322 return NULL;
323 }
324
325 if(result.m_isPtr && pt->GetOperator() == wxT(".")) {
326 ParsedToken::DeleteTokens(header);
327 return NULL;
328 }
329
330 if(!result.m_isPtr && pt->GetOperator() == wxT("->")) {
331 ParsedToken::DeleteTokens(header);
332 return NULL;
333 }
334 pt->SetTypeName(scopeName);
335 pt->SetName(wxT("this"));
336 }
337
338 pt->SetIsTemplate(result.m_isTemplate);
339
340 // If the current token is 'this' then the type is actually the
341 // current scope
342 pt->SetName(_U(result.m_name.c_str()));
343
344 wxArrayString argsList;
345 ParseTemplateInitList(wxString::From8BitData(result.m_templateInitList.c_str()), argsList);
346 pt->SetTemplateInitialization(argsList);
347
348 if(currentToken == NULL) {
349 header = pt;
350 currentToken = pt;
351 } else {
352 currentToken->SetNext(pt);
353 currentToken = pt;
354 }
355 token.Clear();
356 delim.Clear();
357 subscript = false;
358 }
359
360 if(header && header->GetNext() && header->GetName().IsEmpty() && header->GetOperator() == "::") {
361 // a chain with more than one token and the first token is simple "::"
362 // Delete the first token from the list
363 ParsedToken* newHeader = header->GetNext();
364 newHeader->SetPrev(NULL);
365 wxDELETE(header);
366 header = newHeader;
367 }
368 return header;
369 }
370
371 bool Language::NextToken(wxString& token, wxString& delim, bool& subscriptOperator, wxString& funcArgList)
372 {
373 int depth(0);
374 int parenthesisDepth(0);
375 bool collectingFuncArgList = true;
376
377 subscriptOperator = false;
378 funcArgList.Clear();
379
380 CxxLexerToken tok;
381 while(m_tokenScanner.NextToken(tok)) {
382 if(parenthesisDepth) {
383 switch(tok.GetType()) {
384 case '(':
385 ++parenthesisDepth;
386 if(collectingFuncArgList) {
387 funcArgList << "(";
388 }
389 break;
390 case ')':
391 --parenthesisDepth;
392 if(collectingFuncArgList) {
393 funcArgList << ")";
394 }
395 break;
396 default:
397 if(collectingFuncArgList) {
398 funcArgList << " " << tok.GetWXString();
399 }
400 break;
401 }
402 } else {
403 switch(tok.GetType()) {
404 case T_DECLTYPE: {
405 if(m_tokenScanner.GetLastToken().GetType() == ',') {
406 token.RemoveLast();
407 }
408 wxString dummy;
409 if(m_tokenScanner.ReadUntilClosingBracket(')', dummy)) {
410 m_tokenScanner.NextToken(tok); // Consume the closing parent
411 }
412 break;
413 }
414 case T_STATIC_CAST:
415 case T_DYNAMIC_CAST:
416 case T_REINTERPRET_CAST:
417 case T_CONST_CAST: {
418 // We expect now: "<"
419 wxString txt;
420 if(m_tokenScanner.PeekToken(txt) != '<')
421 return false;
422 wxString typestr;
423 if(!m_tokenScanner.ReadUntilClosingBracket('>', typestr))
424 return false;
425 token.swap(typestr);
426
427 // Consume the closing angle bracket
428 m_tokenScanner.NextToken(tok);
429
430 // Peek at the next token
431 if(m_tokenScanner.PeekToken(txt) != '(')
432 return false;
433 if(!m_tokenScanner.ReadUntilClosingBracket(')', typestr))
434 return false;
435 // Consume the closing parenthessis
436 m_tokenScanner.NextToken(tok);
437 token.Replace("*", "");
438 token.Replace("&", "");
439 token.Trim().Trim(false);
440 token.Remove(0, 1).RemoveLast();
441 token.Trim().Trim(false);
442 break;
443 }
444 case T_THIS:
445 token << "this";
446 break;
447 case T_DOUBLE_COLONS:
448 case '.':
449 case T_ARROW:
450 if(depth == 0) {
451 delim = tok.GetWXString();
452 return true;
453 } else {
454 token << " " << tok.GetWXString();
455 }
456 break;
457 case '[':
458 subscriptOperator = true;
459 depth++;
460 token << " " << tok.GetWXString();
461 break;
462 case '(':
463 if(!token.IsEmpty()) {
464 // If the token is empty, we ignore this parenthessis.
465 // The reason is that it is probably from an expression like casting:
466 // (wxClipboard*)
467 parenthesisDepth++;
468 if(collectingFuncArgList) {
469 token << tok.GetWXString();
470 }
471 }
472 break;
473 case ')':
474 // Closing brace on this leve, means that their partner (the open brace)
475 // was ignored (see above) so we should ignore this one as well
476 break;
477 case '<':
478 case '{':
479 depth++;
480 token << " " << tok.GetWXString();
481 break;
482 case '>':
483 case ']':
484 case '}':
485 depth--;
486 token << " " << tok.GetWXString();
487 break;
488 case T_IDENTIFIER:
489 case ',':
490 case T_DOUBLE:
491 case T_INT:
492 case T_STRUCT:
493 case T_LONG:
494 case T_ENUM:
495 case T_CHAR:
496 case T_UNION:
497 case T_FLOAT:
498 case T_SHORT:
499 case T_UNSIGNED:
500 case T_SIGNED:
501 case T_VOID:
502 case T_CLASS:
503 case T_TYPEDEF:
504 token << " " << tok.GetWXString();
505 break;
506 default:
507 break;
508 }
509 }
510 }
511 if(token.IsEmpty() == false && depth == 0) {
512 if(delim.IsEmpty()) {
513 delim = ".";
514 return true;
515 }
516 }
517 return false;
518 }
519
520 void Language::SetAutoCompDeliemters(const std::vector<wxString>& delimArr) { m_delimArr = delimArr; }
521
522 bool Language::ProcessExpression(const wxString& expr, const wxString& text, const wxFileName& fn, int lineno,
523 wxString& typeName, // output
524 wxString& typeScope, // output
525 wxString& oper, // output
526 wxString& scopeTemplateInitList) // output
527 {
528 bool evaluationSucceeded = true;
529 m_templateArgs.clear();
530
531 wxString statement(expr);
532
533 // Trim whitespace from right and left
534 static wxString trimString(_T("{};\r\n\t\v "));
535
536 statement.erase(0, statement.find_first_not_of(trimString));
537 statement.erase(statement.find_last_not_of(trimString) + 1);
538
539 wxString visibleScope, scopeName, localsBody;
540 wxString lastFuncSig;
541 TagEntryPtr matched_tag = TagsManagerST::Get()->FunctionFromBufferLine(text, lineno, fn.GetFullPath());
542
543 wxString textAfterTokensReplacements;
544 textAfterTokensReplacements = ApplyCtagsReplacementTokens(text);
545
546 // Parse the local variables once
547 const wxStringTable_t& ignoreTokens = GetTagsManager()->GetCtagsOptions().GetTokensWxMap();
548 m_locals.clear();
549 {
550 CxxVariableScanner scanner(textAfterTokensReplacements, eCxxStandard::kCxx11, ignoreTokens, false);
551 CxxVariable::Map_t localsMap = scanner.GetVariablesMap();
552 m_locals.insert(localsMap.begin(), localsMap.end());
553 visibleScope = scanner.GetOptimizeBuffer();
554 }
555
556 // parse the the current function's signature
557 if(matched_tag) {
558 CompletionHelper helper;
559 std::vector<wxString> args = helper.split_function_signature(matched_tag->GetSignature(), nullptr);
560 for(const wxString& arg : args) {
561 lastFuncSig << arg << ",";
562 CxxVariableScanner scanner(arg, eCxxStandard::kCxx11, ignoreTokens, true);
563 CxxVariable::Map_t localsMap = scanner.GetVariablesMap();
564 m_locals.insert(localsMap.begin(), localsMap.end());
565 }
566 if(!lastFuncSig.empty()) {
567 lastFuncSig.RemoveLast();
568 }
569 }
570
571 std::vector<wxString> additionalScopes;
572
573 scopeName = GetScopeName(visibleScope, &additionalScopes);
574
575 // Always use the global namespace as an addition scope
576 // but make sure we add it last
577 additionalScopes.push_back(wxT("<global>"));
578
579 SetLastFunctionSignature(lastFuncSig);
580 SetVisibleScope(localsBody);
581 SetAdditionalScopes(additionalScopes, fn.GetFullPath());
582
583 // get next token using the tokenscanner object
584 m_tokenScanner.Reset(statement);
585
586 // By default we keep the head of the list to the top
587 // of the chain
588 TokenContainer container;
589
590 container.head = ParseTokens(scopeName);
591 if(!container.head) {
592 return false;
593 }
594
595 container.current = container.head;
596
597 while(container.current) {
598
599 bool res = ProcessToken(&container);
600
601 if(!res && !container.Rewind()) {
602 evaluationSucceeded = false;
603 break;
604
605 } else if(!res && container.Rewind()) {
606 // ProcessToken() modified the list
607 container.SetRewind(false);
608 continue;
609 }
610
611 container.retries = 0;
612
613 // HACK1: Let the user override the parser decisions
614 RunUserTypes(container.current);
615 // We call here to IsTypeAndScopeExists which will attempt to provide the best scope / type
616 DoIsTypeAndScopeExist(container.current);
617 DoExtractTemplateInitListFromInheritance(container.current);
618
619 if(container.current->GetIsTemplate() && container.current->GetTemplateArgList().IsEmpty()) {
620 // We got no template declaration...
621 container.current->SetTemplateArgList(DoExtractTemplateDeclarationArgs(container.current), m_templateArgs);
622 }
623
624 int retryCount(0);
625 bool cont(false);
626 bool cont2(false);
627
628 do {
629 CheckForTemplateAndTypedef(container.current);
630 // We check subscript operator only once
631 cont = (container.current->GetSubscriptOperator() && OnSubscriptOperator(container.current));
632 if(cont) {
633 RunUserTypes(container.current);
634 }
635 container.current->SetSubscriptOperator(false);
636 cont2 = (container.current->GetOperator() == wxT("->") && OnArrowOperatorOverloading(container.current));
637 if(cont2) {
638 RunUserTypes(container.current);
639 }
640 retryCount++;
641 } while((cont || cont2) && retryCount < 5);
642
643 // Update the results we got so far
644 typeName = container.current->GetTypeName();
645 typeScope = container.current->GetTypeScope();
646
647 // Keep the last operator used, it is required by the caller
648 oper = container.current->GetOperator();
649
650 container.current = container.current->GetNext();
651 }
652
653 // release the tokens
654 ParsedToken::DeleteTokens(container.head);
655 return evaluationSucceeded;
656 }
657
658 bool Language::OnTemplates(ParsedToken* token)
659 {
660 token->ResolveTemplateType(GetTagsManager());
661 return token->ResovleTemplate(GetTagsManager());
662 }
663
664 void Language::DoSimpleTypedef(ParsedToken* token) {}
665
666 bool Language::OnTypedef(ParsedToken* token) { return false; }
667
668 void Language::ParseTemplateArgs(const wxString& argListStr, wxArrayString& argsList)
669 {
670 CppScanner scanner;
671 scanner.SetText(_C(argListStr));
672 int type = scanner.yylex();
673 wxString word = _U(scanner.YYText());
674
675 // Eof?
676 if(type == 0) {
677 return;
678 }
679 if(type != (int)'<') {
680 return;
681 }
682
683 bool nextIsArg(false);
684 bool cont(true);
685 while(cont) {
686 type = scanner.yylex();
687 if(type == 0) {
688 break;
689 }
690
691 switch(type) {
692 case lexCLASS:
693 case IDENTIFIER: {
694 wxString word = _U(scanner.YYText());
695 if(word == wxT("class") || word == wxT("typename")) {
696 nextIsArg = true;
697
698 } else if(nextIsArg) {
699 argsList.Add(word);
700 nextIsArg = false;
701 }
702 break;
703 }
704 case(int)'>':
705 cont = false;
706 break;
707 default:
708 break;
709 }
710 }
711 }
712
713 void Language::ParseTemplateInitList(const wxString& argListStr, wxArrayString& argsList)
714 {
715 CppScanner scanner;
716 scanner.SetText(_C(argListStr));
717 int type = scanner.yylex();
718 wxString word = _U(scanner.YYText());
719
720 // Eof?
721 if(type == 0) {
722 return;
723 }
724 if(type != (int)'<') {
725 return;
726 }
727
728 int depth(1);
729 wxString typeName;
730 while(depth > 0) {
731 type = scanner.yylex();
732 if(type == 0) {
733 break;
734 }
735
736 switch(type) {
737 case(int)',': {
738 if(depth == 1) {
739 argsList.Add(typeName.Trim().Trim(false));
740 typeName.Empty();
741 }
742 break;
743 }
744 case(int)'>':
745 depth--;
746 break;
747 case(int)'<':
748 depth++;
749 break;
750 case(int)'*':
751 case(int)'&':
752 // ignore pointers & references
753 break;
754 default:
755 if(depth == 1) {
756 typeName << _U(scanner.YYText());
757 }
758 break;
759 }
760 }
761
762 if(typeName.Trim().Trim(false).IsEmpty() == false) {
763 argsList.Add(typeName.Trim().Trim(false));
764 }
765 typeName.Empty();
766 }
767
768 void Language::ParseComments(const wxFileName& fileName, std::vector<CommentPtr>* comments)
769 {
770 wxString content;
771 try {
772 wxFFile f(fileName.GetFullPath().GetData());
773 if(!f.IsOpened())
774 return;
775
776 // read the content of the file and parse it
777 f.ReadAll(&content);
778 f.Close();
779 } catch(...) {
780 return;
781 }
782
783 m_scanner->Reset();
784 m_scanner->SetText(_C(content));
785 m_scanner->KeepComment(1);
786
787 int type(0);
788
789 wxString comment(_T(""));
790 int line(-1);
791
792 while(true) {
793 type = m_scanner->yylex();
794 if(type == 0) // eof
795 break;
796
797 // we keep only comments
798 if(type == CPPComment) {
799 // incase the previous comment was one line above this one,
800 // concatenate them to a single comment
801 if(m_scanner->lineno() - 1 == line) {
802 comment << m_scanner->GetComment();
803 line = m_scanner->lineno();
804 m_scanner->ClearComment();
805 continue;
806 }
807
808 // save the previous comment buffer
809 if(comment.IsEmpty() == false) {
810 comments->push_back(new Comment(comment, fileName.GetFullPath(), line - 1));
811 comment.Empty();
812 line = -1;
813 }
814
815 // first time or no comment is buffer
816 if(comment.IsEmpty()) {
817 comment = m_scanner->GetComment();
818 line = m_scanner->lineno();
819 m_scanner->ClearComment();
820 continue;
821 }
822
823 comments->push_back(new Comment(m_scanner->GetComment(), fileName.GetFullPath(), m_scanner->lineno() - 1));
824 comment.Empty();
825 line = -1;
826 m_scanner->ClearComment();
827
828 } else if(type == CComment) {
829 comments->push_back(new Comment(m_scanner->GetComment(), fileName.GetFullPath(), m_scanner->lineno()));
830 m_scanner->ClearComment();
831 }
832 }
833
834 if(comment.IsEmpty() == false) {
835 comments->push_back(new Comment(comment, fileName.GetFullPath(), line - 1));
836 }
837
838 // reset the scanner
839 m_scanner->KeepComment(0);
840 m_scanner->Reset();
841 }
842
843 wxString Language::GetScopeName(const wxString& in, std::vector<wxString>* additionlNS)
844 {
845 std::vector<std::string> moreNS;
846
847 const wxCharBuffer buf = _C(in);
848
849 TagsManager* mgr = GetTagsManager();
850 std::map<std::string, std::string> ignoreTokens = mgr->GetCtagsOptions().GetTokensMap();
851
852 std::string scope_name = get_scope_name(buf.data(), moreNS, ignoreTokens);
853 wxString scope = _U(scope_name.c_str());
854 if(scope.IsEmpty()) {
855 scope = wxT("<global>");
856 }
857
858 if(additionlNS) {
859 for(size_t i = 0; i < moreNS.size(); i++) {
860 additionlNS->push_back(_U(moreNS.at(i).c_str()));
861 }
862
863 // In case we are found some 'using namesapce XXX;' statement
864 // we should scan the following scopes:
865 // XXX
866 // and also:
867 // XXX::CurrentScope (assuming that CurrentScope != <global>)
868 if(scope != wxT("<global>")) {
869 std::vector<wxString> tmpScopes;
870 for(size_t i = 0; i < additionlNS->size(); i++) {
871 tmpScopes.push_back(additionlNS->at(i));
872 tmpScopes.push_back(additionlNS->at(i) + wxT("::") + scope);
873 }
874 additionlNS->clear();
875 additionlNS->insert(additionlNS->begin(), tmpScopes.begin(), tmpScopes.end());
876 }
877
878 wxArrayString moreScopes = GetTagsManager()->BreakToOuterScopes(scope);
879 for(size_t i = 0; i < moreScopes.GetCount(); i++) {
880 if(moreScopes.Item(i) != scope &&
881 std::find(additionlNS->begin(), additionlNS->end(), moreScopes.Item(i)) == additionlNS->end()) {
882 additionlNS->push_back(moreScopes.Item(i));
883 }
884 }
885 }
886
887 return scope;
888 }
889
890 ExpressionResult Language::ParseExpression(const wxString& in)
891 {
892 ExpressionResult result;
893 if(in.IsEmpty()) {
894 result.m_isGlobalScope = true;
895
896 } else {
897 const wxCharBuffer buf = _C(in);
898 result = parse_expression(buf.data());
899 }
900 return result;
901 }
902
903 bool Language::ProcessToken(TokenContainer* tokeContainer) { return false; }
904
905 bool Language::CorrectUsingNamespace(wxString& type, wxString& typeScope, const wxString& parentScope,
906 std::vector<TagEntryPtr>& tags)
907 {
908 wxString strippedScope(typeScope);
909 wxArrayString tmplInitList;
910 DoRemoveTempalteInitialization(strippedScope, tmplInitList);
911
912 if(typeScope == wxT("<global>") && GetAdditionalScopes().empty() == false) {
913 // Incase the typeScope is "global" and we got additional-scopes
914 // Use the additional scopes *before* the "global" scope
915 for(size_t i = 0; i < GetAdditionalScopes().size(); i++) {
916 tags.clear();
917 wxString newScope(GetAdditionalScopes().at(i));
918 if(typeScope != wxT("<global>")) {
919 newScope << wxT("::") << typeScope;
920 }
921
922 if(DoSearchByNameAndScope(type, newScope, tags, type, typeScope)) {
923 return true;
924 }
925 }
926 }
927
928 // try the passed scope (might be <global> now)
929 if(GetTagsManager()->IsTypeAndScopeExists(type, strippedScope)) {
930 return true;
931 }
932
933 // if we are here, it means that the more scopes did not matched any, try the parent scope
934 tags.clear();
935
936 // try all the scopes of the parent:
937 // for example:
938 // assuming the parent scope is A::B::C
939 // try to match:
940 // A::B::C
941 // A::B
942 // A
943 wxArrayString scopesToScan = GetTagsManager()->BreakToOuterScopes(parentScope);
944 scopesToScan.Add(wxT("<global>"));
945 for(size_t i = 0; i < scopesToScan.GetCount(); i++) {
946 tags.clear();
947 if(DoSearchByNameAndScope(type, scopesToScan.Item(i), tags, type, typeScope, false)) {
948 return true;
949 }
950 }
951
952 // still no luck, try the typeScope
953 scopesToScan = GetTagsManager()->BreakToOuterScopes(typeScope);
954 for(size_t i = 0; i < scopesToScan.GetCount(); i++) {
955 tags.clear();
956 if(DoSearchByNameAndScope(type, scopesToScan.Item(i), tags, type, typeScope, false)) {
957 return true;
958 }
959 }
960 return true;
961 }
962
963 bool Language::DoSearchByNameAndScope(const wxString& name, const wxString& scopeName, std::vector<TagEntryPtr>& tags,
964 wxString& type, wxString& typeScope, bool testGlobalScope)
965 {
966 return false;
967 }
968
969 bool Language::VariableFromPattern(const wxString& in, const wxString& name, Variable& var)
970 {
971 VariableList li;
972 wxString pattern(in);
973 // we need to extract the return value from the pattern
974 pattern = pattern.BeforeLast(wxT('$'));
975 pattern = pattern.AfterFirst(wxT('^'));
976
977 // remove C++11 angle bracket to use C++98
978 wxString fixed_pattern;
979 for(const wxChar& ch : pattern) {
980 switch(ch) {
981 case '>':
982 fixed_pattern << " >";
983 break;
984 case '<':
985 fixed_pattern << "< ";
986 break;
987 default:
988 fixed_pattern << ch;
989 break;
990 }
991 }
992 pattern.swap(fixed_pattern);
993
994 const wxCharBuffer patbuf = _C(pattern);
995 li.clear();
996
997 TagsManager* mgr = GetTagsManager();
998 auto ignoreTokens = mgr->GetCtagsOptions().GetTokensMap();
999
1000 get_variables(patbuf.data(), li, ignoreTokens, false);
1001 VariableList::iterator iter = li.begin();
1002 for(; iter != li.end(); iter++) {
1003 Variable v = *iter;
1004 if(name == _U(v.m_name.c_str())) {
1005 var = (*iter);
1006 var.m_pattern = pattern.mb_str(wxConvUTF8).data();
1007 return true;
1008 }
1009 } // if(li.size() == 1)
1010 return false;
1011 }
1012
1013 bool Language::FunctionFromPattern(TagEntryPtr tag, clFunction& foo) { return false; }
1014
1015 void Language::GetLocalVariables(const wxString& in, std::vector<TagEntryPtr>& tags, bool isFuncSignature,
1016 const wxString& name, size_t flags)
1017 {
1018 wxString pattern(in);
1019 pattern = pattern.Trim().Trim(false);
1020
1021 if(flags & ReplaceTokens) {
1022 // Apply ctags replcements table on the current input string
1023 pattern = ApplyCtagsReplacementTokens(in);
1024 }
1025
1026 CxxVariableScanner scanner(pattern, eCxxStandard::kCxx11, GetTagsManager()->GetCtagsOptions().GetTokensWxMap(),
1027 isFuncSignature);
1028 CxxVariable::Vec_t locals = scanner.GetVariables(false);
1029
1030 for(CxxVariable::Ptr_t local : locals) {
1031 const wxString& tagName = local->GetName();
1032
1033 // if we have name, collect only tags that matches name
1034 if(!name.IsEmpty()) {
1035 // incase CaseSensitive is not required, make both string lower case
1036 wxString tmpName(name);
1037 wxString tmpTagName(tagName);
1038 if(flags & IgnoreCaseSensitive) {
1039 tmpName.MakeLower();
1040 tmpTagName.MakeLower();
1041 }
1042
1043 if((flags & PartialMatch) && !tmpTagName.StartsWith(tmpName))
1044 continue;
1045 // Don't suggest what we have typed so far
1046 if((flags & PartialMatch) && tmpTagName == tmpName)
1047 continue;
1048 ;
1049 if((flags & ExactMatch) && tmpTagName != tmpName)
1050 continue;
1051 ;
1052 } // else no name is specified, collect all tags
1053
1054 TagEntryPtr tag(new TagEntry());
1055 tag->SetName(tagName);
1056 tag->SetKind(wxT("variable"));
1057 tag->SetParent(wxT("<local>"));
1058 tag->SetScope(local->GetTypeAsCxxString());
1059 tag->SetAccess("public");
1060 tag->SetPattern(local->ToString());
1061 tags.push_back(tag);
1062 }
1063 }
1064
1065 bool Language::OnArrowOperatorOverloading(ParsedToken* token)
1066 {
1067 bool ret(false);
1068 // collect all functions of typename
1069 std::vector<TagEntryPtr> tags;
1070 wxString typeScope(token->GetTypeScope());
1071 wxString typeName(token->GetTypeName());
1072
1073 // this function will retrieve the ineherited tags as well
1074 GetTagsManager()->GetDereferenceOperator(token->GetPath(), tags);
1075
1076 if(tags.size() == 1) {
1077 // loop over the tags and scan for operator -> overloading
1078 // we found our overloading operator
1079 // extract the 'real' type from the pattern
1080 clFunction f;
1081 if(FunctionFromPattern(tags.at(0), f)) {
1082
1083 typeName = _U(f.m_returnValue.m_type.c_str());
1084 typeScope =
1085 f.m_returnValue.m_typeScope.empty() ? token->GetPath() : _U(f.m_returnValue.m_typeScope.c_str());
1086
1087 token->SetTypeName(typeName);
1088 token->SetTypeScope(typeScope);
1089
1090 // Call the magic method that fixes typename/typescope
1091 DoIsTypeAndScopeExist(token);
1092 ret = true;
1093 }
1094 }
1095 return ret;
1096 }
1097
1098 void Language::SetTagsManager(TagsManager* tm) { m_tm = tm; }
1099
1100 TagsManager* Language::GetTagsManager()
1101 {
1102 if(!m_tm) {
1103 // for backward compatibility allows access to the tags manager using
1104 // the singleton call
1105 return TagsManagerST::Get();
1106 } else {
1107 return m_tm;
1108 }
1109 }
1110
1111 void Language::DoRemoveTempalteInitialization(wxString& str, wxArrayString& tmplInitList)
1112 {
1113 CppScanner sc;
1114 sc.SetText(_C(str));
1115
1116 int type(0);
1117 int depth(0);
1118
1119 wxString token;
1120 wxString outputString;
1121 str.Clear();
1122
1123 while((type = sc.yylex()) != 0) {
1124 if(type == 0)
1125 return;
1126
1127 token = _U(sc.YYText());
1128 switch(type) {
1129 case wxT('<'):
1130 if(depth == 0)
1131 outputString.Clear();
1132 outputString << token;
1133 depth++;
1134 break;
1135
1136 case wxT('>'):
1137 outputString << token;
1138 depth--;
1139 break;
1140
1141 default:
1142 if(depth > 0)
1143 outputString << token;
1144 else
1145 str << token;
1146 break;
1147 }
1148 }
1149
1150 if(outputString.IsEmpty() == false) {
1151 ParseTemplateInitList(outputString, tmplInitList);
1152 }
1153 }
1154
1155 void Language::DoFixFunctionUsingCtagsReturnValue(clFunction& foo, TagEntryPtr tag)
1156 {
1157 wxUnusedVar(foo);
1158 wxUnusedVar(tag);
1159 }
1160
1161 void Language::DoReplaceTokens(wxString& inStr, const wxStringTable_t& ignoreTokens)
1162 {
1163 if(inStr.IsEmpty())
1164 return;
1165
1166 wxStringTable_t::const_iterator iter = ignoreTokens.begin();
1167 for(; iter != ignoreTokens.end(); iter++) {
1168 wxString findWhat = iter->first;
1169 wxString replaceWith = iter->second;
1170
1171 if(findWhat.StartsWith(wxT("re:"))) {
1172 findWhat.Remove(0, 3);
1173 wxRegEx re(findWhat);
1174 if(re.IsValid() && re.Matches(inStr)) {
1175 re.ReplaceAll(&inStr, replaceWith);
1176 }
1177 } else {
1178 // Simple replacement
1179 int where = inStr.Find(findWhat);
1180 if(where >= 0) {
1181 if(inStr.Length() > static_cast<size_t>(where)) {
1182 // Make sure that the next char is a non valid char otherwise this is not a complete word
1183 if(inStr.Mid(where, 1).find_first_of(
1184 wxT("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_1234567890")) != wxString::npos) {
1185 // the match is not a full word
1186 continue;
1187 } else {
1188 inStr.Replace(findWhat, replaceWith);
1189 }
1190 } else {
1191 inStr.Replace(findWhat, replaceWith);
1192 }
1193 }
1194 }
1195 }
1196 }
1197
1198 void Language::CheckForTemplateAndTypedef(ParsedToken* token)
1199 {
1200 bool typedefMatch;
1201 bool templateMatch;
1202 int retry(0);
1203
1204 do {
1205 typedefMatch = OnTypedef(token);
1206 if(typedefMatch) {
1207 RunUserTypes(token);
1208 DoIsTypeAndScopeExist(token);
1209 }
1210
1211 // Attempt to fix the result
1212 if(typedefMatch) {
1213 DoExtractTemplateInitListFromInheritance(token);
1214
1215 // The typeName was a typedef, so make sure we update the template declaration list
1216 // with the actual type
1217 std::vector<TagEntryPtr> tags;
1218 GetTagsManager()->FindByPath(token->GetPath(), tags);
1219 if(tags.size() == 1 && !tags.at(0)->IsTypedef()) {
1220
1221 // Not a typedef
1222 token->SetTemplateArgList(DoExtractTemplateDeclarationArgs(tags.at(0)), m_templateArgs);
1223 token->SetIsTemplate(token->GetTemplateArgList().IsEmpty() == false);
1224
1225 } else if(tags.size() == 1) {
1226
1227 // Typedef
1228 TagEntryPtr t = tags.at(0);
1229 wxString pattern(t->GetPattern());
1230 wxArrayString tmpInitList;
1231 DoRemoveTempalteInitialization(pattern, tmpInitList);
1232
1233 // Incase any of the template initialization list is a
1234 // typedef, resolve it as well
1235 DoResolveTemplateInitializationList(tmpInitList);
1236 token->SetTemplateInitialization(tmpInitList);
1237 }
1238 }
1239
1240 templateMatch = OnTemplates(token);
1241 if(templateMatch) {
1242 if(!DoIsTypeAndScopeExist(token)) {
1243 std::vector<TagEntryPtr> dummyTags;
1244 DoCorrectUsingNamespaces(token, dummyTags);
1245 }
1246 token->SetIsTemplate(false);
1247 DoExtractTemplateInitListFromInheritance(token);
1248 }
1249
1250 if(templateMatch) {
1251 RunUserTypes(token);
1252 }
1253 retry++;
1254
1255 } while((typedefMatch || templateMatch) && retry < 15);
1256 }
1257
1258 void Language::DoResolveTemplateInitializationList(wxArrayString& tmpInitList)
1259 {
1260 for(size_t i = 0; i < tmpInitList.GetCount(); i++) {
1261 wxString fixedTemplateArg;
1262 wxString name = NameFromPath(tmpInitList.Item(i));
1263
1264 wxString tmpScope = ScopeFromPath(tmpInitList.Item(i));
1265 wxString scope = tmpScope == wxT("<global>") ? m_templateHelper.GetPath() : tmpScope;
1266
1267 ParsedToken tok;
1268 tok.SetTypeName(name);
1269 tok.SetTypeScope(scope);
1270
1271 DoSimpleTypedef(&tok);
1272
1273 name = tok.GetTypeName();
1274 scope = tok.GetTypeScope();
1275
1276 if(GetTagsManager()->GetDatabase()->IsTypeAndScopeExistLimitOne(name, scope) == false) {
1277 // no match, assume template: NAME only
1278 tmpInitList.Item(i) = name;
1279 } else
1280 tmpInitList.Item(i) = PathFromNameAndScope(name, scope);
1281 }
1282 }
1283
1284 wxArrayString Language::DoExtractTemplateDeclarationArgs(ParsedToken* token)
1285 {
1286 // Find a tag in the database that matches this find and
1287 // extract the template declaration for it
1288 std::vector<TagEntryPtr> tags;
1289 GetTagsManager()->FindByPath(token->GetPath(), tags);
1290 if(tags.size() != 1)
1291 return wxArrayString();
1292
1293 return DoExtractTemplateDeclarationArgs(tags.at(0));
1294 }
1295
1296 wxArrayString Language::DoExtractTemplateDeclarationArgsFromScope()
1297 {
1298 wxString tmpParentScope(m_templateHelper.GetTypeScope());
1299 wxString cuttedScope(tmpParentScope);
1300
1301 tmpParentScope.Replace(wxT("::"), wxT("@"));
1302 std::vector<TagEntryPtr> tags;
1303
1304 cuttedScope.Trim().Trim(false);
1305 while(!cuttedScope.IsEmpty()) {
1306
1307 // try all the scopes of thse parent:
1308 // for example:
1309 // assuming the parent scope is A::B::C
1310 // try to match:
1311 // A::B::C
1312 // A::B
1313 // A
1314 tags.clear();
1315 GetTagsManager()->FindByPath(cuttedScope, tags);
1316 if(tags.size() == 1) {
1317 if(tags.at(0)->GetPattern().Contains(wxT("template"))) {
1318 return DoExtractTemplateDeclarationArgs(tags.at(0));
1319 }
1320 }
1321
1322 // get the next scope to search
1323 cuttedScope = tmpParentScope.BeforeLast(wxT('@'));
1324 cuttedScope.Replace(wxT("@"), wxT("::"));
1325 cuttedScope.Trim().Trim(false);
1326
1327 tmpParentScope = tmpParentScope.BeforeLast(wxT('@'));
1328 }
1329
1330 return wxArrayString();
1331 }
1332
1333 wxArrayString Language::DoExtractTemplateDeclarationArgs(TagEntryPtr tag)
1334 {
1335 wxString pattern = tag->GetPattern();
1336 wxString templateString;
1337
1338 // extract the template declartion list
1339 CppScanner declScanner;
1340 declScanner.ReturnWhite(1);
1341 declScanner.SetText(_C(pattern));
1342 bool foundTemplate(false);
1343 int type(0);
1344 while(true) {
1345 type = declScanner.yylex();
1346 if(type == 0) // eof
1347 break;
1348
1349 wxString word = _U(declScanner.YYText());
1350 switch(type) {
1351 case IDENTIFIER:
1352 if(word == wxT("template")) {
1353 foundTemplate = true;
1354
1355 } else if(foundTemplate) {
1356 templateString << word;
1357 }
1358 break;
1359
1360 default:
1361 if(foundTemplate) {
1362 templateString << word;
1363 }
1364 break;
1365 }
1366 }
1367
1368 if(foundTemplate) {
1369 wxArrayString ar;
1370 ParseTemplateArgs(templateString, ar);
1371 return ar;
1372 }
1373 return wxArrayString();
1374 }
1375
1376 ///////////////////////////////////////////////////////////////////////////////////////////
1377 ///////////////////////////////////////////////////////////////////////////////////////////
1378 // Scope Class
1379 ///////////////////////////////////////////////////////////////////////////////////////////
1380 ///////////////////////////////////////////////////////////////////////////////////////////
1381
1382 void TemplateHelper::SetTemplateDeclaration(const wxString& templateDeclaration)
1383 {
1384 LanguageST::Get()->ParseTemplateArgs(templateDeclaration, this->templateDeclaration);
1385 }
1386
1387 void TemplateHelper::SetTemplateInstantiation(const wxString& tempalteInstantiation)
1388 {
1389 this->templateInstantiationVector.clear();
1390 wxArrayString l;
1391 LanguageST::Get()->ParseTemplateInitList(tempalteInstantiation, l);
1392 this->templateInstantiationVector.push_back(l);
1393 }
1394
1395 void TemplateHelper::SetTemplateInstantiation(const wxArrayString& templInstantiation)
1396 {
1397 // incase we are using template argument as template instantiation,
1398 // we should perform the replacement or else we will lose
1399 // the actual tempalte instantiation list
1400 // an example for such cases:
1401 // template <class _Tp> class vector {
1402 // typedef Something<_Tp> reference;
1403 // reference get();
1404 // };
1405 // Now, by attempting to resolve this:
1406 // vector<wxString> v;
1407 // v.get()->
1408 // we should replace Something<_Tp> into Something<wxString> *before* we continue with
1409 // the resolving
1410
1411 wxArrayString newInstantiationList = templInstantiation;
1412 // search for 'name' in the declaration list
1413 for(size_t i = 0; i < newInstantiationList.GetCount(); i++) {
1414 int where = this->templateDeclaration.Index(newInstantiationList.Item(i));
1415 if(where != wxNOT_FOUND) {
1416 wxString name = Substitute(newInstantiationList.Item(i));
1417 if(!name.IsEmpty())
1418 newInstantiationList[i] = name;
1419 }
1420 }
1421
1422 templateInstantiationVector.push_back(newInstantiationList);
1423 }
1424
1425 wxString TemplateHelper::Substitute(const wxString& name)
1426 {
1427 // for(size_t i=0; i<templateInstantiationVector.size(); i++) {
1428 int count = static_cast<int>(templateInstantiationVector.size());
1429 for(int i = count - 1; i >= 0; i--) {
1430 int where = templateDeclaration.Index(name);
1431 if(where != wxNOT_FOUND) {
1432 // it exists, return the name in the templateInstantiation list
1433 if(templateInstantiationVector.at(i).GetCount() > (size_t)where &&
1434 templateInstantiationVector.at(i).Item(where) != name)
1435 return templateInstantiationVector.at(i).Item(where);
1436 }
1437 }
1438 return wxT("");
1439 }
1440
1441 void TemplateHelper::Clear()
1442 {
1443 typeName.Clear();
1444 typeScope.Clear();
1445 templateInstantiationVector.clear();
1446 templateDeclaration.Clear();
1447 }
1448
1449 wxString TemplateHelper::GetPath() const
1450 {
1451 wxString path;
1452 if(typeScope != wxT("<global>"))
1453 path << typeScope << wxT("::");
1454
1455 path << typeName;
1456 return path;
1457 }
1458
1459 void Language::SetAdditionalScopes(const std::vector<wxString>& additionalScopes, const wxString& filename)
1460 {
1461 if(!(GetTagsManager()->GetCtagsOptions().GetFlags() & CC_DEEP_SCAN_USING_NAMESPACE_RESOLVING)) {
1462 this->m_additionalScopes = additionalScopes;
1463
1464 } else {
1465 this->m_additionalScopes.clear();
1466 // Use the cache to get the list of using namespaces.
1467 // The cache is populated by the CodeCompletionManager worker
1468 // thread when the file is loaded
1469 std::map<wxString, std::vector<wxString>>::iterator iter = m_additionalScopesCache.find(filename);
1470 if(iter != m_additionalScopesCache.end()) {
1471 this->m_additionalScopes = iter->second;
1472 }
1473
1474 // "using namespace" may not contains current namespace, so make sure we add it
1475 for(size_t i = 0; i < additionalScopes.size(); i++) {
1476 if(!(std::find(this->m_additionalScopes.begin(), this->m_additionalScopes.end(), additionalScopes.at(i)) !=
1477 this->m_additionalScopes.end())) {
1478 this->m_additionalScopes.push_back(additionalScopes.at(i));
1479 }
1480 }
1481 }
1482 }
1483
1484 const std::vector<wxString>& Language::GetAdditionalScopes() const { return m_additionalScopes; }
1485
1486 bool Language::OnSubscriptOperator(ParsedToken* token)
1487 {
1488 bool ret(false);
1489 // collect all functions of typename
1490 std::vector<TagEntryPtr> tags;
1491 wxString scope;
1492 wxString typeName(token->GetTypeName());
1493 wxString typeScope(token->GetTypeScope());
1494
1495 if(typeScope == wxT("<global>"))
1496 scope << token->GetTypeName();
1497 else
1498 scope << token->GetTypeScope() << wxT("::") << token->GetTypeName();
1499
1500 // this function will retrieve the ineherited tags as well
1501 GetTagsManager()->GetSubscriptOperator(scope, tags);
1502 if(tags.size() == 1) {
1503 // we found our overloading operator
1504 // extract the 'real' type from the pattern
1505 clFunction f;
1506 if(FunctionFromPattern(tags.at(0), f)) {
1507 token->SetTypeName(_U(f.m_returnValue.m_type.c_str()));
1508
1509 // first assume that the return value has the same scope like the parent (unless the return value has a
1510 // scope)
1511 token->SetTypeScope(f.m_returnValue.m_typeScope.empty() ? scope : _U(f.m_returnValue.m_typeScope.c_str()));
1512
1513 // Call the magic method that fixes typename/typescope
1514 DoIsTypeAndScopeExist(token);
1515 ret = true;
1516 }
1517 }
1518 return ret;
1519 }
1520
1521 bool Language::RunUserTypes(ParsedToken* token, const wxString& entryPath)
1522 {
1523 wxStringTable_t typeMap = GetTagsManager()->GetCtagsOptions().GetTypesMap();
1524 // HACK1: Let the user override the parser decisions
1525 wxString path = entryPath.IsEmpty() ? token->GetPath() : entryPath;
1526 wxStringTable_t::const_iterator where = typeMap.find(path);
1527 if(where != typeMap.end()) {
1528 wxArrayString argList;
1529
1530 // Split to name and scope
1531 wxString name, scope;
1532
1533 scope = where->second.BeforeFirst(wxT('<'));
1534 name = scope.AfterLast(wxT(':'));
1535 scope = scope.BeforeLast(wxT(':'));
1536 if(scope.EndsWith(wxT(":"))) {
1537 scope.RemoveLast();
1538 }
1539 token->SetTypeName(name);
1540
1541 // Did we got a scope as well?
1542 if(!scope.IsEmpty())
1543 token->SetTypeScope(scope);
1544
1545 wxString argsString = where->second.AfterFirst(wxT('<'));
1546 argsString.Prepend(wxT("<"));
1547
1548 DoRemoveTempalteInitialization(argsString, argList);
1549 if(argList.IsEmpty() == false) {
1550 // If we already got a concrete template initialization list
1551 // do not override it with the dummy one taken from the user
1552 // type definition
1553 if(token->GetTemplateInitialization().IsEmpty())
1554 token->SetTemplateInitialization(argList);
1555 token->SetIsTemplate(true);
1556 }
1557 return true;
1558 }
1559 return false;
1560 }
1561
1562 bool Language::DoIsTypeAndScopeExist(ParsedToken* token)
1563 {
1564 // Check to see if this is a primitve type...
1565 if(is_primitive_type(token->GetTypeName().mb_str(wxConvUTF8).data())) {
1566 return true;
1567 }
1568
1569 // Does the typename is happen to be a template argument?
1570 if(m_templateArgs.count(token->GetTypeName())) {
1571 return true;
1572 }
1573
1574 std::vector<wxString> scopes_to_try = GetAdditionalScopes();
1575 wxArrayString parent_scopes = ::wxStringTokenize(token->GetFullScope(), ":", wxTOKEN_STRTOK);
1576
1577 std::vector<wxString> additional_sscopes;
1578 while(!parent_scopes.empty()) {
1579 wxString tmpscope;
1580 for(const wxString& s : parent_scopes) {
1581 if(!tmpscope.empty()) {
1582 tmpscope << "::";
1583 }
1584 tmpscope << s;
1585 }
1586 additional_sscopes.push_back(tmpscope);
1587 parent_scopes.pop_back();
1588 }
1589
1590 // prepend the `additional_sscopes` to the `scopes_to_try`
1591 scopes_to_try.insert(scopes_to_try.begin(), additional_sscopes.begin(), additional_sscopes.end());
1592 wxString type = token->GetTypeName();
1593 wxString scope;
1594
1595 bool res = false;
1596 for(const wxString& s : scopes_to_try) {
1597 scope = s;
1598 res = GetTagsManager()->IsTypeAndScopeExists(type, scope);
1599 if(res) {
1600 token->SetTypeName(type);
1601 token->SetTypeScope(scope);
1602 return true;
1603 }
1604 }
1605 return false;
1606 }
1607
1608 bool Language::DoCorrectUsingNamespaces(ParsedToken* token, std::vector<TagEntryPtr>& tags)
1609 {
1610 wxString type(token->GetTypeName());
1611 wxString scope(token->GetTypeScope());
1612 bool res = CorrectUsingNamespace(type, scope, token->GetContextScope(), tags);
1613
1614 token->SetTypeName(type);
1615 token->SetTypeScope(scope);
1616
1617 return res;
1618 }
1619
1620 void Language::DoExtractTemplateInitListFromInheritance(TagEntryPtr tag, ParsedToken* token)
1621 {
1622 wxArrayString initList;
1623 wxString parent;
1624 wxString scope;
1625
1626 if(token->GetIsTemplate()) {
1627 // if this token is already tagged as 'template' dont
1628 // change this
1629 return;
1630 }
1631
1632 // Loop over the parents of 'tag' and search for any template parent
1633 // In case we find one, extract the template initialization list from
1634 // the parent inheritance line and copy it to the current token.
1635
1636 // If we do find a match, search for the parent itself in the database
1637 // and extract its template declaration list
1638 if(tag->IsClass() || tag->IsStruct()) {
1639 // returns the inheris string with template initialization list
1640 wxArrayString inherits = tag->GetInheritsAsArrayWithTemplates();
1641 wxArrayString inheritsNoTemplate = tag->GetInheritsAsArrayNoTemplates();
1642 size_t i = 0;
1643 for(; i < inherits.size(); i++) {
1644 DoRemoveTempalteInitialization(inherits.Item(i), initList);
1645 if(initList.IsEmpty() == false) {
1646 break;
1647 }
1648 }
1649
1650 if(initList.IsEmpty() == false) {
1651 token->SetIsTemplate(true);
1652 token->SetTemplateInitialization(initList);
1653
1654 if(i < inheritsNoTemplate.GetCount()) {
1655 parent = inheritsNoTemplate.Item(i);
1656 scope = tag->GetScope();
1657
1658 // Find this parent
1659 GetTagsManager()->IsTypeAndScopeExists(parent, scope);
1660 if(scope.IsEmpty() == false && scope != wxT("<global>")) {
1661 parent.Prepend(scope + wxT("::"));
1662 }
1663
1664 std::vector<TagEntryPtr> tags;
1665 GetTagsManager()->FindByPath(parent, tags);
1666 if(tags.size() == 1) {
1667 wxArrayString newArgList = DoExtractTemplateDeclarationArgs(tags.at(0));
1668 if(newArgList.IsEmpty() == false) {
1669 token->SetTemplateArgList(newArgList, m_templateArgs);
1670 }
1671 }
1672 }
1673 }
1674 }
1675 }
1676
1677 void Language::DoExtractTemplateInitListFromInheritance(ParsedToken* token)
1678 {
1679 std::vector<TagEntryPtr> tags;
1680 GetTagsManager()->FindByPath(token->GetPath(), tags);
1681 if(tags.size() == 1) {
1682 DoExtractTemplateInitListFromInheritance(tags.at(0), token);
1683 }
1684 }
1685
1686 void Language::DoFixTokensFromVariable(TokenContainer* tokeContainer, const wxString& variableDecl)
1687 {
1688 // the current tokan is indeed defined on the local stack.
1689 // what we do now is creating new chain of tokens based on the
1690 // variable declaration, removing the token that represents the local variable
1691 // and link the two chains together
1692 //
1693 // In addition, we copy the subscript operator flag
1694 // from the variable into the token declaration
1695 ParsedToken* token = tokeContainer->current;
1696 wxString scopeName = token->GetCurrentScopeName();
1697 wxString op = token->GetOperator();
1698 bool subscript = token->GetSubscriptOperator();
1699
1700 wxString newTextToParse;
1701 newTextToParse << variableDecl << op;
1702 m_tokenScanner.Reset(newTextToParse);
1703 ParsedToken* newToken = ParseTokens(scopeName);
1704 if(newToken) {
1705 // copy the subscript operator from the local variable token to the
1706 // last token in the new parsed list
1707 ParsedToken* lastToken = newToken;
1708 while(lastToken && lastToken->GetNext()) {
1709 lastToken = lastToken->GetNext();
1710 }
1711 lastToken->SetSubscriptOperator(subscript);
1712 // If the local variable token has more tokens down the chain,
1713 // disconnect it from them while connecting the rest of the
1714 // tokens to the newly parsed list
1715 if(token->GetNext()) {
1716 lastToken->SetNext(token->GetNext());
1717 token->GetNext()->SetPrev(lastToken);
1718 token->SetNext(NULL);
1719 }
1720 // free the token
1721 ParsedToken::DeleteTokens(token);
1722 tokeContainer->head = newToken;
1723 tokeContainer->current = newToken;
1724 tokeContainer->SetRewind(true);
1725 }
1726 }
1727
1728 void Language::DoExtractTemplateArgsFromSelf(ParsedToken* token)
1729 {
1730 // if it is already marked as template, dont change it
1731 if(token->GetIsTemplate())
1732 return;
1733
1734 std::vector<TagEntryPtr> tags;
1735 GetTagsManager()->FindByPath(token->GetPath(), tags);
1736 if(tags.size() == 1 && !tags.at(0)->IsTypedef()) {
1737 // Not a typedef
1738 token->SetTemplateArgList(DoExtractTemplateDeclarationArgs(tags.at(0)), m_templateArgs);
1739 token->SetIsTemplate(token->GetTemplateArgList().IsEmpty() == false);
1740 }
1741 }
1742
1743 // Adaptor to Language
1744 static Language* gs_Language = NULL;
1745 void LanguageST::Free()
1746 {
1747 if(gs_Language) {
1748 delete gs_Language;
1749 }
1750 gs_Language = NULL;
1751 }
1752
1753 Language* LanguageST::Get()
1754 {
1755 if(gs_Language == NULL)
1756 gs_Language = new Language();
1757 return gs_Language;
1758 }
1759
1760 wxString Language::ApplyCtagsReplacementTokens(const wxString& in)
1761 {
1762 // First, get the replacement map
1763 CLReplacementList replacements;
1764 const wxStringTable_t& replacementMap = GetTagsManager()->GetCtagsOptions().GetTokensWxMap();
1765 wxStringTable_t::const_iterator iter = replacementMap.begin();
1766 for(; iter != replacementMap.end(); ++iter) {
1767
1768 if(iter->second.IsEmpty())
1769 continue;
1770
1771 wxString pattern = iter->first;
1772 wxString replace = iter->second;
1773 pattern.Trim().Trim(false);
1774 replace.Trim().Trim(false);
1775 CLReplacement repl;
1776 repl.construct(pattern.To8BitData().data(), replace.To8BitData().data());
1777 if(repl.is_ok) {
1778 replacements.push_back(repl);
1779 }
1780 }
1781
1782 if(replacements.empty())
1783 return in;
1784
1785 // Now, apply the replacements
1786 wxString outputStr;
1787 wxArrayString lines = ::wxStringTokenize(in, wxT("\r\n"), wxTOKEN_STRTOK);
1788 for(size_t i = 0; i < lines.GetCount(); i++) {
1789 std::string outStr = lines.Item(i).mb_str(wxConvUTF8).data();
1790 CLReplacementList::iterator iter = replacements.begin();
1791 for(; iter != replacements.end(); iter++) {
1792 ::CLReplacePatternA(outStr, *iter, outStr);
1793 }
1794
1795 outputStr << wxString(outStr.c_str(), wxConvUTF8) << wxT("\n");
1796 }
1797 return outputStr;
1798 }
1799
1800 int Language::DoReadClassName(CppScanner& scanner, wxString& clsname) const
1801 {
1802 clsname.clear();
1803 int type = 0;
1804
1805 while(true) {
1806 type = scanner.yylex();
1807 if(type == 0)
1808 return 0;
1809
1810 if(type == IDENTIFIER) {
1811 clsname = scanner.YYText();
1812
1813 } else if(type == '{' || type == ':') {
1814 return type;
1815
1816 } else if(type == ';') {
1817 // we probably encountered a forward declaration or 'friend' statement
1818 clsname.Clear();
1819 return (int)';';
1820 }
1821 }
1822 return 0;
1823 }
1824
1825 bool Language::InsertFunctionDecl(const wxString& clsname, const wxString& functionDecl, wxString& sourceContent,
1826 int visibility)
1827 {
1828 // detemine the visibility requested
1829 int typeVisibility = lexPUBLIC;
1830 wxString strVisibility = wxT("public:\n");
1831 switch(visibility) {
1832 default:
1833 case 0:
1834 typeVisibility = lexPUBLIC;
1835 strVisibility = wxT("public:\n");
1836 break;
1837
1838 case 1:
1839 typeVisibility = lexPROTECTED;
1840 strVisibility = wxT("protected:\n");
1841 break;
1842
1843 case 2:
1844 typeVisibility = lexPRIVATE;
1845 strVisibility = wxT("private:\n");
1846 break;
1847 }
1848
1849 // step 1: locate the class
1850 CppScanner scanner;
1851 scanner.SetText(sourceContent.mb_str(wxConvUTF8).data());
1852
1853 bool success = false;
1854 int type = 0;
1855 while(true) {
1856 type = scanner.yylex();
1857 if(type == 0) {
1858 return false; // EOF
1859 }
1860
1861 if(type == lexCLASS) {
1862 wxString name;
1863 type = DoReadClassName(scanner, name);
1864 if(type == 0) {
1865 return false;
1866 }
1867
1868 if(name == clsname) {
1869 // We found the lex
1870 success = true;
1871 break;
1872 }
1873 }
1874 }
1875
1876 if(!success)
1877 return false;
1878
1879 // scanner is pointing on the class
1880 // We now need to find the first opening curly brace
1881 success = false;
1882 if(type == '{') {
1883 // DoReadClassName already consumed the '{' character
1884 // mark this as a success and continue
1885 success = true;
1886
1887 } else {
1888 while(true) {
1889 type = scanner.yylex();
1890 if(type == 0)
1891 return false; // EOF
1892
1893 if(type == '{') {
1894 success = true;
1895 break;
1896 }
1897 }
1898 }
1899
1900 if(!success)
1901 return false;
1902
1903 // search for requested visibility, if we could not locate it
1904 // locate the class ending curly brace
1905 success = false;
1906 int depth = 1;
1907 int visibilityLine = wxNOT_FOUND;
1908 int closingCurlyBraceLine = wxNOT_FOUND;
1909 while(true) {
1910 type = scanner.yylex();
1911 if(type == 0)
1912 break;
1913
1914 if(type == typeVisibility) {
1915 visibilityLine = scanner.LineNo();
1916 break;
1917 }
1918
1919 if(type == '{') {
1920 depth++;
1921
1922 } else if(type == '}') {
1923 depth--;
1924
1925 if(depth == 0) {
1926 // reached end of class
1927 closingCurlyBraceLine = scanner.LineNo();
1928 break;
1929 }
1930 }
1931 }
1932
1933 wxString strToInsert;
1934 int insertLine = visibilityLine;
1935 if(visibilityLine == wxNOT_FOUND) {
1936 // could not locate the visibility line
1937 insertLine = closingCurlyBraceLine;
1938 strToInsert << strVisibility << functionDecl;
1939 insertLine--; // Place it one line on top of the curly brace
1940
1941 } else {
1942 strToInsert << functionDecl;
1943 }
1944
1945 if(insertLine == wxNOT_FOUND)
1946 // could not find any of the two
1947 return false;
1948
1949 wxString newContent;
1950 wxArrayString lines = ::wxStringTokenize(sourceContent, wxT("\n"), wxTOKEN_RET_DELIMS);
1951 for(size_t i = 0; i < lines.GetCount(); i++) {
1952 if(insertLine == (int)i) {
1953 newContent << strToInsert;
1954 }
1955 newContent << lines.Item(i);
1956 }
1957 sourceContent = newContent;
1958 return true;
1959 }
1960
1961 int Language::GetBestLineForForwardDecl(const wxString& fileContent) const
1962 {
1963 // Locating the place for adding forward declaration is one line on top of the first non comment/preprocessor
1964 // code. So basically we constrcut our lexer and call yylex() once (it will skip all whitespaces/comments/pp...
1965 // )
1966 CppLexer lexer(fileContent.mb_str(wxConvISO8859_1).data());
1967
1968 while(true) {
1969 int type = lexer.lex();
1970 if(type == 0) {
1971 // EOF
1972 return wxNOT_FOUND;
1973 }
1974 break;
1975 }
1976 // stc is 0 based
1977 int line = lexer.line_number();
1978 if(line)
1979 --line;
1980 return line;
1981 }
1982
1983 void Language::UpdateAdditionalScopesCache(const wxString& filename, const std::vector<wxString>& additionalScopes)
1984 {
1985 if(m_additionalScopesCache.count(filename)) {
1986 m_additionalScopesCache.erase(filename);
1987 }
1988 m_additionalScopesCache.insert(std::make_pair(filename, additionalScopes));
1989 }
1990
1991 void Language::ClearAdditionalScopesCache() { m_additionalScopesCache.clear(); }
1992
1993 CxxVariable::Ptr_t Language::FindLocalVariable(const wxString& name)
1994 {
1995 if(m_locals.empty()) {
1996 return nullptr;
1997 }
1998 CxxVariable::Map_t::iterator iter = m_locals.find(name);
1999 if(iter == m_locals.end()) {
2000 return nullptr;
2001 }
2002 return iter->second;
2003 }
2004
2005 CxxVariable::Ptr_t Language::FindVariableInScope(const wxString& scope, const wxString& name)
2006 {
2007 CxxVariableScanner scanner(scope, eCxxStandard::kCxx11, GetTagsManager()->GetCtagsOptions().GetTokensWxMap(),
2008 false);
2009 CxxVariable::Map_t M = scanner.GetVariablesMap();
2010 if(M.count(name) == 0) {
2011 return nullptr;
2012 }
2013 return M[name];
2014 }