Debian Codegraph @

CodeLite/pptable.cpp

raw
1 //////////////////////////////////////////////////////////////////////////////
2 //////////////////////////////////////////////////////////////////////////////
3 //
4 // copyright : (C) 2014 Eran Ifrah
5 // file name : pptable.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
26 #include "pptable.h"
27 #include <wx/tokenzr.h>
28 #include <set>
29 #include "CxxLexerAPI.h"
30 #include "CxxScannerTokens.h"
31 #include <algorithm>
32
33 bool IsWordChar(const wxString& s, int strSize)
34 {
35 if(strSize) {
36 return s.find_first_of(wxT("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890_")) !=
37 wxString::npos;
38
39 } else {
40 return s.find_first_of(wxT("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_")) != wxString::npos;
41 }
42 }
43
44 bool IsWordCharA(char c, int strSize)
45 {
46 if(strSize) {
47 return ((c >= 97 && c <= 122) || // a-z
48 (c >= 65 && c <= 90) || // A-Z
49 (c >= 48 && c <= 57) || // 0-9
50 (c == '_'));
51
52 } else {
53 return ((c >= 97 && c <= 122) || // a-z
54 (c >= 65 && c <= 90) || // A-Z
55 (c == '_'));
56 }
57 }
58
59 std::string ReplaceWordA(const std::string& str, const std::string& word, const std::string& replaceWith)
60 {
61 char currChar;
62 char nextChar;
63 std::string currentWord;
64 std::string output;
65
66 output.reserve(str.length() * 2);
67
68 for(size_t i = 0; i < str.length(); i++) {
69 // Look ahead
70 if(str.length() > i + 1) {
71 nextChar = str[i + 1];
72 } else {
73 // we are at the end of buffer
74 nextChar = '\0';
75 }
76
77 currChar = str[i];
78 if(!IsWordCharA(currChar, currentWord.length())) {
79 output += str[i];
80 currentWord.clear();
81
82 } else {
83
84 currentWord += currChar;
85 if(IsWordCharA(nextChar, currentWord.length())) {
86 // do nothing
87
88 } else if(!IsWordCharA(nextChar, currentWord.length()) && currentWord == word) {
89 output += replaceWith;
90 currentWord.clear();
91
92 } else {
93 output += currentWord;
94 currentWord.clear();
95 }
96 }
97 }
98 return output;
99 }
100
101 // Helper string find metho
102 wxString ReplaceWord(const wxString& str, const wxString& word, const wxString& replaceWith)
103 {
104 wxString currChar;
105 wxString nextChar;
106 wxString currentWord;
107 wxString output;
108 for(size_t i = 0; i < str.Length(); i++) {
109 // Look ahead
110 if(str.Length() > i + 1) {
111 nextChar = str[i + 1];
112 } else {
113 // we are at the end of buffer
114 nextChar = wxT('\0');
115 }
116
117 currChar = str[i];
118 if(!IsWordChar(currChar, currentWord.Length())) {
119 output << str[i];
120 currentWord.Clear();
121
122 } else {
123
124 currentWord << currChar;
125 if(IsWordChar(nextChar, currentWord.Length())) {
126 // do nothing
127
128 } else if(!IsWordChar(nextChar, currentWord.Length()) && currentWord == word) {
129 output << replaceWith;
130 currentWord.Clear();
131
132 } else {
133 output << currentWord;
134 currentWord.Clear();
135 }
136 }
137 }
138 return output;
139 }
140
141 void TokenizeWords(const wxString& str, std::list<wxString>& outputList)
142 {
143 outputList.clear();
144 Scanner_t scanner = ::LexerNew(str);
145 if(scanner) {
146 CxxLexerToken token;
147 while(::LexerNext(scanner, token)) {
148 if(token.GetType() == T_IDENTIFIER || token.GetType() == T_PP_IDENTIFIER) {
149 outputList.push_back(token.GetWXString());
150 // put a limit or we might run into memory issues
151 if(outputList.size() >= 1000) {
152 break;
153 }
154 }
155 }
156 // Destroy the lexer
157 ::LexerDestroy(&scanner);
158 }
159 }
160
161 static PPTable* ms_instance = NULL;
162
163 void PPToken::processArgs(const wxString& argsList)
164 {
165 args = wxStringTokenize(argsList, wxT(","), wxTOKEN_STRTOK);
166
167 // replace all occurances of 'arg' with %1, %2 etc
168 for(size_t i = 0; i < args.GetCount(); i++) {
169 wxString replaceWith = wxString::Format(wxT("%%%d"), (int)i);
170 std::string res = ReplaceWordA(
171 replacement.To8BitData().data(), args.Item(i).To8BitData().data(), replaceWith.To8BitData().data());
172 if(res.empty()) {
173 replacement.clear();
174
175 } else {
176 replacement = wxString::From8BitData(res.c_str());
177 }
178 }
179 }
180
181 void PPToken::print(wxFFile& fp)
182 {
183 wxString buff;
184 buff << name << wxT("(") << (flags & IsFunctionLike) << wxT(")") << wxT("=") << replacement << wxT("\n");
185 fp.Write(buff);
186 }
187
188 wxString PPToken::fullname() const
189 {
190 wxString fullname;
191 fullname << name;
192 if(flags & IsFunctionLike) {
193 fullname << wxT("(");
194 for(size_t i = 0; i < args.size(); i++) {
195 fullname << wxT("%") << i << wxT(",");
196 }
197 if(args.size()) {
198 fullname.RemoveLast();
199 }
200 fullname << wxT(")");
201 }
202 return fullname;
203 }
204
205 void PPToken::squeeze()
206 {
207 std::set<wxString> alreadyReplacedMacros;
208
209 // perform the squeeze 5 times max
210 for(size_t count = 0; count < 5; count++) {
211 bool modified(false);
212
213 // get list of possible macros in the replacement
214 std::list<wxString> tmpWords;
215 TokenizeWords(replacement, tmpWords);
216 wxArrayString words;
217 if(tmpWords.empty()) break;
218
219 // Make room for at least tmpWords.size() items
220 words.Alloc(tmpWords.size());
221
222 // make sure that a word is not been replaced more than once
223 // this will avoid recursion
224 // an example (taken from qglobal.h of the Qt library):
225 //
226 // #define qDebug QT_NO_QDEBUG_MACRO
227 // #define QT_NO_QDEBUG_MACRO if(1); else qDebug
228 //
229 std::for_each(tmpWords.begin(), tmpWords.end(), [&](const wxString& word){
230 if(alreadyReplacedMacros.count(word) == 0) {
231 alreadyReplacedMacros.insert(word);
232 words.Add(word);
233 }
234 });
235
236 for(size_t i = 0; i < words.size(); i++) {
237 PPToken tok = PPTable::Instance()->Token(words.Item(i));
238 if(tok.flags & IsValid) {
239 if(tok.flags & IsFunctionLike) {
240 int where = replacement.Find(words.Item(i));
241 if(where != wxNOT_FOUND) {
242 wxString initList;
243 wxArrayString initListArr;
244 if(readInitList(replacement, where + words.Item(i).Length(), initList, initListArr)) {
245 tok.expandOnce(initListArr);
246
247 replacement.Remove(where, words.Item(i).Length() + initList.Length());
248 tok.replacement.Replace(wxT("##"), wxT(""));
249 replacement.insert(where, tok.replacement);
250 modified = true;
251 }
252 }
253
254 } else {
255 if(replacement.Replace(words.Item(i), tok.replacement)) {
256 modified = true;
257 }
258 }
259 }
260 }
261
262 if(!modified) break;
263 }
264 replacement.Replace(wxT("##"), wxT(""));
265 }
266
267 bool
268 PPToken::readInitList(const std::string& in, size_t from, std::string& initList, std::vector<std::string>& initListArr)
269 {
270 if(in.length() < from) {
271 return false;
272 }
273
274 std::string tmpString = in.substr(from);
275 size_t start = tmpString.find('(');
276 if(start == std::string::npos) {
277 return false;
278 }
279
280 // skip the open brace
281 tmpString = tmpString.substr(start + 1);
282
283 for(size_t i = 0; i < start; i++) {
284 initList += " ";
285 }
286
287 initList += "(";
288 std::string word;
289 int depth(1);
290
291 for(size_t i = 0; i < tmpString.length(); i++) {
292 char ch = tmpString[i];
293 initList += ch;
294 switch(ch) {
295 case ')':
296 depth--;
297 if(depth == 0) {
298 initListArr.push_back(word);
299 return true;
300 } else {
301 word += ch;
302 }
303 break;
304 case '(':
305 depth++;
306 word += ch;
307 break;
308 case ',':
309 if(depth == 1) {
310 initListArr.push_back(word);
311 word.clear();
312 } else {
313 word += ch;
314 }
315 break;
316 default:
317 word += ch;
318 break;
319 }
320 }
321 return false;
322 }
323
324 bool PPToken::readInitList(const wxString& in, int from, wxString& initList, wxArrayString& initListArr)
325 {
326 // sanity
327 if(in.length() > 100) return false;
328
329 if((int)in.Length() < from) {
330 return false;
331 }
332
333 wxString tmpString = in.Mid(from);
334 int start = tmpString.Find(wxT("("));
335 if(start == wxNOT_FOUND) {
336 return false;
337 }
338 tmpString = tmpString.Mid(start + 1);
339
340 for(size_t i = 0; i < (size_t)start; i++) {
341 initList << wxT(" ");
342 }
343
344 initList << wxT("(");
345 wxString word;
346 int depth(1);
347
348 for(size_t i = 0; i < tmpString.Length(); i++) {
349 wxChar ch = tmpString[i];
350 initList << ch;
351 switch(ch) {
352 case wxT(')'):
353 depth--;
354 if(depth == 0) {
355 initListArr.Add(word);
356 return true;
357 } else {
358 word << ch;
359 }
360 break;
361 case wxT('('):
362 depth++;
363 word << ch;
364 break;
365 case wxT(','):
366 if(depth == 1) {
367 initListArr.Add(word);
368 word.Clear();
369 } else {
370 word << ch;
371 }
372 break;
373 default:
374 word << ch;
375 break;
376 }
377 }
378 return false;
379 }
380
381 void PPToken::expandOnce(const wxArrayString& initList)
382 {
383 if(initList.size() != args.size()) return;
384
385 for(size_t i = 0; i < args.size(); i++) {
386 wxString placeHolder;
387 placeHolder << wxT("%") << i;
388
389 wxString replaceWith = initList.Item(i);
390 replaceWith.Trim().Trim(false);
391
392 if(replaceWith.Contains(placeHolder)) continue;
393
394 replacement.Replace(placeHolder, initList.Item(i));
395 }
396 }
397
398 wxString PPToken::signature() const
399 {
400 wxString sig;
401 if(flags & IsFunctionLike) {
402 sig << wxT("(");
403 for(size_t i = 0; i < args.size(); i++) {
404 sig << wxT("%") << i << wxT(",");
405 }
406 if(args.size()) {
407 sig.RemoveLast();
408 }
409 sig << wxT(")");
410 }
411 return sig;
412 }
413
414 ///////////////////////////////////////////////////
415
416 PPTable::PPTable() {}
417
418 PPTable::~PPTable() {}
419
420 PPTable* PPTable::Instance()
421 {
422 if(ms_instance == NULL) {
423 ms_instance = new PPTable();
424 }
425 return ms_instance;
426 }
427
428 void PPTable::Release()
429 {
430 if(ms_instance) {
431 delete ms_instance;
432 }
433 ms_instance = NULL;
434 }
435
436 PPToken PPTable::Token(const wxString& name)
437 {
438 std::map<wxString, PPToken>::iterator iter = m_table.find(name);
439 if(iter == m_table.end()) {
440 return PPToken();
441 }
442
443 return iter->second;
444 }
445
446 void PPTable::Add(const PPToken& token)
447 {
448 if(token.name.IsEmpty()) return;
449
450 wxString name = token.name;
451 name.Trim().Trim(false);
452 std::map<wxString, PPToken>::iterator iter = m_table.find(name);
453 if(iter == m_table.end())
454 m_table[name] = token;
455 else {
456 // if the new token's replacement is empty and the current one is NOT empty,
457 // replace the two (we prefer empty replacements)
458 if(iter->second.flags & PPToken::IsOverridable && !iter->second.replacement.IsEmpty() &&
459 token.replacement.IsEmpty()) {
460 m_table[name] = token;
461 }
462 }
463 }
464
465 void PPTable::AddUsed(const wxString& name)
466 {
467 if(name.IsEmpty()) {
468 return;
469 }
470 m_namesUsed.insert(name);
471 }
472
473 void PPTable::Print(wxFFile& fp)
474 {
475 std::map<wxString, PPToken>::iterator iter = m_table.begin();
476 for(; iter != m_table.end(); iter++) {
477 iter->second.print(fp);
478 }
479 }
480
481 bool PPTable::Contains(const wxString& name)
482 {
483 std::map<wxString, PPToken>::iterator iter = m_table.find(name);
484 return iter != m_table.end();
485 }
486
487 wxString PPTable::Export()
488 {
489 wxString table;
490 std::map<wxString, PPToken>::iterator iter = m_table.begin();
491 for(; iter != m_table.end(); iter++) {
492 iter->second.squeeze();
493 wxString replacement = iter->second.replacement;
494 replacement.Trim().Trim(false);
495
496 // remove extra whitespaces
497 while(replacement.Replace(wxT(" "), wxT(" "))) {
498 }
499
500 if(replacement.IsEmpty()) {
501 table << iter->second.fullname() << wxT("\n");
502
503 } else if(iter->second.flags & PPToken::IsFunctionLike) {
504 table << iter->second.fullname() << wxT("=") << replacement << wxT("\n");
505
506 } else {
507 // macros with replacement but they are not in a form of a function
508 // we take only macros that thier replacement is not a number
509 long v(-1);
510 if(!replacement.ToLong(&v) && !replacement.ToLong(&v, 8) && !replacement.ToLong(&v, 16) &&
511 replacement.find(wxT('"')) == wxString::npos && !replacement.StartsWith(wxT("0x"))) {
512 table << iter->second.fullname() << wxT("=") << replacement << wxT("\n");
513 }
514 }
515 }
516 return table;
517 }
518
519 void PPTable::Squeeze()
520 {
521 std::map<wxString, PPToken>::iterator iter = m_table.begin();
522 for(; iter != m_table.end(); iter++) {
523 m_table[iter->first].squeeze();
524 }
525 }
526
527 void PPTable::Clear() { m_table.clear(); }
528
529 void PPTable::ClearNamesUsed() { m_namesUsed.clear(); }
530
531 bool CLReplacePattern(const wxString& in, const wxString& pattern, const wxString& replaceWith, wxString& outStr)
532 {
533 int where = pattern.Find(wxT("%0"));
534 if(where != wxNOT_FOUND) {
535 wxString replacement(replaceWith);
536
537 // a patterened expression
538 wxString searchFor = pattern.BeforeFirst(wxT('('));
539 where = in.Find(searchFor);
540 if(where == wxNOT_FOUND) {
541 return false;
542 }
543
544 wxString initList;
545 wxArrayString initListArr;
546 if(PPToken::readInitList(in, searchFor.Length() + where, initList, initListArr) == false) return false;
547
548 outStr = in;
549 // update the 'replacement' with the actual values ( replace %0..%n)
550 for(size_t i = 0; i < initListArr.size(); i++) {
551 wxString placeHolder;
552 placeHolder << wxT("%") << i;
553 replacement.Replace(placeHolder, initListArr.Item(i));
554 }
555
556 outStr.Remove(where, searchFor.Length() + initList.Length());
557 outStr.insert(where, replacement);
558 return true;
559
560 } else {
561 if(in.Find(pattern) == wxNOT_FOUND) {
562 return false;
563 }
564 // simple replacement
565 outStr = ReplaceWord(in, pattern, replaceWith);
566 return outStr != in;
567 }
568 }
569
570 std::string replacement;
571
572 bool CLReplacePatternA(const std::string& in, const CLReplacement& repl, std::string& outStr)
573 {
574 if(repl.is_compound) {
575 size_t where = in.find(repl.searchFor);
576 if(where == std::string::npos) return false;
577
578 std::string initList;
579 std::vector<std::string> initListArr;
580 if(PPToken::readInitList(in, repl.searchFor.length() + where, initList, initListArr) == false) return false;
581
582 // update the 'replacement' with the actual values ( replace %0..%n)
583 replacement = repl.replaceWith;
584 char placeHolder[4];
585 for(size_t i = 0; i < initListArr.size(); i++) {
586
587 memset(placeHolder, 0, sizeof(placeHolder));
588 sprintf(placeHolder, "%%%d", (int)i);
589
590 size_t pos = replacement.find(placeHolder);
591 const std::string& init = initListArr[i];
592 while(pos != std::string::npos) {
593 replacement.replace(pos, strlen(placeHolder), init.c_str());
594
595 // search for the next match
596 pos = replacement.find(placeHolder, pos + 1);
597 }
598 }
599
600 outStr = in;
601 where = outStr.find(repl.searchFor);
602 if(where == std::string::npos) return false;
603
604 outStr.replace(where, repl.searchFor.length() + initList.length(), replacement);
605 return true;
606
607 } else {
608
609 size_t where = in.find(repl.searchFor);
610 if(where == std::string::npos) {
611 return false;
612 }
613
614 outStr = ReplaceWordA(in, repl.searchFor, repl.replaceWith);
615
616 // outStr = in;
617 // outStr.replace(where, repl.searchFor.length(), repl.replaceWith);
618
619 // simple replacement
620 return outStr != in;
621 }
622 }
623
624 void CLReplacement::construct(const std::string& pattern, const std::string& replacement)
625 {
626 is_ok = true;
627 full_pattern = pattern;
628 is_compound = full_pattern.find("%0") != std::string::npos;
629 if(is_compound) {
630 // a patterened expression
631 replaceWith = replacement;
632 size_t where = pattern.find('(');
633 if(where == std::string::npos) {
634 is_ok = false;
635 return;
636 }
637
638 searchFor = pattern.substr(0, where);
639 if(searchFor.empty()) {
640 is_ok = false;
641 return;
642 }
643
644 } else {
645 // simple Key=Value pair
646 replaceWith = replacement;
647 searchFor = full_pattern;
648 }
649 }