/
tokenlist.cpp
1170 lines (1039 loc) · 39.3 KB
/
tokenlist.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-2016 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 "tokenlist.h"
#include "token.h"
#include "mathlib.h"
#include "path.h"
#include "preprocessor.h"
#include "settings.h"
#include "errorlogger.h"
#include <cstring>
#include <sstream>
#include <cctype>
#include <stack>
// How many compileExpression recursions are allowed?
// For practical code this could be endless. But in some special torture test
// there needs to be a limit.
static const unsigned int AST_MAX_DEPTH = 50U;
TokenList::TokenList(const Settings* settings) :
_front(0),
_back(0),
_settings(settings),
_isC(false),
_isCPP(false)
{
}
TokenList::~TokenList()
{
deallocateTokens();
}
//---------------------------------------------------------------------------
const std::string& TokenList::getSourceFilePath() const
{
if (getFiles().empty()) {
return emptyString;
}
return getFiles()[0];
}
//---------------------------------------------------------------------------
// Deallocate lists..
void TokenList::deallocateTokens()
{
deleteTokens(_front);
_front = 0;
_back = 0;
_files.clear();
}
unsigned int TokenList::appendFileIfNew(const std::string &fileName)
{
// Has this file been tokenized already?
for (std::size_t i = 0; i < _files.size(); ++i)
if (Path::sameFileName(_files[i], fileName))
return (unsigned int)i;
// The "_files" vector remembers what files have been tokenized..
_files.push_back(Path::simplifyPath(fileName));
// Update _isC and _isCPP properties
if (_files.size() == 1) { // Update only useful if first file added to _files
if (!_settings) {
_isC = Path::isC(getSourceFilePath());
_isCPP = Path::isCPP(getSourceFilePath());
} else {
_isC = _settings->enforcedLang == Settings::C || (_settings->enforcedLang == Settings::None && Path::isC(getSourceFilePath()));
_isCPP = _settings->enforcedLang == Settings::CPP || (_settings->enforcedLang == Settings::None && Path::isCPP(getSourceFilePath()));
}
}
return _files.size() - 1U;
}
void TokenList::deleteTokens(Token *tok)
{
while (tok) {
Token *next = tok->next();
delete tok;
tok = next;
}
}
//---------------------------------------------------------------------------
// add a token.
//---------------------------------------------------------------------------
void TokenList::addtoken(std::string str, const unsigned int lineno, const unsigned int fileno, bool split)
{
if (str.empty())
return;
// If token contains # characters, split it up
if (split) {
size_t begin = 0;
size_t end = 0;
while ((end = str.find("##", begin)) != std::string::npos) {
addtoken(str.substr(begin, end - begin), lineno, fileno, false);
addtoken("##", lineno, fileno, false);
begin = end+2;
}
if (begin != 0) {
addtoken(str.substr(begin), lineno, fileno, false);
return;
}
}
// Replace hexadecimal value with decimal
if (MathLib::isIntHex(str) || MathLib::isOct(str) || MathLib::isBin(str)) {
str = MathLib::value(str).str();
} else if (str.compare(0, 5, "_Bool") == 0) {
str = "bool";
}
if (_back) {
_back->insertToken(str);
} else {
_front = new Token(&_back);
_back = _front;
_back->str(str);
}
if (isCPP() && str == "delete")
_back->isKeyword(true);
_back->linenr(lineno);
_back->fileIndex(fileno);
}
void TokenList::addtoken(const Token * tok, const unsigned int lineno, const unsigned int fileno)
{
if (tok == nullptr)
return;
if (_back) {
_back->insertToken(tok->str(), tok->originalName());
} else {
_front = new Token(&_back);
_back = _front;
_back->str(tok->str());
if (!tok->originalName().empty())
_back->originalName(tok->originalName());
}
_back->linenr(lineno);
_back->fileIndex(fileno);
_back->flags(tok->flags());
}
//---------------------------------------------------------------------------
// InsertTokens - Copy and insert tokens
//---------------------------------------------------------------------------
void TokenList::insertTokens(Token *dest, const Token *src, unsigned int n)
{
std::stack<Token *> link;
while (n > 0) {
dest->insertToken(src->str(), src->originalName());
dest = dest->next();
// Set links
if (Token::Match(dest, "(|[|{"))
link.push(dest);
else if (!link.empty() && Token::Match(dest, ")|]|}")) {
Token::createMutualLinks(dest, link.top());
link.pop();
}
dest->fileIndex(src->fileIndex());
dest->linenr(src->linenr());
dest->varId(src->varId());
dest->tokType(src->tokType());
dest->flags(src->flags());
src = src->next();
--n;
}
}
//---------------------------------------------------------------------------
// Tokenize - tokenizes a given file.
//---------------------------------------------------------------------------
bool TokenList::createTokens(std::istream &code, const std::string& file0)
{
appendFileIfNew(file0);
// 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 completely parsed, last item in the vector
// is removed and lineno is set to point to that value.
std::stack<unsigned int> lineNumbers;
// fileIndexes holds index for _files vector about currently parsed files
// every time an include file is completely parsed, last item in the vector
// is removed and FileIndex is set to point to that value.
std::stack<unsigned int> fileIndexes;
// FileIndex. What file in the _files vector is read now?
unsigned int FileIndex = 0;
bool expandedMacro = false;
// Read one byte at a time from code and create tokens
for (char ch = (char)code.get(); code.good() && ch; ch = (char)code.get()) {
if (ch == Preprocessor::macroChar) {
while (code.peek() == Preprocessor::macroChar)
code.get();
if (!CurrentToken.empty()) {
addtoken(CurrentToken, lineno, FileIndex, true);
_back->isExpandedMacro(expandedMacro);
CurrentToken.clear();
}
expandedMacro = true;
continue;
}
// char/string..
// multiline strings are not handled. The preprocessor should handle that for us.
else if (ch == '\'' || ch == '\"') {
std::string line;
// read char
bool special = false;
char c = ch;
do {
// Append token..
line += c;
// Special sequence '\.'
if (special)
special = false;
else
special = (c == '\\');
// Get next character
c = (char)code.get();
} while (code.good() && (special || c != ch));
line += ch;
// Handle #file "file.h"
if (CurrentToken == "#file") {
// Extract the filename
line = line.substr(1, line.length() - 2);
++lineno;
fileIndexes.push(FileIndex);
FileIndex = appendFileIfNew(line);
lineNumbers.push(lineno);
lineno = 0;
} else {
// Add previous token
addtoken(CurrentToken, lineno, FileIndex);
if (!CurrentToken.empty())
_back->isExpandedMacro(expandedMacro);
// Add content of the string
addtoken(line, lineno, FileIndex);
if (!line.empty())
_back->isExpandedMacro(expandedMacro);
}
CurrentToken.clear();
continue;
}
if (ch == '.' &&
!CurrentToken.empty() &&
std::isdigit((unsigned char)CurrentToken[0])) {
// Don't separate doubles "5.4"
} else if (std::strchr("+-", ch) &&
CurrentToken.length() > 0 &&
std::isdigit((unsigned char)CurrentToken[0]) &&
(CurrentToken.back() == 'e' ||
CurrentToken.back() == 'E') &&
!MathLib::isIntHex(CurrentToken)) {
// Don't separate doubles "4.2e+10"
} else if (CurrentToken.empty() && ch == '.' && std::isdigit((unsigned char)code.peek())) {
// tokenize .125 into 0.125
CurrentToken = "0";
} else if (std::strchr("+-*/%&|^?!=<>[](){};:,.~\n ", ch)) {
if (CurrentToken == "#file") {
// Handle this where strings are handled
continue;
} else if (CurrentToken == "#line") {
// Read to end of line
std::string line;
std::getline(code, line);
unsigned int row=0;
std::istringstream fiss(line);
if (fiss >> row) {
// Update the current line number
lineno = row;
std::string line2;
if (std::getline(fiss, line2) && line2.length() > 4U) {
// _"file_name" -> file_name
line2 = line2.substr(2, line2.length() - 3);
// Update the current file
FileIndex = appendFileIfNew(line2);
}
} else
++lineno;
CurrentToken.clear();
continue;
} else if (CurrentToken == "#endfile") {
if (lineNumbers.empty() || fileIndexes.empty()) { // error
deallocateTokens();
return false;
}
lineno = lineNumbers.top();
lineNumbers.pop();
FileIndex = fileIndexes.top();
fileIndexes.pop();
CurrentToken.clear();
continue;
}
addtoken(CurrentToken, lineno, FileIndex, true);
if (!CurrentToken.empty()) {
_back->isExpandedMacro(expandedMacro);
expandedMacro = false;
CurrentToken.clear();
}
if (ch == '\n') {
if (_settings->terminated())
return false;
++lineno;
continue;
} else if (ch == ' ') {
continue;
}
CurrentToken += ch;
// Add "++", "--", ">>" or ... token
if (std::strchr("+-<>=:&|", ch) && (code.peek() == ch))
CurrentToken += (char)code.get();
addtoken(CurrentToken, lineno, FileIndex);
_back->isExpandedMacro(expandedMacro);
CurrentToken.clear();
expandedMacro = false;
continue;
}
CurrentToken += ch;
}
addtoken(CurrentToken, lineno, FileIndex, true);
if (!CurrentToken.empty())
_back->isExpandedMacro(expandedMacro);
// Split up ++ and --..
for (Token *tok = _front; tok; tok = tok->next()) {
if (!Token::Match(tok, "++|--"))
continue;
if (Token::Match(tok->previous(), "%num% ++|--") ||
Token::Match(tok, "++|-- %num%")) {
tok->str(tok->str()[0]);
tok->insertToken(tok->str());
}
}
Token::assignProgressValues(_front);
for (std::size_t i = 1; i < _files.size(); i++)
_files[i] = Path::getRelativePath(_files[i], _settings->basePaths);
return true;
}
//---------------------------------------------------------------------------
unsigned long long TokenList::calculateChecksum() const
{
unsigned long long checksum = 0;
for (const Token* tok = front(); tok; tok = tok->next()) {
const unsigned int subchecksum1 = tok->flags() + tok->varId() + tok->tokType();
unsigned int subchecksum2 = 0;
for (std::size_t i = 0; i < tok->str().size(); i++)
subchecksum2 += (unsigned int)tok->str()[i];
if (!tok->originalName().empty()) {
for (std::size_t i = 0; i < tok->originalName().size(); i++)
subchecksum2 += (unsigned int) tok->originalName()[i];
}
checksum ^= ((static_cast<unsigned long long>(subchecksum1) << 32) | subchecksum2);
const bool bit1 = (checksum & 1) != 0;
checksum >>= 1;
if (bit1)
checksum |= (1ULL << 63);
}
return checksum;
}
//---------------------------------------------------------------------------
struct AST_state {
std::stack<Token*> op;
unsigned int depth;
unsigned int inArrayAssignment;
bool cpp;
unsigned int assign;
explicit AST_state(bool cpp_) : depth(0), inArrayAssignment(0), cpp(cpp_), assign(0U) {}
};
static Token * skipDecl(Token *tok)
{
if (!Token::Match(tok->previous(), "( %name%"))
return tok;
Token *vartok = tok;
while (Token::Match(vartok, "%name%|*|&|::|<")) {
if (vartok->str() == "<") {
if (vartok->link())
vartok = vartok->link();
else
return tok;
} else if (Token::Match(vartok, "%name% [:=]")) {
return vartok;
}
vartok = vartok->next();
}
return tok;
}
static bool iscast(const Token *tok)
{
if (!Token::Match(tok, "( ::| %name%"))
return false;
if (tok->previous() && tok->previous()->isName() && tok->previous()->str() != "return")
return false;
if (Token::simpleMatch(tok->previous(), ">") && tok->previous()->link())
return false;
if (Token::Match(tok, "( (| typeof (") && Token::Match(tok->link(), ") %num%"))
return true;
bool type = false;
for (const Token *tok2 = tok->next(); tok2; tok2 = tok2->next()) {
while (tok2->link() && Token::Match(tok2, "(|[|<"))
tok2 = tok2->link()->next();
if (tok2->str() == ")")
return type || tok2->strAt(-1) == "*" || Token::Match(tok2, ") &|~") ||
(Token::Match(tok2, ") %any%") &&
!tok2->next()->isOp() &&
!Token::Match(tok2->next(), "[[]);,?:.]"));
if (!Token::Match(tok2, "%name%|*|&|::"))
return false;
if (tok2->isStandardType() && tok2->next()->str() != "(")
type = true;
}
return false;
}
// X{} X<Y>{} etc
static bool iscpp11init(const Token * const tok)
{
const Token *nameToken = nullptr;
if (tok->isName())
nameToken = tok;
else if (Token::Match(tok->previous(), "%name% {"))
nameToken = tok->previous();
else if (tok->linkAt(-1) && Token::simpleMatch(tok->previous(), "> {") && Token::Match(tok->linkAt(-1)->previous(),"%name% <"))
nameToken = tok->linkAt(-1)->previous();
if (!nameToken)
return false;
const Token *endtok = nullptr;
if (Token::Match(nameToken,"%name% {"))
endtok = nameToken->linkAt(1);
else if (Token::Match(nameToken,"%name% <") && Token::simpleMatch(nameToken->linkAt(1),"> {"))
endtok = nameToken->linkAt(1)->linkAt(1);
else
return false;
// There is no initialisation for example here: 'class Fred {};'
if (!Token::simpleMatch(endtok, "} ;"))
return true;
const Token *prev = nameToken;
while (Token::Match(prev, "%name%|::|:|<|>")) {
if (Token::Match(prev, "class|struct"))
return false;
prev = prev->previous();
}
return true;
}
static void compileUnaryOp(Token *&tok, AST_state& state, void(*f)(Token *&tok, AST_state& state))
{
Token *unaryop = tok;
if (f) {
tok = tok->next();
state.depth++;
if (tok && state.depth <= AST_MAX_DEPTH)
f(tok, state);
state.depth--;
}
if (!state.op.empty()) {
unaryop->astOperand1(state.op.top());
state.op.pop();
}
state.op.push(unaryop);
}
static void compileBinOp(Token *&tok, AST_state& state, void(*f)(Token *&tok, AST_state& state))
{
Token *binop = tok;
if (f) {
tok = tok->next();
state.depth++;
if (tok && state.depth <= AST_MAX_DEPTH)
f(tok, state);
state.depth--;
}
// TODO: Should we check if op is empty.
// * Is it better to add assertion that it isn't?
// * Write debug warning if it's empty?
if (!state.op.empty()) {
binop->astOperand2(state.op.top());
state.op.pop();
}
if (!state.op.empty()) {
binop->astOperand1(state.op.top());
state.op.pop();
}
state.op.push(binop);
}
static void compileExpression(Token *&tok, AST_state& state);
static void compileTerm(Token *&tok, AST_state& state)
{
if (!tok)
return;
if (Token::Match(tok, "L %str%|%char%"))
tok = tok->next();
if (state.inArrayAssignment && tok->str() == "." && Token::Match(tok->previous(), ",|{")) // Jump over . in C style struct initialization
tok = tok->next();
if (tok->isLiteral()) {
state.op.push(tok);
do {
tok = tok->next();
} while (Token::Match(tok, "%name%|%str%"));
} else if (tok->isName() && tok->str() != "case") {
if (tok->str() == "return") {
compileUnaryOp(tok, state, compileExpression);
state.op.pop();
} else if (Token::Match(tok, "sizeof !!(")) {
compileUnaryOp(tok, state, compileExpression);
state.op.pop();
} else if (state.cpp && iscpp11init(tok)) { // X{} X<Y>{} etc
state.op.push(tok);
tok = tok->next();
if (tok->str() == "<")
tok = tok->link()->next();
} else if (!state.cpp || !Token::Match(tok, "new|delete %name%|*|&|::|(|[")) {
tok = skipDecl(tok);
while (tok->next() && tok->next()->isName())
tok = tok->next();
state.op.push(tok);
if (Token::Match(tok, "%name% <") && tok->linkAt(1))
tok = tok->linkAt(1);
tok = tok->next();
if (Token::Match(tok, "%str%")) {
while (Token::Match(tok, "%name%|%str%"))
tok = tok->next();
}
}
} else if (tok->str() == "{") {
if (tok->previous() && tok->previous()->isName()) {
compileBinOp(tok, state, compileExpression);
} else if (!state.inArrayAssignment && tok->strAt(-1) != "=") {
state.op.push(tok);
tok = tok->link()->next();
} else {
if (tok->link() != tok->next()) {
state.inArrayAssignment++;
compileUnaryOp(tok, state, compileExpression);
while (Token::Match(tok, "} [,}]") && state.inArrayAssignment > 0U) {
tok = tok->next();
state.inArrayAssignment--;
}
} else {
state.op.push(tok);
}
}
}
}
static void compileScope(Token *&tok, AST_state& state)
{
compileTerm(tok, state);
while (tok) {
if (tok->str() == "::") {
Token *binop = tok;
tok = tok->next();
if (tok && tok->str() == "~") // Jump over ~ of destructor definition
tok = tok->next();
if (tok)
compileTerm(tok, state);
if (binop->previous() && (binop->previous()->isName() || (binop->previous()->link() && binop->strAt(-1) == ">")))
compileBinOp(binop, state, nullptr);
else
compileUnaryOp(binop, state, nullptr);
} else break;
}
}
static bool isPrefixUnary(const Token* tok, bool cpp)
{
if (!tok->previous()
|| ((Token::Match(tok->previous(), "(|[|{|%op%|;|}|?|:|,|.|return|::") || (cpp && tok->strAt(-1) == "throw"))
&& (tok->previous()->tokType() != Token::eIncDecOp || tok->tokType() == Token::eIncDecOp)))
return true;
return tok->strAt(-1) == ")" && iscast(tok->linkAt(-1));
}
static void compilePrecedence2(Token *&tok, AST_state& state)
{
compileScope(tok, state);
while (tok) {
if (tok->tokType() == Token::eIncDecOp && !isPrefixUnary(tok, state.cpp)) {
compileUnaryOp(tok, state, compileScope);
} else if (tok->str() == "." && tok->strAt(1) != "*") {
if (tok->strAt(1) == ".") {
state.op.push(tok);
tok = tok->tokAt(3);
break;
} else
compileBinOp(tok, state, compileScope);
} else if (tok->str() == "[") {
bool lambda = false;
if (state.cpp && isPrefixUnary(tok, state.cpp) && tok->link()->strAt(1) == "(") { // Lambda
// What we do here:
// - Nest the round bracket under the square bracket.
// - Nest what follows the lambda (if anything) with the lambda opening [
// - Compile the content of the lambda function as separate tree (this is done later)
// this must be consistent with isLambdaCaptureList
Token* squareBracket = tok;
Token* roundBracket = squareBracket->link()->next();
Token* curlyBracket = roundBracket->link()->next();
while (Token::Match(curlyBracket, "%name%|.|::"))
curlyBracket = curlyBracket->next();
if (Token::simpleMatch(curlyBracket, "{")) {
lambda = true;
squareBracket->astOperand1(roundBracket);
roundBracket->astOperand1(curlyBracket);
state.op.push(squareBracket);
tok = curlyBracket->link()->next();
}
}
if (!lambda) {
Token* tok2 = tok;
if (tok->strAt(1) != "]")
compileBinOp(tok, state, compileExpression);
else
compileUnaryOp(tok, state, compileExpression);
tok = tok2->link()->next();
}
} else if (tok->str() == "(" && (!iscast(tok) || Token::Match(tok->previous(), "if|while|for|switch|catch"))) {
Token* tok2 = tok;
tok = tok->next();
const bool opPrevTopSquare = !state.op.empty() && state.op.top() && state.op.top()->str() == "[";
const std::size_t oldOpSize = state.op.size();
compileExpression(tok, state);
tok = tok2;
if ((tok->previous() && tok->previous()->isName() && (tok->strAt(-1) != "return" && (!state.cpp || !Token::Match(tok->previous(), "throw|delete"))))
|| (tok->strAt(-1) == "]" && (!state.cpp || !Token::Match(tok->linkAt(-1)->previous(), "new|delete")))
|| (tok->strAt(-1) == ">" && tok->linkAt(-1))
|| (tok->strAt(-1) == ")" && !iscast(tok->linkAt(-1))) // Don't treat brackets to clarify precedence as function calls
|| (tok->strAt(-1) == "}" && opPrevTopSquare)) {
const bool operandInside = oldOpSize < state.op.size();
if (operandInside)
compileBinOp(tok, state, nullptr);
else
compileUnaryOp(tok, state, nullptr);
}
tok = tok->link()->next();
} else if (state.cpp && tok->str() == "{" && iscpp11init(tok)) {
if (Token::simpleMatch(tok, "{ }"))
compileUnaryOp(tok, state, compileExpression);
else
compileBinOp(tok, state, compileExpression);
if (Token::simpleMatch(tok, "}"))
tok = tok->next();
} else break;
}
}
static void compilePrecedence3(Token *&tok, AST_state& state)
{
compilePrecedence2(tok, state);
while (tok) {
if ((Token::Match(tok, "[+-!~*&]") || tok->tokType() == Token::eIncDecOp) &&
isPrefixUnary(tok, state.cpp)) {
if (Token::Match(tok, "* [*,)]")) {
Token* tok2 = tok->next();
while (tok2->next() && tok2->str() == "*")
tok2 = tok2->next();
if (Token::Match(tok2, "[>),]")) {
tok = tok2;
continue;
}
}
compileUnaryOp(tok, state, compilePrecedence3);
} else if (tok->str() == "(" && iscast(tok)) {
Token* tok2 = tok;
tok = tok->link()->next();
compilePrecedence3(tok, state);
compileUnaryOp(tok2, state, nullptr);
} else if (state.cpp && Token::Match(tok, "new %name%|::|(")) {
Token* newtok = tok;
tok = tok->next();
bool innertype = false;
if (tok->str() == "(") {
if (Token::Match(tok, "( &| %name%") && Token::Match(tok->link(), ") ( %type%") && Token::simpleMatch(tok->link()->linkAt(1), ") ("))
tok = tok->link()->next();
if (Token::Match(tok->link(), ") ::| %type%"))
tok = tok->link()->next();
else if (Token::Match(tok, "( %type%") && Token::Match(tok->link(), ") [();,[]")) {
tok = tok->next();
innertype = true;
} else if (Token::Match(tok, "( &| %name%") && Token::simpleMatch(tok->link(), ") (")) {
tok = tok->next();
innertype = true;
} else {
/* bad code */
continue;
}
}
state.op.push(tok);
while (Token::Match(tok, "%name%|*|&|<|::")) {
if (tok->link())
tok = tok->link();
tok = tok->next();
}
if (Token::Match(tok, "( const| %type% ) (")) {
state.op.push(tok->next());
tok = tok->link()->next();
compileBinOp(tok, state, compilePrecedence2);
} else if (tok && (tok->str() == "[" || tok->str() == "(" || tok->str() == "{"))
compilePrecedence2(tok, state);
else if (innertype && Token::simpleMatch(tok, ") [")) {
tok = tok->next();
compilePrecedence2(tok, state);
}
compileUnaryOp(newtok, state, nullptr);
if (innertype && Token::simpleMatch(tok, ") ,"))
tok = tok->next();
} else if (state.cpp && Token::Match(tok, "delete %name%|*|&|::|(|[")) {
Token* tok2 = tok;
tok = tok->next();
if (tok && tok->str() == "[")
tok = tok->link()->next();
compilePrecedence3(tok, state);
compileUnaryOp(tok2, state, nullptr);
}
// TODO: Handle sizeof
else break;
}
}
static void compilePointerToElem(Token *&tok, AST_state& state)
{
compilePrecedence3(tok, state);
while (tok) {
if (Token::simpleMatch(tok, ". *")) {
compileBinOp(tok, state, compilePrecedence3);
} else break;
}
}
static void compileMulDiv(Token *&tok, AST_state& state)
{
compilePointerToElem(tok, state);
while (tok) {
if (Token::Match(tok, "[/%]") || (tok->str() == "*" && !tok->astOperand1())) {
if (Token::Match(tok, "* [*,)]")) {
Token* tok2 = tok->next();
while (tok2->next() && tok2->str() == "*")
tok2 = tok2->next();
if (Token::Match(tok2, "[>),]")) {
tok = tok2;
break;
}
}
compileBinOp(tok, state, compilePointerToElem);
} else break;
}
}
static void compileAddSub(Token *&tok, AST_state& state)
{
compileMulDiv(tok, state);
while (tok) {
if (Token::Match(tok, "+|-") && !tok->astOperand1()) {
compileBinOp(tok, state, compileMulDiv);
} else break;
}
}
static void compileShift(Token *&tok, AST_state& state)
{
compileAddSub(tok, state);
while (tok) {
if (Token::Match(tok, "<<|>>")) {
compileBinOp(tok, state, compileAddSub);
} else break;
}
}
static void compileRelComp(Token *&tok, AST_state& state)
{
compileShift(tok, state);
while (tok) {
if (Token::Match(tok, "<|<=|>=|>") && !tok->link()) {
compileBinOp(tok, state, compileShift);
} else break;
}
}
static void compileEqComp(Token *&tok, AST_state& state)
{
compileRelComp(tok, state);
while (tok) {
if (Token::Match(tok, "==|!=")) {
compileBinOp(tok, state, compileRelComp);
} else break;
}
}
static void compileAnd(Token *&tok, AST_state& state)
{
compileEqComp(tok, state);
while (tok) {
if (tok->str() == "&" && !tok->astOperand1()) {
Token* tok2 = tok->next();
if (!tok2)
break;
if (tok2->str() == "&")
tok2 = tok2->next();
if (state.cpp && Token::Match(tok2, ",|)")) {
tok = tok2;
break; // rValue reference
}
compileBinOp(tok, state, compileEqComp);
} else break;
}
}
static void compileXor(Token *&tok, AST_state& state)
{
compileAnd(tok, state);
while (tok) {
if (tok->str() == "^") {
compileBinOp(tok, state, compileAnd);
} else break;
}
}
static void compileOr(Token *&tok, AST_state& state)
{
compileXor(tok, state);
while (tok) {
if (tok->str() == "|") {
compileBinOp(tok, state, compileXor);
} else break;
}
}
static void compileLogicAnd(Token *&tok, AST_state& state)
{
compileOr(tok, state);
while (tok) {
if (tok->str() == "&&") {
compileBinOp(tok, state, compileOr);
} else break;
}
}
static void compileLogicOr(Token *&tok, AST_state& state)
{
compileLogicAnd(tok, state);
while (tok) {
if (tok->str() == "||") {
compileBinOp(tok, state, compileLogicAnd);
} else break;
}
}
static void compileAssignTernary(Token *&tok, AST_state& state)
{
compileLogicOr(tok, state);
while (tok) {
if (tok->isAssignmentOp()) {
state.assign++;
compileBinOp(tok, state, compileAssignTernary);
if (state.assign > 0U)
state.assign--;
} else if (tok->str() == "?") {
// http://en.cppreference.com/w/cpp/language/operator_precedence says about ternary operator:
// "The expression in the middle of the conditional operator (between ? and :) is parsed as if parenthesized: its precedence relative to ?: is ignored."
// Hence, we rely on Tokenizer::prepareTernaryOpForAST() to add such parentheses where necessary.
if (tok->strAt(1) == ":") {
state.op.push(0);
}
const unsigned int assign = state.assign;
state.assign = 0U;
compileBinOp(tok, state, compileAssignTernary);
state.assign = assign;
} else if (tok->str() == ":") {
if (state.assign > 0U)
break;
compileBinOp(tok, state, compileAssignTernary);
} else break;
}
}
static void compileComma(Token *&tok, AST_state& state)
{
compileAssignTernary(tok, state);
while (tok) {
if (tok->str() == ",") {
compileBinOp(tok, state, compileAssignTernary);
} else break;
}
}
static void compileExpression(Token *&tok, AST_state& state)
{
if (state.depth > AST_MAX_DEPTH)
return; // ticket #5592
if (tok)
compileComma(tok, state);
}
static bool isLambdaCaptureList(const Token * tok)
{
// a lambda expression '[x](y){}' is compiled as:
// [
// `-(
// `-{
// see compilePrecedence2
if (tok->str() != "[")
return false;
if (!tok->astOperand1() || tok->astOperand1()->str() != "(")
return false;
const Token * params = tok->astOperand1();
if (!params || !params->astOperand1() || params->astOperand1()->str() != "{")
return false;
return true;
}
static Token * createAstAtToken(Token *tok, bool cpp)
{
if (Token::simpleMatch(tok, "for (")) {
Token *tok2 = skipDecl(tok->tokAt(2));