forked from danmar/simplecpp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
simplecpp.cpp
executable file
·3289 lines (2909 loc) · 123 KB
/
simplecpp.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
/*
* simplecpp - A simple and high-fidelity C/C++ preprocessor library
* Copyright (C) 2016-2022 Daniel Marjamäki.
*
* This library is free software: you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation, either
* version 3 of the License, or (at your option) any later version.
*
* This library 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library. If not, see <http://www.gnu.org/licenses/>.
*/
#if defined(_WIN32) || defined(__CYGWIN__) || defined(__MINGW32__)
#define SIMPLECPP_WINDOWS
#define NOMINMAX
#endif
#include "simplecpp.h"
#include <algorithm>
#include <climits>
#include <cstring>
#include <exception>
#include <fstream>
#include <iostream>
#include <limits>
#include <sstream>
#include <stack>
#include <stdexcept>
#if __cplusplus >= 201103L
#include <unordered_map>
#endif
#include <utility>
#ifdef SIMPLECPP_WINDOWS
#include <windows.h>
#undef ERROR
#undef TRUE
#endif
#if (__cplusplus < 201103L) && !defined(__APPLE__)
#define nullptr NULL
#endif
static bool isHex(const std::string &s)
{
return s.size()>2 && (s.compare(0,2,"0x")==0 || s.compare(0,2,"0X")==0);
}
static bool isOct(const std::string &s)
{
return s.size()>1 && (s[0]=='0') && (s[1] >= '0') && (s[1] < '8');
}
static const simplecpp::TokenString DEFINE("define");
static const simplecpp::TokenString UNDEF("undef");
static const simplecpp::TokenString INCLUDE("include");
static const simplecpp::TokenString ERROR("error");
static const simplecpp::TokenString WARNING("warning");
static const simplecpp::TokenString IF("if");
static const simplecpp::TokenString IFDEF("ifdef");
static const simplecpp::TokenString IFNDEF("ifndef");
static const simplecpp::TokenString DEFINED("defined");
static const simplecpp::TokenString ELSE("else");
static const simplecpp::TokenString ELIF("elif");
static const simplecpp::TokenString ENDIF("endif");
static const simplecpp::TokenString PRAGMA("pragma");
static const simplecpp::TokenString ONCE("once");
static const simplecpp::TokenString HAS_INCLUDE("__has_include");
template<class T> static std::string toString(T t)
{
std::ostringstream ostr;
ostr << t;
return ostr.str();
}
static long long stringToLL(const std::string &s)
{
long long ret;
const bool hex = isHex(s);
const bool oct = isOct(s);
std::istringstream istr(hex ? s.substr(2) : oct ? s.substr(1) : s);
if (hex)
istr >> std::hex;
else if (oct)
istr >> std::oct;
istr >> ret;
return ret;
}
static unsigned long long stringToULL(const std::string &s)
{
unsigned long long ret;
const bool hex = isHex(s);
const bool oct = isOct(s);
std::istringstream istr(hex ? s.substr(2) : oct ? s.substr(1) : s);
if (hex)
istr >> std::hex;
else if (oct)
istr >> std::oct;
istr >> ret;
return ret;
}
static bool startsWith(const std::string &str, const std::string &s)
{
return (str.size() >= s.size() && str.compare(0, s.size(), s) == 0);
}
static bool endsWith(const std::string &s, const std::string &e)
{
return (s.size() >= e.size() && s.compare(s.size() - e.size(), e.size(), e) == 0);
}
static bool sameline(const simplecpp::Token *tok1, const simplecpp::Token *tok2)
{
return tok1 && tok2 && tok1->location.sameline(tok2->location);
}
static bool isAlternativeBinaryOp(const simplecpp::Token *tok, const std::string &alt)
{
return (tok->name &&
tok->str() == alt &&
tok->previous &&
tok->next &&
(tok->previous->number || tok->previous->name || tok->previous->op == ')') &&
(tok->next->number || tok->next->name || tok->next->op == '('));
}
static bool isAlternativeUnaryOp(const simplecpp::Token *tok, const std::string &alt)
{
return ((tok->name && tok->str() == alt) &&
(!tok->previous || tok->previous->op == '(') &&
(tok->next && (tok->next->name || tok->next->number)));
}
static std::string replaceAll(std::string s, const std::string& from, const std::string& to)
{
for (size_t pos = s.find(from); pos != std::string::npos; pos = s.find(from, pos + to.size()))
s.replace(pos, from.size(), to);
return s;
}
const std::string simplecpp::Location::emptyFileName;
void simplecpp::Location::adjust(const std::string &str)
{
if (strpbrk(str.c_str(), "\r\n") == nullptr) {
col += str.size();
return;
}
for (std::size_t i = 0U; i < str.size(); ++i) {
col++;
if (str[i] == '\n' || str[i] == '\r') {
col = 1;
line++;
if (str[i] == '\r' && (i+1)<str.size() && str[i+1]=='\n')
++i;
}
}
}
bool simplecpp::Token::isOneOf(const char ops[]) const
{
return (op != '\0') && (std::strchr(ops, op) != nullptr);
}
bool simplecpp::Token::startsWithOneOf(const char c[]) const
{
return std::strchr(c, string[0]) != nullptr;
}
bool simplecpp::Token::endsWithOneOf(const char c[]) const
{
return std::strchr(c, string[string.size() - 1U]) != nullptr;
}
void simplecpp::Token::printAll() const
{
const Token *tok = this;
while (tok->previous)
tok = tok->previous;
for (; tok; tok = tok->next) {
if (tok->previous) {
std::cout << (sameline(tok, tok->previous) ? ' ' : '\n');
}
std::cout << tok->str();
}
std::cout << std::endl;
}
void simplecpp::Token::printOut() const
{
for (const Token *tok = this; tok; tok = tok->next) {
if (tok != this) {
std::cout << (sameline(tok, tok->previous) ? ' ' : '\n');
}
std::cout << tok->str();
}
std::cout << std::endl;
}
simplecpp::TokenList::TokenList(std::vector<std::string> &filenames) : frontToken(nullptr), backToken(nullptr), files(filenames) {}
simplecpp::TokenList::TokenList(std::istream &istr, std::vector<std::string> &filenames, const std::string &filename, OutputList *outputList)
: frontToken(nullptr), backToken(nullptr), files(filenames)
{
readfile(istr,filename,outputList);
}
simplecpp::TokenList::TokenList(const TokenList &other) : frontToken(nullptr), backToken(nullptr), files(other.files)
{
*this = other;
}
#if __cplusplus >= 201103L
simplecpp::TokenList::TokenList(TokenList &&other) : TokenList(other)
{
*this = std::move(other);
}
#endif
simplecpp::TokenList::~TokenList()
{
clear();
}
simplecpp::TokenList &simplecpp::TokenList::operator=(const TokenList &other)
{
if (this != &other) {
clear();
files = other.files;
for (const Token *tok = other.cfront(); tok; tok = tok->next)
push_back(new Token(*tok));
sizeOfType = other.sizeOfType;
}
return *this;
}
#if __cplusplus >= 201103L
simplecpp::TokenList &simplecpp::TokenList::operator=(TokenList &&other)
{
if (this != &other) {
clear();
frontToken = other.frontToken;
other.frontToken = nullptr;
backToken = other.backToken;
other.backToken = nullptr;
files = other.files;
sizeOfType = std::move(other.sizeOfType);
}
return *this;
}
#endif
void simplecpp::TokenList::clear()
{
backToken = nullptr;
while (frontToken) {
Token *next = frontToken->next;
delete frontToken;
frontToken = next;
}
sizeOfType.clear();
}
void simplecpp::TokenList::push_back(Token *tok)
{
if (!frontToken)
frontToken = tok;
else
backToken->next = tok;
tok->previous = backToken;
backToken = tok;
}
void simplecpp::TokenList::dump() const
{
std::cout << stringify() << std::endl;
}
std::string simplecpp::TokenList::stringify() const
{
std::ostringstream ret;
Location loc(files);
for (const Token *tok = cfront(); tok; tok = tok->next) {
if (tok->location.line < loc.line || tok->location.fileIndex != loc.fileIndex) {
ret << "\n#line " << tok->location.line << " \"" << tok->location.file() << "\"\n";
loc = tok->location;
}
while (tok->location.line > loc.line) {
ret << '\n';
loc.line++;
}
if (sameline(tok->previous, tok))
ret << ' ';
ret << tok->str();
loc.adjust(tok->str());
}
return ret.str();
}
static unsigned char readChar(std::istream &istr, unsigned int bom)
{
unsigned char ch = static_cast<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) {
const unsigned char ch2 = static_cast<unsigned char>(istr.get());
const int ch16 = (bom == 0xfeff) ? (ch<<8 | ch2) : (ch2<<8 | ch);
ch = static_cast<unsigned char>(((ch16 >= 0x80) ? 0xff : ch16));
}
// Handling of newlines..
if (ch == '\r') {
ch = '\n';
if (bom == 0 && static_cast<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;
}
static unsigned char peekChar(std::istream &istr, unsigned int bom)
{
unsigned char ch = static_cast<unsigned char>(istr.peek());
// 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) {
(void)istr.get();
const unsigned char ch2 = static_cast<unsigned char>(istr.peek());
istr.unget();
const int ch16 = (bom == 0xfeff) ? (ch<<8 | ch2) : (ch2<<8 | ch);
ch = static_cast<unsigned char>(((ch16 >= 0x80) ? 0xff : ch16));
}
// Handling of newlines..
if (ch == '\r')
ch = '\n';
return ch;
}
static void ungetChar(std::istream &istr, unsigned int bom)
{
istr.unget();
if (bom == 0xfeff || bom == 0xfffe)
istr.unget();
}
static unsigned short getAndSkipBOM(std::istream &istr)
{
const int ch1 = istr.peek();
// The UTF-16 BOM is 0xfffe or 0xfeff.
if (ch1 >= 0xfe) {
unsigned short bom = (static_cast<unsigned char>(istr.get()) << 8);
if (istr.peek() >= 0xfe)
return bom | static_cast<unsigned char>(istr.get());
istr.unget();
return 0;
}
// Skip UTF-8 BOM 0xefbbbf
if (ch1 == 0xef) {
(void)istr.get();
if (istr.get() == 0xbb && istr.peek() == 0xbf) {
(void)istr.get();
} else {
istr.unget();
istr.unget();
}
}
return 0;
}
static bool isNameChar(unsigned char ch)
{
return std::isalnum(ch) || ch == '_' || ch == '$';
}
static std::string escapeString(const std::string &str)
{
std::ostringstream ostr;
ostr << '\"';
for (std::size_t i = 1U; i < str.size() - 1; ++i) {
char c = str[i];
if (c == '\\' || c == '\"' || c == '\'')
ostr << '\\';
ostr << c;
}
ostr << '\"';
return ostr.str();
}
static void portabilityBackslash(simplecpp::OutputList *outputList, const std::vector<std::string> &files, const simplecpp::Location &location)
{
if (!outputList)
return;
simplecpp::Output err(files);
err.type = simplecpp::Output::PORTABILITY_BACKSLASH;
err.location = location;
err.msg = "Combination 'backslash space newline' is not portable.";
outputList->push_back(err);
}
static bool isStringLiteralPrefix(const std::string &str)
{
return str == "u" || str == "U" || str == "L" || str == "u8" ||
str == "R" || str == "uR" || str == "UR" || str == "LR" || str == "u8R";
}
void simplecpp::TokenList::lineDirective(unsigned int fileIndex, unsigned int line, Location *location)
{
if (fileIndex != location->fileIndex || line >= location->line) {
location->fileIndex = fileIndex;
location->line = line;
return;
}
if (line + 2 >= location->line) {
location->line = line;
while (cback()->op != '#')
deleteToken(back());
deleteToken(back());
return;
}
}
static const std::string COMMENT_END("*/");
void simplecpp::TokenList::readfile(std::istream &istr, const std::string &filename, OutputList *outputList)
{
std::stack<simplecpp::Location> loc;
unsigned int multiline = 0U;
const Token *oldLastToken = nullptr;
const unsigned short bom = getAndSkipBOM(istr);
Location location(files);
location.fileIndex = fileIndex(filename);
location.line = 1U;
location.col = 1U;
while (istr.good()) {
unsigned char ch = readChar(istr,bom);
if (!istr.good())
break;
if (ch < ' ' && ch != '\t' && ch != '\n' && ch != '\r')
ch = ' ';
if (ch >= 0x80) {
if (outputList) {
simplecpp::Output err(files);
err.type = simplecpp::Output::UNHANDLED_CHAR_ERROR;
err.location = location;
std::ostringstream s;
s << static_cast<int>(ch);
err.msg = "The code contains unhandled character(s) (character code=" + s.str() + "). Neither unicode nor extended ascii is supported.";
outputList->push_back(err);
}
clear();
return;
}
if (ch == '\n') {
if (cback() && cback()->op == '\\') {
if (location.col > cback()->location.col + 1U)
portabilityBackslash(outputList, files, cback()->location);
++multiline;
deleteToken(back());
} else {
location.line += multiline + 1;
multiline = 0U;
}
if (!multiline)
location.col = 1;
if (oldLastToken != cback()) {
oldLastToken = cback();
const std::string lastline(lastLine());
if (lastline == "# file %str%") {
const Token *strtok = cback();
while (strtok->comment)
strtok = strtok->previous;
loc.push(location);
location.fileIndex = fileIndex(strtok->str().substr(1U, strtok->str().size() - 2U));
location.line = 1U;
} else if (lastline == "# line %num%") {
const Token *numtok = cback();
while (numtok->comment)
numtok = numtok->previous;
lineDirective(location.fileIndex, std::atol(numtok->str().c_str()), &location);
} else if (lastline == "# %num% %str%" || lastline == "# line %num% %str%") {
const Token *strtok = cback();
while (strtok->comment)
strtok = strtok->previous;
const Token *numtok = strtok->previous;
while (numtok->comment)
numtok = numtok->previous;
lineDirective(fileIndex(replaceAll(strtok->str().substr(1U, strtok->str().size() - 2U),"\\\\","\\")),
std::atol(numtok->str().c_str()), &location);
}
// #endfile
else if (lastline == "# endfile" && !loc.empty()) {
location = loc.top();
loc.pop();
}
}
continue;
}
if (std::isspace(ch)) {
location.col++;
continue;
}
TokenString currentToken;
if (cback() && cback()->location.line == location.line && cback()->previous && cback()->previous->op == '#' && (lastLine() == "# error" || lastLine() == "# warning")) {
char prev = ' ';
while (istr.good() && (prev == '\\' || (ch != '\r' && ch != '\n'))) {
currentToken += ch;
prev = ch;
ch = readChar(istr, bom);
}
ungetChar(istr, bom);
push_back(new Token(currentToken, location));
location.adjust(currentToken);
continue;
}
// number or name
if (isNameChar(ch)) {
const bool num = std::isdigit(ch);
while (istr.good() && isNameChar(ch)) {
currentToken += ch;
ch = readChar(istr,bom);
if (num && ch=='\'' && isNameChar(peekChar(istr,bom)))
ch = readChar(istr,bom);
}
ungetChar(istr,bom);
}
// comment
else if (ch == '/' && peekChar(istr,bom) == '/') {
while (istr.good() && ch != '\r' && ch != '\n') {
currentToken += ch;
ch = readChar(istr, bom);
}
const std::string::size_type pos = currentToken.find_last_not_of(" \t");
if (pos < currentToken.size() - 1U && currentToken[pos] == '\\')
portabilityBackslash(outputList, files, location);
if (currentToken[currentToken.size() - 1U] == '\\') {
++multiline;
currentToken.erase(currentToken.size() - 1U);
} else {
ungetChar(istr, bom);
}
}
// comment
else if (ch == '/' && peekChar(istr,bom) == '*') {
currentToken = "/*";
(void)readChar(istr,bom);
ch = readChar(istr,bom);
while (istr.good()) {
currentToken += ch;
if (currentToken.size() >= 4U && endsWith(currentToken, COMMENT_END))
break;
ch = readChar(istr,bom);
}
// multiline..
std::string::size_type pos = 0;
while ((pos = currentToken.find("\\\n",pos)) != std::string::npos) {
currentToken.erase(pos,2);
++multiline;
}
if (multiline || startsWith(lastLine(10),"# ")) {
pos = 0;
while ((pos = currentToken.find('\n',pos)) != std::string::npos) {
currentToken.erase(pos,1);
++multiline;
}
}
}
// string / char literal
else if (ch == '\"' || ch == '\'') {
std::string prefix;
if (cback() && cback()->name && isStringLiteralPrefix(cback()->str()) &&
((cback()->location.col + cback()->str().size()) == location.col) &&
(cback()->location.line == location.line)) {
prefix = cback()->str();
}
// C++11 raw string literal
if (ch == '\"' && !prefix.empty() && *cback()->str().rbegin() == 'R') {
std::string delim;
currentToken = ch;
prefix.resize(prefix.size() - 1);
ch = readChar(istr,bom);
while (istr.good() && ch != '(' && ch != '\n') {
delim += ch;
ch = readChar(istr,bom);
}
if (!istr.good() || ch == '\n') {
if (outputList) {
Output err(files);
err.type = Output::SYNTAX_ERROR;
err.location = location;
err.msg = "Invalid newline in raw string delimiter.";
outputList->push_back(err);
}
return;
}
const std::string endOfRawString(')' + delim + currentToken);
while (istr.good() && !(endsWith(currentToken, endOfRawString) && currentToken.size() > 1))
currentToken += readChar(istr,bom);
if (!endsWith(currentToken, endOfRawString)) {
if (outputList) {
Output err(files);
err.type = Output::SYNTAX_ERROR;
err.location = location;
err.msg = "Raw string missing terminating delimiter.";
outputList->push_back(err);
}
return;
}
currentToken.erase(currentToken.size() - endOfRawString.size(), endOfRawString.size() - 1U);
currentToken = escapeString(currentToken);
currentToken.insert(0, prefix);
back()->setstr(currentToken);
location.adjust(currentToken);
if (currentToken.find_first_of("\r\n") == std::string::npos)
location.col += 2 + 2 * delim.size();
else
location.col += 1 + delim.size();
continue;
}
currentToken = readUntil(istr,location,ch,ch,outputList,bom);
if (currentToken.size() < 2U)
// Error is reported by readUntil()
return;
std::string s = currentToken;
std::string::size_type pos;
int newlines = 0;
while ((pos = s.find_first_of("\r\n")) != std::string::npos) {
s.erase(pos,1);
newlines++;
}
if (prefix.empty())
push_back(new Token(s, location)); // push string without newlines
else
back()->setstr(prefix + s);
if (newlines > 0 && lastLine().compare(0,9,"# define ") == 0) {
multiline += newlines;
location.adjust(s);
} else {
location.adjust(currentToken);
}
continue;
}
else {
currentToken += ch;
}
if (currentToken == "<" && lastLine() == "# include") {
currentToken = readUntil(istr, location, '<', '>', outputList, bom);
if (currentToken.size() < 2U)
return;
}
push_back(new Token(currentToken, location));
if (multiline)
location.col += currentToken.size();
else
location.adjust(currentToken);
}
combineOperators();
}
void simplecpp::TokenList::constFold()
{
while (cfront()) {
// goto last '('
Token *tok = back();
while (tok && tok->op != '(')
tok = tok->previous;
// no '(', goto first token
if (!tok)
tok = front();
// Constant fold expression
constFoldUnaryNotPosNeg(tok);
constFoldMulDivRem(tok);
constFoldAddSub(tok);
constFoldShift(tok);
constFoldComparison(tok);
constFoldBitwise(tok);
constFoldLogicalOp(tok);
constFoldQuestionOp(&tok);
// If there is no '(' we are done with the constant folding
if (tok->op != '(')
break;
if (!tok->next || !tok->next->next || tok->next->next->op != ')')
break;
tok = tok->next;
deleteToken(tok->previous);
deleteToken(tok->next);
}
}
static bool isFloatSuffix(const simplecpp::Token *tok)
{
if (!tok || tok->str().size() != 1U)
return false;
const char c = std::tolower(tok->str()[0]);
return c == 'f' || c == 'l';
}
void simplecpp::TokenList::combineOperators()
{
std::stack<bool> executableScope;
executableScope.push(false);
for (Token *tok = front(); tok; tok = tok->next) {
if (tok->op == '{') {
if (executableScope.top()) {
executableScope.push(true);
continue;
}
const Token *prev = tok->previous;
while (prev && prev->isOneOf(";{}()"))
prev = prev->previous;
executableScope.push(prev && prev->op == ')');
continue;
}
if (tok->op == '}') {
if (executableScope.size() > 1)
executableScope.pop();
continue;
}
if (tok->op == '.') {
// ellipsis ...
if (tok->next && tok->next->op == '.' && tok->next->location.col == (tok->location.col + 1) &&
tok->next->next && tok->next->next->op == '.' && tok->next->next->location.col == (tok->location.col + 2)) {
tok->setstr("...");
deleteToken(tok->next);
deleteToken(tok->next);
continue;
}
// float literals..
if (tok->previous && tok->previous->number) {
tok->setstr(tok->previous->str() + '.');
deleteToken(tok->previous);
if (isFloatSuffix(tok->next) || (tok->next && tok->next->startsWithOneOf("AaBbCcDdEeFfPp"))) {
tok->setstr(tok->str() + tok->next->str());
deleteToken(tok->next);
}
}
if (tok->next && tok->next->number) {
tok->setstr(tok->str() + tok->next->str());
deleteToken(tok->next);
}
}
// match: [0-9.]+E [+-] [0-9]+
const char lastChar = tok->str()[tok->str().size() - 1];
if (tok->number && !isOct(tok->str()) &&
((!isHex(tok->str()) && (lastChar == 'E' || lastChar == 'e')) ||
(isHex(tok->str()) && (lastChar == 'P' || lastChar == 'p'))) &&
tok->next && tok->next->isOneOf("+-") && tok->next->next && tok->next->next->number) {
tok->setstr(tok->str() + tok->next->op + tok->next->next->str());
deleteToken(tok->next);
deleteToken(tok->next);
}
if (tok->op == '\0' || !tok->next || tok->next->op == '\0')
continue;
if (!sameline(tok,tok->next))
continue;
if (tok->location.col + 1U != tok->next->location.col)
continue;
if (tok->next->op == '=' && tok->isOneOf("=!<>+-*/%&|^")) {
if (tok->op == '&' && !executableScope.top()) {
// don't combine &= if it is a anonymous reference parameter with default value:
// void f(x&=2)
int indentlevel = 0;
const Token *start = tok;
while (indentlevel >= 0 && start) {
if (start->op == ')')
++indentlevel;
else if (start->op == '(')
--indentlevel;
else if (start->isOneOf(";{}"))
break;
start = start->previous;
}
if (indentlevel == -1 && start) {
const Token *ftok = start;
bool isFuncDecl = ftok->name;
while (isFuncDecl) {
if (!start->name && start->str() != "::" && start->op != '*' && start->op != '&')
isFuncDecl = false;
if (!start->previous)
break;
if (start->previous->isOneOf(";{}:"))
break;
start = start->previous;
}
isFuncDecl &= start != ftok && start->name;
if (isFuncDecl) {
// TODO: we could loop through the parameters here and check if they are correct.
continue;
}
}
}
tok->setstr(tok->str() + "=");
deleteToken(tok->next);
} else if ((tok->op == '|' || tok->op == '&') && tok->op == tok->next->op) {
tok->setstr(tok->str() + tok->next->str());
deleteToken(tok->next);
} else if (tok->op == ':' && tok->next->op == ':') {
tok->setstr(tok->str() + tok->next->str());
deleteToken(tok->next);
} else if (tok->op == '-' && tok->next->op == '>') {
tok->setstr(tok->str() + tok->next->str());
deleteToken(tok->next);
} else if ((tok->op == '<' || tok->op == '>') && tok->op == tok->next->op) {
tok->setstr(tok->str() + tok->next->str());
deleteToken(tok->next);
if (tok->next && tok->next->op == '=' && tok->next->next && tok->next->next->op != '=') {
tok->setstr(tok->str() + tok->next->str());
deleteToken(tok->next);
}
} else if ((tok->op == '+' || tok->op == '-') && tok->op == tok->next->op) {
if (tok->location.col + 1U != tok->next->location.col)
continue;
if (tok->previous && tok->previous->number)
continue;
if (tok->next->next && tok->next->next->number)
continue;
tok->setstr(tok->str() + tok->next->str());
deleteToken(tok->next);
}
}
}
static const std::string COMPL("compl");
static const std::string NOT("not");
void simplecpp::TokenList::constFoldUnaryNotPosNeg(simplecpp::Token *tok)
{
for (; tok && tok->op != ')'; tok = tok->next) {
// "not" might be !
if (isAlternativeUnaryOp(tok, NOT))
tok->op = '!';
// "compl" might be ~
else if (isAlternativeUnaryOp(tok, COMPL))
tok->op = '~';
if (tok->op == '!' && tok->next && tok->next->number) {
tok->setstr(tok->next->str() == "0" ? "1" : "0");
deleteToken(tok->next);
} else if (tok->op == '~' && tok->next && tok->next->number) {
tok->setstr(toString(~stringToLL(tok->next->str())));
deleteToken(tok->next);
} else {
if (tok->previous && (tok->previous->number || tok->previous->name))
continue;
if (!tok->next || !tok->next->number)
continue;
switch (tok->op) {
case '+':
tok->setstr(tok->next->str());
deleteToken(tok->next);
break;
case '-':
tok->setstr(tok->op + tok->next->str());
deleteToken(tok->next);
break;
}
}
}
}
void simplecpp::TokenList::constFoldMulDivRem(Token *tok)
{
for (; tok && tok->op != ')'; tok = tok->next) {
if (!tok->previous || !tok->previous->number)
continue;
if (!tok->next || !tok->next->number)
continue;
long long result;
if (tok->op == '*')
result = (stringToLL(tok->previous->str()) * stringToLL(tok->next->str()));
else if (tok->op == '/' || tok->op == '%') {
long long rhs = stringToLL(tok->next->str());
if (rhs == 0)
throw std::overflow_error("division/modulo by zero");
long long lhs = stringToLL(tok->previous->str());
if (rhs == -1 && lhs == std::numeric_limits<long long>::min())
throw std::overflow_error("division overflow");
if (tok->op == '/')
result = (lhs / rhs);
else
result = (lhs % rhs);
} else
continue;
tok = tok->previous;
tok->setstr(toString(result));
deleteToken(tok->next);
deleteToken(tok->next);
}
}
void simplecpp::TokenList::constFoldAddSub(Token *tok)
{
for (; tok && tok->op != ')'; tok = tok->next) {
if (!tok->previous || !tok->previous->number)
continue;
if (!tok->next || !tok->next->number)
continue;
long long result;
if (tok->op == '+')
result = stringToLL(tok->previous->str()) + stringToLL(tok->next->str());
else if (tok->op == '-')
result = stringToLL(tok->previous->str()) - stringToLL(tok->next->str());
else
continue;
tok = tok->previous;
tok->setstr(toString(result));
deleteToken(tok->next);
deleteToken(tok->next);
}
}
void simplecpp::TokenList::constFoldShift(Token *tok)
{
for (; tok && tok->op != ')'; tok = tok->next) {
if (!tok->previous || !tok->previous->number)
continue;
if (!tok->next || !tok->next->number)
continue;
long long result;
if (tok->str() == "<<")
result = stringToLL(tok->previous->str()) << stringToLL(tok->next->str());
else if (tok->str() == ">>")
result = stringToLL(tok->previous->str()) >> stringToLL(tok->next->str());
else