/
preprocessor.cpp
1234 lines (1048 loc) · 36.1 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-2009 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 "filelister.h"
#include <algorithm>
#include <stdexcept>
#include <sstream>
#include <fstream>
#include <iostream>
#include <cstdlib>
#include <cctype>
#include <cstring>
#include <vector>
void Preprocessor::writeError(const std::string &fileName, const std::string &code, size_t endPos, ErrorLogger *errorLogger, const std::string &errorType, const std::string &errorText)
{
if (!errorLogger)
{
return;
}
// line number in parsed code
unsigned int lineno = 1;
// The current token being parsed
std::string CurrentToken;
// lineNumbers holds line numbers for files in fileIndexes
// every time an include file is complitely parsed, last item in the vector
// is removed and lineno is set to point to that value.
std::vector<unsigned int> lineNumbers;
// fileIndexes holds index for _files vector about currently parsed files
// every time an include file is complitely parsed, last item in the vector
// is removed and FileIndex is set to point to that value.
std::vector<std::string> fileIndexes;
// FileIndex. What file in the _files vector is read now?
std::string FileIndex = fileName;
// Read one byte at a time from code and create tokens
if (endPos > code.length())
endPos = code.length();
for (size_t codePos = 0; codePos < endPos; ++codePos)
{
char ch = code[codePos];
// UTF / extended ASCII => The output from the preprocessor should only be standard ASCII
if (ch < 0)
{
// TODO: Remove characters that are redundant
// TODO: Convert characters that are needed to standard ASCII
// Not sure how to handle this character. Bailing out.
if (ch < 0)
continue;
}
// char/string..
if (ch == '\'' || ch == '\"')
{
std::string line;
// read char
bool special = false;
char c = ch;
do
{
// Append token..
line += c;
if (c == '\n')
++lineno;
// Special sequence '\.'
if (special)
special = false;
else
special = (c == '\\');
// Get next character
++codePos;
c = code[codePos];
}
while (codePos < endPos && (special || c != ch));
line += ch;
// Handle #file "file.h"
if (CurrentToken == "#file")
{
// Extract the filename
line = line.substr(1, line.length() - 2);
// Has this file been tokenized already?
++lineno;
fileIndexes.push_back(FileIndex);
FileIndex = FileLister::simplifyPath(line.c_str());
lineNumbers.push_back(lineno);
lineno = 0;
}
CurrentToken.clear();
continue;
}
if (strchr("+-*/%&|^?!=<>[](){};:,.~\n ", ch))
{
if (ch == '.' &&
CurrentToken.length() > 0 &&
std::isdigit(CurrentToken[0]))
{
// Don't separate doubles "5.4"
}
else if (strchr("+-", ch) &&
CurrentToken.length() > 0 &&
std::isdigit(CurrentToken[0]) &&
CurrentToken[CurrentToken.length()-1] == 'e')
{
// Don't separate doubles "4.2e+10"
}
else
{
if (CurrentToken == "#file")
{
// Handle this where strings are handled
continue;
}
else if (CurrentToken == "#endfile")
{
if (lineNumbers.empty() || fileIndexes.empty())
{
std::cerr << "####### Preprocessor bug! #######\n";
std::exit(0);
}
lineno = lineNumbers.back();
lineNumbers.pop_back();
FileIndex = fileIndexes.back();
fileIndexes.pop_back();
CurrentToken.clear();
continue;
}
// If token contains # characters, split it up
std::string temp;
for (std::string::size_type i = 0; i < CurrentToken.length(); ++i)
{
if (CurrentToken[i] == '#' && CurrentToken.length() + 1 > i && CurrentToken[i+1] == '#')
{
temp.clear();
++i;
}
else
temp += CurrentToken[i];
}
CurrentToken.clear();
if (ch == '\n')
{
++lineno;
continue;
}
else if (ch == ' ')
{
continue;
}
CurrentToken += ch;
// Add "++", "--" or ">>" token
if ((ch == '+' || ch == '-' || ch == '>') && (code[codePos+1] == ch))
{
++codePos;
CurrentToken += code[codePos];
}
CurrentToken.clear();
continue;
}
}
CurrentToken += ch;
}
std::list<ErrorLogger::ErrorMessage::FileLocation> locationList;
ErrorLogger::ErrorMessage::FileLocation loc;
loc.line = lineno;
loc.file = FileIndex;
locationList.push_back(loc);
errorLogger->reportErr(
ErrorLogger::ErrorMessage(locationList,
"error",
errorText,
errorType));
}
Preprocessor::Preprocessor()
{
}
static char readChar(std::istream &istr)
{
char ch = (char)istr.get();
// Handling of newlines..
if (ch == '\r')
{
ch = '\n';
if ((char)istr.peek() == '\n')
(void)istr.get();
}
return ch;
}
/** Just read the code into a string. Perform simple cleanup of the code */
std::string Preprocessor::read(std::istream &istr)
{
// Get filedata from stream..
bool ignoreSpace = true;
// need space.. #if( => #if (
bool needSpace = false;
// For the error report
int lineno = 1;
// handling <backspace><newline>
// when this is encountered the <backspace><newline> will be "skipped".
// on the next <newline>, extra newlines will be added
unsigned int newlines = 0;
std::ostringstream code;
for (char ch = readChar(istr); istr.good(); ch = readChar(istr))
{
if (ch == '\n')
++lineno;
// Replace assorted special chars with spaces..
if ((ch != '\n') && (std::isspace(ch) || std::iscntrl(ch)))
ch = ' ';
// Skip spaces after ' ' and after '#'
if (ch == ' ' && ignoreSpace)
continue;
ignoreSpace = bool(ch == ' ' || ch == '#' || ch == '\n');
if (needSpace)
{
if (ch == '(')
code << " ";
else if (! std::isalpha(ch))
needSpace = false;
}
if (ch == '#')
needSpace = true;
// <backspace><newline>..
if (ch == '\\')
{
char chNext = 0;
while (true)
{
chNext = (char)istr.peek();
if (chNext != '\n' && chNext != '\r' &&
(std::isspace(chNext) || std::iscntrl(chNext)))
{
// Skip whitespace between <backspace> and <newline>
(void)readChar(istr);
continue;
}
break;
}
if (chNext == '\n' || chNext == '\r')
{
++newlines;
(void)readChar(istr); // Skip the "<backspace><newline>"
}
else
code << "\\";
}
// Just some code..
else
{
code << std::string(1, ch);
// if there has been <backspace><newline> sequences, add extra newlines..
if (ch == '\n' && newlines > 0)
{
code << std::string(newlines, '\n');
newlines = 0;
}
}
}
return removeComments(code.str());
}
std::string Preprocessor::removeComments(const std::string &str)
{
// For the error report
int lineno = 1;
// handling <backspace><newline>
// when this is encountered the <backspace><newline> will be "skipped".
// on the next <newline>, extra newlines will be added
unsigned int newlines = 0;
std::ostringstream code;
char previous = 0;
for (std::string::size_type i = 0; i < str.length(); ++i)
{
char ch = str[i];
if (ch < 0)
throw std::runtime_error("The code contains characters that are unhandled");
// Remove comments..
if (str.compare(i, 2, "//", 0, 2) == 0)
{
i = str.find('\n', i);
if (i == std::string::npos)
break;
code << "\n";
previous = '\n';
++lineno;
}
else if (str.compare(i, 2, "/*", 0, 2) == 0)
{
char chPrev = 0;
++i;
while (i < str.length() && (chPrev != '*' || ch != '/'))
{
chPrev = ch;
++i;
ch = str[i];
if (ch == '\n')
{
code << "\n";
previous = '\n';
++lineno;
}
}
}
// String or char constants..
else if (ch == '\"' || ch == '\'')
{
code << std::string(1, ch);
char chNext;
do
{
++i;
chNext = str[i];
if (chNext == '\\')
{
++i;
char chSeq = str[i];
if (chSeq == '\n')
++newlines;
else
{
code << std::string(1, chNext);
code << std::string(1, chSeq);
previous = chSeq;
}
}
else
{
code << std::string(1, chNext);
previous = chNext;
}
}
while (i < str.length() && chNext != ch);
}
// Just some code..
else
{
if (ch == ' ' && previous == ' ')
{
// Skip double white space
}
else
{
code << std::string(1, ch);
previous = ch;
}
// if there has been <backspace><newline> sequences, add extra newlines..
if (ch == '\n' && newlines > 0)
{
code << std::string(newlines, '\n');
newlines = 0;
previous = '\n';
}
}
}
return code.str();
}
void Preprocessor::preprocess(std::istream &istr, std::map<std::string, std::string> &result, const std::string &filename, const std::list<std::string> &includePaths, ErrorLogger *errorLogger)
{
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)
result[ *it ] = Preprocessor::getcode(data, *it, filename, errorLogger);
}
std::string Preprocessor::removeSpaceNearNL(const std::string &str)
{
std::string tmp;
int prev = -1;
for (unsigned int i = 0; i < str.size(); i++)
{
if (str[i] == ' ' &&
((i > 0 && tmp[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;
}
}
return tmp;
}
std::string Preprocessor::replaceIfDefined(const std::string &str)
{
std::string ret(str);
std::string::size_type 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;
}
return ret;
}
void Preprocessor::preprocess(std::istream &istr, std::string &processedFile, std::list<std::string> &resultConfigurations, const std::string &filename, const std::list<std::string> &includePaths)
{
processedFile = read(istr);
// 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);
handleIncludes(processedFile, filename, includePaths);
processedFile = replaceIfDefined(processedFile);
// Get all possible configurations..
resultConfigurations = getcfgs(processedFile);
}
// Get the DEF in this line: "#ifdef DEF"
std::string Preprocessor::getdef(std::string line, bool def)
{
// If def is true, the line must start with "#ifdef"
if (def && line.find("#ifdef ") != 0 && line.find("#if ") != 0 && line.find("#elif ") != 0)
{
return "";
}
// If def is false, the line must start with "#ifndef"
if (!def && line.find("#ifndef ") != 0)
{
return "";
}
// Remove the "#ifdef" or "#ifndef"
line.erase(0, line.find(" "));
// Remove all spaces.
while (line.find(" ") != std::string::npos)
line.erase(line.find(" "), 1);
// The remaining string is our result.
return line;
}
std::list<std::string> Preprocessor::getcfgs(const std::string &filedata)
{
std::list<std::string> ret;
ret.push_back("");
std::list<std::string> deflist;
// 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;
std::istringstream istr(filedata);
std::string line;
while (getline(istr, line))
{
if (line.substr(0, 6) == "#file ")
{
++filelevel;
continue;
}
else if (line == "#endfile")
{
if (filelevel > 0)
--filelevel;
continue;
}
if (filelevel > 0)
continue;
std::string def = getdef(line, true) + getdef(line, false);
if (!def.empty())
{
if (! deflist.empty() && line.find("#elif ") == 0)
deflist.pop_back();
deflist.push_back(def);
def = "";
for (std::list<std::string>::const_iterator it = deflist.begin(); it != deflist.end(); ++it)
{
if (*it == "0")
break;
if (*it == "1")
continue;
if (! def.empty())
def += ";";
def += *it;
}
if (std::find(ret.begin(), ret.end(), def) == ret.end())
ret.push_back(def);
}
if (line.find("#else") == 0 && ! deflist.empty())
{
std::string def((deflist.back() == "1") ? "0" : "1");
deflist.pop_back();
deflist.push_back(def);
}
if (line.find("#endif") == 0 && ! deflist.empty())
deflist.pop_back();
}
return ret;
}
bool Preprocessor::match_cfg_def(std::string cfg, const std::string &def)
{
if (def == "0")
return false;
if (def == "1")
return true;
if (cfg.empty())
return false;
while (! cfg.empty())
{
if (cfg.find(";") == std::string::npos)
return bool(cfg == def);
std::string _cfg = cfg.substr(0, cfg.find(";"));
if (_cfg == def)
return true;
cfg.erase(0, cfg.find(";") + 1);
}
return false;
}
std::string Preprocessor::getcode(const std::string &filedata, std::string cfg, const std::string &filename, ErrorLogger *errorLogger)
{
std::ostringstream ret;
bool match = true;
std::list<bool> matching_ifdef;
std::list<bool> matched_ifdef;
std::istringstream istr(filedata);
std::string line;
while (getline(istr, line))
{
std::string def = getdef(line, true);
std::string ndef = getdef(line, false);
if (line.find("#elif ") == 0)
{
if (matched_ifdef.back())
{
matching_ifdef.back() = false;
}
else
{
if (match_cfg_def(cfg, def))
{
matching_ifdef.back() = true;
matched_ifdef.back() = true;
}
}
}
else if (! def.empty())
{
matching_ifdef.push_back(match_cfg_def(cfg, def));
matched_ifdef.push_back(matching_ifdef.back());
}
else if (! ndef.empty())
{
matching_ifdef.push_back(! match_cfg_def(cfg, ndef));
matched_ifdef.push_back(matching_ifdef.back());
}
else if (line == "#else")
{
if (! matched_ifdef.empty())
matching_ifdef.back() = ! matched_ifdef.back();
}
else if (line.compare(0, 6, "#endif") == 0)
{
if (! matched_ifdef.empty())
matched_ifdef.pop_back();
if (! matching_ifdef.empty())
matching_ifdef.pop_back();
}
if (!line.empty() && line[0] == '#')
{
match = true;
for (std::list<bool>::const_iterator it = matching_ifdef.begin(); it != matching_ifdef.end(); ++it)
match &= bool(*it);
}
if (!match && line.find("#define") == 0)
{
// Remove define that is not part of this configuration
line = "";
}
else if (line.find("#file \"") == 0 ||
line.find("#endfile") == 0 ||
line.find("#define") == 0)
{
// We must not remove #file tags or line numbers
// are corrupted. File tags are removed by the tokenizer.
}
else if (!match ||
line[0] == '#')
{
// Remove #if, #else, #pragma etc, leaving only
// #define, #file and #endfile. and also lines
// which are not part of this configuration.
line = "";
}
ret << line << "\n";
}
return expandMacros(ret.str(), filename, errorLogger);
}
int Preprocessor::getHeaderFileName(std::string &str)
{
std::string result;
std::string::size_type i = str.find_first_of("<\"");
if (i == std::string::npos)
{
str = "";
return 0;
}
char c = str[i];
if (c == '<')
c = '>';
for (i = i + 1; i < str.length(); ++i)
{
if (str[i] == c)
break;
result.append(1, str[i]);
}
str = result;
if (c == '"')
return 1;
else
return 2;
}
void Preprocessor::handleIncludes(std::string &code, const std::string &filename, const std::list<std::string> &includePaths)
{
std::list<std::string> paths;
std::string path;
path = filename;
path.erase(1 + path.find_last_of("\\/"));
paths.push_back(path);
std::string::size_type pos = 0;
std::string::size_type endfilePos = 0;
std::map<std::string, bool> handledFiles;
endfilePos = pos;
while ((pos = code.find("#include", pos)) != std::string::npos)
{
// Accept only includes that are at the start of a line
if (pos > 0 && code[pos-1] != '\n')
{
pos += 8; // length of "#include"
continue;
}
// If endfile is encountered, we have moved to a next file in our stack,
// so remove last path in our list.
while ((endfilePos = code.find("#endfile", endfilePos)) != std::string::npos && endfilePos < pos)
{
paths.pop_back();
endfilePos += 8; // size of #endfile
}
endfilePos = pos;
std::string::size_type end = code.find("\n", pos);
std::string filename = code.substr(pos, end - pos);
// Remove #include clause
code.erase(pos, end - pos);
int headerType = getHeaderFileName(filename);
if (headerType == 0)
continue;
std::string tempFile = filename;
std::transform(tempFile.begin(), tempFile.end(), tempFile.begin(), static_cast < int(*)(int) > (std::tolower));
if (handledFiles.find(tempFile) != handledFiles.end())
{
// We have processed this file already once, skip
// it this time to avoid ethernal loop.
continue;
}
handledFiles[ tempFile ] = true;
// filename contains now a file name e.g. "menu.h"
std::string processedFile;
for (std::list<std::string>::const_iterator iter = includePaths.begin(); iter != includePaths.end(); ++iter)
{
std::ifstream fin;
fin.open((*iter + filename).c_str());
if (fin.is_open())
{
filename = *iter + filename;
processedFile = Preprocessor::read(fin);
break;
}
}
if (headerType == 1 && processedFile.length() == 0)
{
filename = paths.back() + filename;
std::ifstream fin(filename.c_str());
if (fin.is_open())
processedFile = Preprocessor::read(fin);
}
if (processedFile.length() > 0)
{
// 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);
processedFile = "#file \"" + filename + "\"\n" + processedFile + "\n#endfile";
code.insert(pos, processedFile);
path = filename;
path.erase(1 + path.find_last_of("\\/"));
paths.push_back(path);
}
}
}
class Macro
{
private:
Tokenizer tokenizer;
std::vector<std::string> _params;
std::string _name;
std::string _macro;
bool _variadic;
public:
Macro(const std::string ¯o)
: _macro(macro)
{
// Tokenize the macro to make it easier to handle
std::istringstream istr(macro.c_str());
tokenizer.createTokens(istr);
// macro name..
if (tokens() && tokens()->isName())
_name = tokens()->str();
_variadic = false;
std::string::size_type pos = macro.find_first_of(" (");
if (pos != std::string::npos && macro[pos] == '(')
{
// Extract macro parameters
if (Token::Match(tokens(), "%var% ( %var%"))
{
for (const Token *tok = tokens()->tokAt(2); tok; tok = tok->next())
{
if (tok->str() == ")")
break;
if (Token::simpleMatch(tok, ". . . )"))
{
_variadic = true;
break;
}
if (tok->isName())
_params.push_back(tok->str());
}
}
}
}
const Token *tokens() const
{
return tokenizer.tokens();
}
const std::vector<std::string> params() const
{
return _params;
}
bool variadic() const
{
return _variadic;
}
const std::string &name() const
{
return _name;
}
bool code(const std::vector<std::string> ¶ms2, std::string ¯ocode) const
{
if (_params.empty())
{
std::string::size_type pos = _macro.find(" ");
if (pos == std::string::npos)
macrocode = "";
else
{
macrocode = _macro.substr(pos + 1);
if ((pos = macrocode.find_first_of("\r\n")) != std::string::npos)
macrocode.erase(pos);
}
}
else
{
const Token *tok = tokens();
while (tok && tok->str() != ")")
tok = tok->next();
if (tok)
{
bool optcomma = false;
while ((tok = tok->next()) != NULL)
{
std::string str = tok->str();
if (str == "##")
continue;
if (str[0] == '#' || tok->isName())
{
bool stringify = false;
if (str[0] == '#')
{
str = str.erase(0, 1);
stringify = true;
}
for (unsigned int i = 0; i < _params.size(); ++i)
{
if (str == _params[i])
{
if (_variadic && i == _params.size() - 1)
{
str = "";
for (unsigned int j = _params.size() - 1; j < params2.size(); ++j)
{
if (optcomma || j > _params.size() - 1)
str += ",";
optcomma = false;
str += params2[j];
}
}
else if (i >= params2.size())
{
// Macro had more parameters than caller used.
macrocode = "";
return false;
}
else if (stringify)
str = "\"" + params2[i] + "\"";
else
str = params2[i];
break;
}
}
}
if (_variadic && Token::simpleMatch(tok, ",") && tok->next() && Token::simpleMatch(tok->next(), "##"))
{
optcomma = true;
continue;
}
optcomma = false;
macrocode += str;
if (Token::Match(tok, "%type% %var%"))
macrocode += " ";
}
}
}
return true;
}
};
std::string Preprocessor::expandMacros(std::string code, const std::string &filename, ErrorLogger *errorLogger)
{
// Search for macros and expand them..
std::string::size_type defpos = 0;