forked from danmar/cppcheck
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpreprocessor.cpp
2935 lines (2538 loc) · 103 KB
/
preprocessor.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2012 Daniel Marjamäki and Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "preprocessor.h"
#include "tokenize.h"
#include "token.h"
#include "path.h"
#include "errorlogger.h"
#include "settings.h"
#include <algorithm>
#include <sstream>
#include <fstream>
#include <cstdlib>
#include <cctype>
#include <vector>
#include <set>
#include <stack>
bool Preprocessor::missingIncludeFlag;
char Preprocessor::macroChar = char(1);
Preprocessor::Preprocessor(Settings *settings, ErrorLogger *errorLogger) : _settings(settings), _errorLogger(errorLogger)
{
}
void Preprocessor::writeError(const std::string &fileName, const unsigned int linenr, ErrorLogger *errorLogger, const std::string &errorType, const std::string &errorText)
{
if (!errorLogger)
return;
std::list<ErrorLogger::ErrorMessage::FileLocation> locationList;
ErrorLogger::ErrorMessage::FileLocation loc;
loc.line = linenr;
loc.setfile(fileName);
locationList.push_back(loc);
errorLogger->reportErr(ErrorLogger::ErrorMessage(locationList,
Severity::error,
errorText,
errorType,
false));
}
static unsigned char readChar(std::istream &istr, unsigned int bom)
{
unsigned char ch = (unsigned char)istr.get();
// For UTF-16 encoded files the BOM is 0xfeff/0xfffe. If the
// character is non-ASCII character then replace it with 0xff
if (bom == 0xfeff || bom == 0xfffe) {
unsigned char ch2 = (unsigned char)istr.get();
int ch16 = (bom == 0xfeff) ? (ch<<8 | ch2) : (ch2<<8 | ch);
ch = (unsigned char)((ch16 >= 0x80) ? 0xff : ch16);
}
// Handling of newlines..
if (ch == '\r') {
ch = '\n';
if (bom == 0 && (char)istr.peek() == '\n')
(void)istr.get();
else if (bom == 0xfeff || bom == 0xfffe) {
int c1 = istr.get();
int c2 = istr.get();
int ch16 = (bom == 0xfeff) ? (c1<<8 | c2) : (c2<<8 | c1);
if (ch16 != '\n') {
istr.unget();
istr.unget();
}
}
}
return ch;
}
// Concatenates a list of strings, inserting a separator between parts
static std::string join(const std::set<std::string>& list, char separator)
{
std::string s;
for (std::set<std::string>::const_iterator it = list.begin(); it != list.end(); ++it) {
if (!s.empty())
s += separator;
s += *it;
}
return s;
}
// Removes duplicate string portions separated by the specified separator
static std::string unify(const std::string &s, char separator)
{
std::set<std::string> parts;
std::string::size_type prevPos = 0;
for (std::string::size_type pos = 0; pos < s.length(); ++pos) {
if (s[pos] == separator) {
if (pos > prevPos)
parts.insert(s.substr(prevPos, pos - prevPos));
prevPos = pos + 1;
}
}
if (prevPos < s.length())
parts.insert(s.substr(prevPos));
return join(parts, separator);
}
/** Just read the code into a string. Perform simple cleanup of the code */
std::string Preprocessor::read(std::istream &istr, const std::string &filename)
{
// The UTF-16 BOM is 0xfffe or 0xfeff.
unsigned int bom = 0;
if (istr.peek() >= 0xfe) {
bom = (istr.get() << 8);
if (istr.peek() >= 0xfe)
bom |= istr.get();
}
// ------------------------------------------------------------------------------------------
//
// handling <backslash><newline>
// when this is encountered the <backslash><newline> will be "skipped".
// on the next <newline>, extra newlines will be added
std::ostringstream code;
unsigned int newlines = 0;
for (unsigned char ch = readChar(istr,bom); istr.good(); ch = readChar(istr,bom)) {
// Replace assorted special chars with spaces..
if (((ch & 0x80) == 0) && (ch != '\n') && (std::isspace(ch) || std::iscntrl(ch)))
ch = ' ';
// <backslash><newline>..
// for gcc-compatibility the trailing spaces should be ignored
// for vs-compatibility the trailing spaces should be kept
// See tickets #640 and #1869
// The solution for now is to have a compiler-dependent behaviour.
if (ch == '\\') {
unsigned char chNext;
#ifdef __GNUC__
// gcc-compatibility: ignore spaces
for (;;) {
chNext = (unsigned char)istr.peek();
if (chNext != '\n' && chNext != '\r' &&
(std::isspace(chNext) || std::iscntrl(chNext))) {
// Skip whitespace between <backslash> and <newline>
(void)readChar(istr,bom);
continue;
}
break;
}
#else
// keep spaces
chNext = (unsigned char)istr.peek();
#endif
if (chNext == '\n' || chNext == '\r') {
++newlines;
(void)readChar(istr,bom); // Skip the "<backslash><newline>"
} else
code << "\\";
} else {
code << char(ch);
// if there has been <backslash><newline> sequences, add extra newlines..
if (ch == '\n' && newlines > 0) {
code << std::string(newlines, '\n');
newlines = 0;
}
}
}
std::string result = code.str();
code.str("");
// ------------------------------------------------------------------------------------------
//
// Remove all comments..
result = removeComments(result, filename);
// ------------------------------------------------------------------------------------------
//
// Clean up all preprocessor statements
result = preprocessCleanupDirectives(result);
// ------------------------------------------------------------------------------------------
//
// Clean up preprocessor #if statements with Parentheses
result = removeParentheses(result);
// Remove '#if 0' blocks
if (result.find("#if 0\n") != std::string::npos)
result = removeIf0(result);
return result;
}
std::string Preprocessor::preprocessCleanupDirectives(const std::string &processedFile)
{
std::ostringstream code;
std::istringstream sstr(processedFile);
std::string line;
while (std::getline(sstr, line)) {
// Trim lines..
if (!line.empty() && line[0] == ' ')
line.erase(0, line.find_first_not_of(" "));
if (!line.empty() && line[line.size()-1] == ' ')
line.erase(line.find_last_not_of(" ") + 1);
// Preprocessor
if (!line.empty() && line[0] == '#') {
enum {
ESC_NONE,
ESC_SINGLE,
ESC_DOUBLE
} escapeStatus = ESC_NONE;
char prev = ' '; // hack to make it skip spaces between # and the directive
code << "#";
std::string::const_iterator i = line.begin();
++i;
// need space.. #if( => #if (
bool needSpace = true;
while (i != line.end()) {
// disable esc-mode
if (escapeStatus != ESC_NONE) {
if (prev != '\\' && escapeStatus == ESC_SINGLE && *i == '\'') {
escapeStatus = ESC_NONE;
}
if (prev != '\\' && escapeStatus == ESC_DOUBLE && *i == '"') {
escapeStatus = ESC_NONE;
}
} else {
// enable esc-mode
if (escapeStatus == ESC_NONE && *i == '"')
escapeStatus = ESC_DOUBLE;
if (escapeStatus == ESC_NONE && *i == '\'')
escapeStatus = ESC_SINGLE;
}
// skip double whitespace between arguments
if (escapeStatus == ESC_NONE && prev == ' ' && *i == ' ') {
++i;
continue;
}
// Convert #if( to "#if ("
if (escapeStatus == ESC_NONE) {
if (needSpace) {
if (*i == '(' || *i == '!')
code << " ";
else if (!std::isalpha(*i))
needSpace = false;
}
if (*i == '#')
needSpace = true;
}
code << *i;
if (escapeStatus != ESC_NONE && prev == '\\' && *i == '\\') {
prev = ' ';
} else {
prev = *i;
}
++i;
}
if (escapeStatus != ESC_NONE) {
// unmatched quotes.. compiler should probably complain about this..
}
} else {
// Do not mess with regular code..
code << line;
}
code << (sstr.eof()?"":"\n");
}
return code.str();
}
static bool hasbom(const std::string &str)
{
return bool(str.size() >= 3 &&
static_cast<unsigned char>(str[0]) == 0xef &&
static_cast<unsigned char>(str[1]) == 0xbb &&
static_cast<unsigned char>(str[2]) == 0xbf);
}
// This wrapper exists because Sun's CC does not allow a static_cast
// from extern "C" int(*)(int) to int(*)(int).
static int tolowerWrapper(int c)
{
return std::tolower(c);
}
static bool isFallThroughComment(std::string comment)
{
// convert comment to lower case without whitespace
for (std::string::iterator i = comment.begin(); i != comment.end();) {
if (std::isspace(static_cast<unsigned char>(*i)))
i = comment.erase(i);
else
++i;
}
std::transform(comment.begin(), comment.end(), comment.begin(), tolowerWrapper);
return comment.find("fallthr") != std::string::npos ||
comment.find("fallsthr") != std::string::npos ||
comment.find("fall-thr") != std::string::npos ||
comment.find("dropthr") != std::string::npos ||
comment.find("passthr") != std::string::npos ||
comment.find("nobreak") != std::string::npos ||
comment == "fall";
}
std::string Preprocessor::removeComments(const std::string &str, const std::string &filename)
{
// For the error report
unsigned int lineno = 1;
// handling <backslash><newline>
// when this is encountered the <backslash><newline> will be "skipped".
// on the next <newline>, extra newlines will be added
unsigned int newlines = 0;
std::ostringstream code;
unsigned char previous = 0;
bool inPreprocessorLine = false;
std::vector<std::string> suppressionIDs;
bool fallThroughComment = false;
for (std::string::size_type i = hasbom(str) ? 3U : 0U; i < str.length(); ++i) {
unsigned char ch = static_cast<unsigned char>(str[i]);
if (ch & 0x80) {
std::ostringstream errmsg;
errmsg << "The code contains characters that are unhandled. "
<< "Neither unicode nor extended ASCII are supported. "
<< "(line=" << lineno << ", character code=" << std::hex << (int(ch) & 0xff) << ")";
writeError(filename, lineno, _errorLogger, "syntaxError", errmsg.str());
}
if ((str.compare(i, 6, "#error") == 0 && (!_settings || _settings->userDefines.empty())) ||
str.compare(i, 8, "#warning") == 0) {
if (str.compare(i, 6, "#error") == 0)
code << "#error";
i = str.find("\n", i);
if (i == std::string::npos)
break;
--i;
continue;
}
// First skip over any whitespace that may be present
if (std::isspace(ch)) {
if (ch == ' ' && previous == ' ') {
// Skip double white space
} else {
code << char(ch);
previous = ch;
}
// if there has been <backslash><newline> sequences, add extra newlines..
if (ch == '\n') {
if (previous != '\\')
inPreprocessorLine = false;
++lineno;
if (newlines > 0) {
code << std::string(newlines, '\n');
newlines = 0;
previous = '\n';
}
}
continue;
}
// Remove comments..
if (str.compare(i, 2, "//", 0, 2) == 0) {
std::size_t commentStart = i + 2;
i = str.find('\n', i);
if (i == std::string::npos)
break;
std::string comment(str, commentStart, i - commentStart);
if (_settings && _settings->_inlineSuppressions) {
std::istringstream iss(comment);
std::string word;
iss >> word;
if (word == "cppcheck-suppress") {
iss >> word;
if (iss)
suppressionIDs.push_back(word);
}
}
if (isFallThroughComment(comment)) {
fallThroughComment = true;
}
code << "\n";
previous = '\n';
++lineno;
} else if (str.compare(i, 2, "/*", 0, 2) == 0) {
std::size_t commentStart = i + 2;
unsigned char chPrev = 0;
++i;
while (i < str.length() && (chPrev != '*' || ch != '/')) {
chPrev = ch;
++i;
ch = static_cast<unsigned char>(str[i]);
if (ch == '\n') {
++newlines;
++lineno;
}
}
std::string comment(str, commentStart, i - commentStart - 1);
if (isFallThroughComment(comment)) {
fallThroughComment = true;
}
if (_settings && _settings->_inlineSuppressions) {
std::istringstream iss(comment);
std::string word;
iss >> word;
if (word == "cppcheck-suppress") {
iss >> word;
if (iss)
suppressionIDs.push_back(word);
}
}
} else if (ch == '#' && previous == '\n') {
code << ch;
previous = ch;
inPreprocessorLine = true;
// Add any pending inline suppressions that have accumulated.
if (!suppressionIDs.empty()) {
if (_settings != NULL) {
// Add the suppressions.
for (std::size_t j = 0; j < suppressionIDs.size(); ++j) {
const std::string errmsg(_settings->nomsg.addSuppression(suppressionIDs[j], filename, lineno));
if (!errmsg.empty()) {
writeError(filename, lineno, _errorLogger, "cppcheckError", errmsg);
}
}
}
suppressionIDs.clear();
}
} else {
if (!inPreprocessorLine) {
// Not whitespace, not a comment, and not preprocessor.
// Must be code here!
// First check for a "fall through" comment match, but only
// add a suppression if the next token is 'case' or 'default'
if (_settings && _settings->isEnabled("style") && _settings->experimental && fallThroughComment) {
std::string::size_type j = str.find_first_not_of("abcdefghijklmnopqrstuvwxyz", i);
std::string tok = str.substr(i, j - i);
if (tok == "case" || tok == "default")
suppressionIDs.push_back("switchCaseFallThrough");
fallThroughComment = false;
}
// Add any pending inline suppressions that have accumulated.
if (!suppressionIDs.empty()) {
if (_settings != NULL) {
// Add the suppressions.
for (std::size_t j = 0; j < suppressionIDs.size(); ++j) {
const std::string errmsg(_settings->nomsg.addSuppression(suppressionIDs[j], filename, lineno));
if (!errmsg.empty()) {
writeError(filename, lineno, _errorLogger, "cppcheckError", errmsg);
}
}
}
suppressionIDs.clear();
}
}
// String or char constants..
if (ch == '\"' || ch == '\'') {
code << char(ch);
char chNext;
do {
++i;
chNext = str[i];
if (chNext == '\\') {
++i;
char chSeq = str[i];
if (chSeq == '\n')
++newlines;
else {
code << chNext;
code << chSeq;
previous = static_cast<unsigned char>(chSeq);
}
} else {
code << chNext;
previous = static_cast<unsigned char>(chNext);
}
} while (i < str.length() && chNext != ch && chNext != '\n');
}
// Rawstring..
else if (str.compare(i,2,"R\"")==0) {
std::string delim;
for (std::string::size_type i2 = i+2; i2 < str.length(); ++i2) {
if (i2 > 16 ||
std::isspace(str[i2]) ||
std::iscntrl(str[i2]) ||
str[i2] == ')' ||
str[i2] == '\\') {
delim = " ";
break;
} else if (str[i2] == '(')
break;
delim += str[i2];
}
const std::string::size_type endpos = str.find(")" + delim + "\"", i);
if (delim != " " && endpos != std::string::npos) {
unsigned int rawstringnewlines = 0;
code << '\"';
for (std::string::size_type p = i + 3 + delim.size(); p < endpos; ++p) {
if (str[p] == '\n') {
rawstringnewlines++;
code << "\\n";
} else if (std::iscntrl((unsigned char)str[p]) ||
std::isspace((unsigned char)str[p])) {
code << " ";
} else if (str[p] == '\\') {
code << "\\";
} else if (str[p] == '\"' || str[p] == '\'') {
code << "\\" << (char)str[p];
} else {
code << (char)str[p];
}
}
code << "\"";
if (rawstringnewlines > 0)
code << std::string(rawstringnewlines, '\n');
i = endpos + delim.size() + 2;
} else {
code << "R";
previous = 'R';
}
} else {
code << char(ch);
previous = ch;
}
}
}
return code.str();
}
std::string Preprocessor::removeIf0(const std::string &code)
{
std::ostringstream ret;
std::istringstream istr(code);
std::string line;
while (std::getline(istr,line)) {
ret << line << "\n";
if (line == "#if 0") {
// goto the end of the '#if 0' block
unsigned int level = 1;
bool in = false;
while (level > 0 && std::getline(istr,line)) {
if (line.compare(0,3,"#if") == 0)
++level;
else if (line == "#endif")
--level;
else if ((line == "#else") || (line.compare(0, 5, "#elif") == 0)) {
if (level == 1)
in = true;
} else {
if (in)
ret << line << "\n";
else
// replace code within '#if 0' block with empty lines
ret << "\n";
continue;
}
ret << line << "\n";
}
}
}
return ret.str();
}
std::string Preprocessor::removeParentheses(const std::string &str)
{
if (str.find("\n#if") == std::string::npos && str.compare(0, 3, "#if") != 0)
return str;
std::istringstream istr(str);
std::ostringstream ret;
std::string line;
while (std::getline(istr, line)) {
if (line.compare(0, 3, "#if") == 0 || line.compare(0, 5, "#elif") == 0) {
std::string::size_type pos;
pos = 0;
while ((pos = line.find(" (", pos)) != std::string::npos)
line.erase(pos, 1);
pos = 0;
while ((pos = line.find("( ", pos)) != std::string::npos)
line.erase(pos + 1, 1);
pos = 0;
while ((pos = line.find(" )", pos)) != std::string::npos)
line.erase(pos, 1);
pos = 0;
while ((pos = line.find(") ", pos)) != std::string::npos)
line.erase(pos + 1, 1);
// Remove inner parenthesis "((..))"..
pos = 0;
while ((pos = line.find("((", pos)) != std::string::npos) {
++pos;
std::string::size_type pos2 = line.find_first_of("()", pos + 1);
if (pos2 != std::string::npos && line[pos2] == ')') {
line.erase(pos2, 1);
line.erase(pos, 1);
}
}
// "#if(A) => #if A", but avoid "#if (defined A) || defined (B)"
if ((line.compare(0, 4, "#if(") == 0 || line.compare(0, 6, "#elif(") == 0) &&
line[line.length() - 1] == ')') {
int ind = 0;
for (std::string::size_type i = 0; i < line.length(); ++i) {
if (line[i] == '(')
++ind;
else if (line[i] == ')') {
--ind;
if (ind == 0) {
if (i == line.length() - 1) {
line[line.find('(')] = ' ';
line.erase(line.length() - 1);
}
break;
}
}
}
}
if (line.compare(0, 4, "#if(") == 0)
line.insert(3, " ");
else if (line.compare(0, 6, "#elif(") == 0)
line.insert(5, " ");
}
ret << line << "\n";
}
return ret.str();
}
void Preprocessor::removeAsm(std::string &str)
{
std::string::size_type pos = 0;
while ((pos = str.find("#asm\n", pos)) != std::string::npos) {
str.replace(pos, 4, "asm(");
std::string::size_type pos2 = str.find("#endasm", pos);
if (pos2 != std::string::npos) {
str.replace(pos2, 7, ");");
pos = pos2;
}
}
}
void Preprocessor::preprocess(std::istream &istr, std::map<std::string, std::string> &result, const std::string &filename, const std::list<std::string> &includePaths)
{
std::list<std::string> configs;
std::string data;
preprocess(istr, data, configs, filename, includePaths);
for (std::list<std::string>::const_iterator it = configs.begin(); it != configs.end(); ++it) {
if (_settings && (_settings->userUndefs.find(*it) == _settings->userUndefs.end()))
result[ *it ] = getcode(data, *it, filename);
}
}
std::string Preprocessor::removeSpaceNearNL(const std::string &str)
{
std::string tmp;
char prev = 0;
for (unsigned int i = 0; i < str.size(); i++) {
if (str[i] == ' ' &&
((i > 0 && prev == '\n') ||
(i + 1 < str.size() && str[i+1] == '\n')
)
) {
// Ignore space that has new line in either side of it
} else {
tmp.append(1, str[i]);
prev = str[i];
}
}
return tmp;
}
std::string Preprocessor::replaceIfDefined(const std::string &str)
{
std::string ret(str);
std::string::size_type pos;
pos = 0;
while ((pos = ret.find("#if defined(", pos)) != std::string::npos) {
std::string::size_type pos2 = ret.find(")", pos + 9);
if (pos2 > ret.length() - 1)
break;
if (ret[pos2+1] == '\n') {
ret.erase(pos2, 1);
ret.erase(pos + 3, 9);
ret.insert(pos + 3, "def ");
}
++pos;
}
pos = 0;
while ((pos = ret.find("#if !defined(", pos)) != std::string::npos) {
std::string::size_type pos2 = ret.find(")", pos + 9);
if (pos2 > ret.length() - 1)
break;
if (ret[pos2+1] == '\n') {
ret.erase(pos2, 1);
ret.erase(pos + 3, 10);
ret.insert(pos + 3, "ndef ");
}
++pos;
}
pos = 0;
while ((pos = ret.find("#elif defined(", pos)) != std::string::npos) {
std::string::size_type pos2 = ret.find(")", pos + 9);
if (pos2 > ret.length() - 1)
break;
if (ret[pos2+1] == '\n') {
ret.erase(pos2, 1);
ret.erase(pos + 6, 8);
}
++pos;
}
return ret;
}
void Preprocessor::preprocessWhitespaces(std::string &processedFile)
{
// Replace all tabs with spaces..
std::replace(processedFile.begin(), processedFile.end(), '\t', ' ');
// Remove all indentation..
if (!processedFile.empty() && processedFile[0] == ' ')
processedFile.erase(0, processedFile.find_first_not_of(" "));
// Remove space characters that are after or before new line character
processedFile = removeSpaceNearNL(processedFile);
}
void Preprocessor::preprocess(std::istream &srcCodeStream, std::string &processedFile, std::list<std::string> &resultConfigurations, const std::string &filename, const std::list<std::string> &includePaths)
{
if (file0.empty())
file0 = filename;
processedFile = read(srcCodeStream, filename);
// Remove asm(...)
removeAsm(processedFile);
// Replace "defined A" with "defined(A)"
{
std::istringstream istr(processedFile);
std::ostringstream ostr;
std::string line;
while (std::getline(istr, line)) {
if (line.compare(0, 4, "#if ") == 0 || line.compare(0, 6, "#elif ") == 0) {
std::string::size_type pos = 0;
while ((pos = line.find(" defined ")) != std::string::npos) {
line[pos+8] = '(';
pos = line.find_first_of(" |&", pos + 8);
if (pos == std::string::npos)
line += ")";
else
line.insert(pos, ")");
}
}
ostr << line << "\n";
}
processedFile = ostr.str();
}
if (_settings && !_settings->userDefines.empty()) {
std::map<std::string, std::string> defs;
// TODO: break out this code. There is other similar code.
std::string::size_type pos1 = 0;
while (pos1 != std::string::npos) {
const std::string::size_type pos2 = _settings->userDefines.find_first_of(";=", pos1);
const std::string::size_type pos3 = _settings->userDefines.find(";", pos1);
std::string name, value;
if (pos2 == std::string::npos)
name = _settings->userDefines.substr(pos1);
else
name = _settings->userDefines.substr(pos1, pos2 - pos1);
if (pos2 != pos3) {
if (pos3 == std::string::npos)
value = _settings->userDefines.substr(pos2+1);
else
value = _settings->userDefines.substr(pos2+1, pos3 - pos2 - 1);
}
defs[name] = value;
pos1 = pos3;
if (pos1 != std::string::npos)
pos1++;
}
processedFile = handleIncludes(processedFile, filename, includePaths, defs);
if (_settings->userDefines.empty())
resultConfigurations = getcfgs(processedFile, filename);
} else {
handleIncludes(processedFile, filename, includePaths);
processedFile = replaceIfDefined(processedFile);
// Get all possible configurations..
resultConfigurations = getcfgs(processedFile, filename);
// Remove configurations that are disabled by -U
handleUndef(resultConfigurations);
}
}
void Preprocessor::handleUndef(std::list<std::string> &configurations) const
{
if (_settings && !_settings->userUndefs.empty()) {
for (std::list<std::string>::iterator cfg = configurations.begin(); cfg != configurations.end();) {
bool undef = false;
for (std::set<std::string>::const_iterator it = _settings->userUndefs.begin(); it != _settings->userUndefs.end(); ++it) {
if (*it == *cfg)
undef = true;
else if (cfg->compare(0,it->length(),*it)==0 && cfg->find_first_of(";=") == it->length())
undef = true;
else if (cfg->find(";" + *it) == std::string::npos)
;
else if (cfg->find(";" + *it + ";") != std::string::npos)
undef = true;
else if (cfg->find(";" + *it + "=") != std::string::npos)
undef = true;
else if (cfg->find(";" + *it) + it->size() + 1U == cfg->size())
undef = true;
}
if (undef)
configurations.erase(cfg++);
else
++cfg;
}
}
}
// Get the DEF in this line: "#ifdef DEF"
std::string Preprocessor::getdef(std::string line, bool def)
{
if (line.empty() || line[0] != '#')
return "";
// If def is true, the line must start with "#ifdef"
if (def && line.compare(0, 7, "#ifdef ") != 0 && line.compare(0, 4, "#if ") != 0
&& (line.compare(0, 6, "#elif ") != 0 || line.compare(0, 7, "#elif !") == 0)) {
return "";
}
// If def is false, the line must start with "#ifndef"
if (!def && line.compare(0, 8, "#ifndef ") != 0 && line.compare(0, 7, "#elif !") != 0) {
return "";
}
// Remove the "#ifdef" or "#ifndef"
if (line.compare(0, 12, "#if defined ") == 0)
line.erase(0, 11);
else if (line.compare(0, 15, "#elif !defined(") == 0) {
line.erase(0, 15);
std::string::size_type pos = line.find(")");
// if pos == ::npos then another part of the code will complain
// about the mismatch
if (pos != std::string::npos)
line.erase(pos, 1);
} else
line.erase(0, line.find(" "));
// Remove all spaces.
std::string::size_type pos = 0;
while ((pos = line.find(" ", pos)) != std::string::npos) {
const unsigned char chprev(static_cast<unsigned char>((pos > 0) ? line[pos-1] : 0));
const unsigned char chnext(static_cast<unsigned char>((pos + 1 < line.length()) ? line[pos+1] : 0));
if ((std::isalnum(chprev) || chprev == '_') && (std::isalnum(chnext) || chnext == '_'))
++pos;
else
line.erase(pos, 1);
}
// The remaining string is our result.
return line;
}
/**
* Simplifies the variable map. For example if the map contains A=>B, B=>1, then A=>B is simplified to A=>1.
* @param [in,out] variables - a map of variable name to variable value. This map will be modified.
*/
static void simplifyVarMap(std::map<std::string, std::string> &variables)
{
for (std::map<std::string, std::string>::iterator i = variables.begin(); i != variables.end(); ++i) {
std::string& varValue = i->second;
// TODO: 1. tokenize the value, replace each token like this.
// TODO: 2. handle function-macros too.
std::set<std::string> seenVariables;
std::map<std::string, std::string>::iterator it = variables.find(varValue);
while (it != variables.end() && it->first != it->second) {
if (seenVariables.find(it->first) != seenVariables.end()) {
// We have already seen this variable. there is a cycle of #define that we can't process at
// this time. Stop trying to simplify the current variable and leave it as is.
break;
} else {
seenVariables.insert(it->first);
varValue = it->second;
it = variables.find(varValue);
}
}
}
}
std::list<std::string> Preprocessor::getcfgs(const std::string &filedata, const std::string &filename)
{
std::list<std::string> ret;
ret.push_back("");
std::list<std::string> deflist, ndeflist;
// constants defined through "#define" in the code..
std::set<std::string> defines;
// How deep into included files are we currently parsing?
// 0=>Source file, 1=>Included by source file, 2=>included by header that was included by source file, etc
int filelevel = 0;
bool includeguard = false;
unsigned int linenr = 0;
std::istringstream istr(filedata);
std::string line;
while (std::getline(istr, line)) {
++linenr;
if (_errorLogger)
_errorLogger->reportProgress(filename, "Preprocessing (get configurations 1)", 0);
if (line.empty())
continue;
if (line.compare(0, 6, "#file ") == 0) {
includeguard = true;
++filelevel;
continue;
}
else if (line == "#endfile") {
includeguard = false;
if (filelevel > 0)
--filelevel;
continue;
}