forked from danmar/cppcheck
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtokenlist.cpp
2239 lines (2017 loc) · 81.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-2024 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 "astutils.h"
#include "errorlogger.h"
#include "errortypes.h"
#include "keywords.h"
#include "library.h"
#include "path.h"
#include "platform.h"
#include "settings.h"
#include "standards.h"
#include "token.h"
#include <cctype>
#include <cstdint>
#include <exception>
#include <functional>
#include <iostream>
#include <utility>
#include <set>
#include <stack>
#include <unordered_set>
#include <simplecpp.h>
//#define N_ASSERT_LANG
#ifndef N_ASSERT_LANG
#include <cassert>
#define ASSERT_LANG(x) assert(x)
#else
#define ASSERT_LANG(x)
#endif
// 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 constexpr int AST_MAX_DEPTH = 150;
TokenList::TokenList(const Settings* settings)
: mTokensFrontBack(*this)
, mSettings(settings)
{
if (mSettings && (mSettings->enforcedLang != Standards::Language::None)) {
mLang = mSettings->enforcedLang;
}
}
TokenList::~TokenList()
{
deallocateTokens();
}
//---------------------------------------------------------------------------
const std::string& TokenList::getSourceFilePath() const
{
if (getFiles().empty()) {
return emptyString;
}
return getFiles()[0];
}
//---------------------------------------------------------------------------
// Deallocate lists..
void TokenList::deallocateTokens()
{
deleteTokens(mTokensFrontBack.front);
mTokensFrontBack.front = nullptr;
mTokensFrontBack.back = nullptr;
mFiles.clear();
}
void TokenList::determineCppC()
{
// only try to determine if it wasn't enforced
if (mLang == Standards::Language::None) {
ASSERT_LANG(!getSourceFilePath().empty());
mLang = Path::identify(getSourceFilePath(), mSettings ? mSettings->cppHeaderProbe : false);
// TODO: cannot enable assert as this might occur for unknown extensions
//ASSERT_LANG(mLang != Standards::Language::None);
if (mLang == Standards::Language::None) {
// TODO: should default to C instead like we do for headers
// default to C++
mLang = Standards::Language::CPP;
}
}
}
int TokenList::appendFileIfNew(std::string fileName)
{
// Has this file been tokenized already?
for (int i = 0; i < mFiles.size(); ++i)
if (Path::sameFileName(mFiles[i], fileName))
return i;
// The "mFiles" vector remembers what files have been tokenized..
mFiles.push_back(std::move(fileName));
// Update mIsC and mIsCpp properties
if (mFiles.size() == 1) { // Update only useful if first file added to _files
determineCppC();
}
return mFiles.size() - 1;
}
void TokenList::clangSetOrigFiles()
{
mOrigFiles = mFiles;
}
void TokenList::deleteTokens(Token *tok)
{
while (tok) {
Token *next = tok->next();
delete tok;
tok = next;
}
}
//---------------------------------------------------------------------------
// add a token.
//---------------------------------------------------------------------------
void TokenList::addtoken(const std::string& str, const nonneg int lineno, const nonneg int column, const nonneg 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, column, fileno, false);
begin = end+2;
}
if (begin != 0) {
addtoken(str.substr(begin), lineno, column, fileno, false);
return;
}
}
if (mTokensFrontBack.back) {
mTokensFrontBack.back->insertToken(str);
} else {
mTokensFrontBack.front = new Token(mTokensFrontBack);
mTokensFrontBack.back = mTokensFrontBack.front;
mTokensFrontBack.back->str(str);
}
mTokensFrontBack.back->linenr(lineno);
mTokensFrontBack.back->column(column);
mTokensFrontBack.back->fileIndex(fileno);
}
void TokenList::addtoken(const std::string& str, const Token *locationTok)
{
if (str.empty())
return;
if (mTokensFrontBack.back) {
mTokensFrontBack.back->insertToken(str);
} else {
mTokensFrontBack.front = new Token(mTokensFrontBack);
mTokensFrontBack.back = mTokensFrontBack.front;
mTokensFrontBack.back->str(str);
}
mTokensFrontBack.back->linenr(locationTok->linenr());
mTokensFrontBack.back->column(locationTok->column());
mTokensFrontBack.back->fileIndex(locationTok->fileIndex());
}
void TokenList::addtoken(const Token * tok, const nonneg int lineno, const nonneg int column, const nonneg int fileno)
{
if (tok == nullptr)
return;
if (mTokensFrontBack.back) {
mTokensFrontBack.back->insertToken(tok->str(), tok->originalName());
} else {
mTokensFrontBack.front = new Token(mTokensFrontBack);
mTokensFrontBack.back = mTokensFrontBack.front;
mTokensFrontBack.back->str(tok->str());
if (!tok->originalName().empty())
mTokensFrontBack.back->originalName(tok->originalName());
}
mTokensFrontBack.back->linenr(lineno);
mTokensFrontBack.back->column(column);
mTokensFrontBack.back->fileIndex(fileno);
mTokensFrontBack.back->flags(tok->flags());
}
void TokenList::addtoken(const Token *tok, const Token *locationTok)
{
if (tok == nullptr || locationTok == nullptr)
return;
if (mTokensFrontBack.back) {
mTokensFrontBack.back->insertToken(tok->str(), tok->originalName());
} else {
mTokensFrontBack.front = new Token(mTokensFrontBack);
mTokensFrontBack.back = mTokensFrontBack.front;
mTokensFrontBack.back->str(tok->str());
if (!tok->originalName().empty())
mTokensFrontBack.back->originalName(tok->originalName());
}
mTokensFrontBack.back->flags(tok->flags());
mTokensFrontBack.back->linenr(locationTok->linenr());
mTokensFrontBack.back->column(locationTok->column());
mTokensFrontBack.back->fileIndex(locationTok->fileIndex());
}
void TokenList::addtoken(const Token *tok)
{
if (tok == nullptr)
return;
if (mTokensFrontBack.back) {
mTokensFrontBack.back->insertToken(tok->str(), tok->originalName(), tok->getMacroName());
} else {
mTokensFrontBack.front = new Token(mTokensFrontBack);
mTokensFrontBack.back = mTokensFrontBack.front;
mTokensFrontBack.back->str(tok->str());
mTokensFrontBack.back->originalName(tok->originalName());
mTokensFrontBack.back->setMacroName(tok->getMacroName());
}
mTokensFrontBack.back->flags(tok->flags());
mTokensFrontBack.back->linenr(tok->linenr());
mTokensFrontBack.back->column(tok->column());
mTokensFrontBack.back->fileIndex(tok->fileIndex());
}
//---------------------------------------------------------------------------
// copyTokens - Copy and insert tokens
//---------------------------------------------------------------------------
Token *TokenList::copyTokens(Token *dest, const Token *first, const Token *last, bool one_line)
{
std::stack<Token *> links;
Token *tok2 = dest;
int linenr = dest->linenr();
const int commonFileIndex = dest->fileIndex();
for (const Token *tok = first; tok != last->next(); tok = tok->next()) {
tok2->insertToken(tok->str());
tok2 = tok2->next();
tok2->fileIndex(commonFileIndex);
tok2->linenr(linenr);
tok2->tokType(tok->tokType());
tok2->flags(tok->flags());
tok2->varId(tok->varId());
tok2->setTokenDebug(tok->getTokenDebug());
// Check for links and fix them up
if (Token::Match(tok2, "(|[|{"))
links.push(tok2);
else if (Token::Match(tok2, ")|]|}")) {
if (links.empty())
return tok2;
Token * link = links.top();
tok2->link(link);
link->link(tok2);
links.pop();
}
if (!one_line && tok->next())
linenr += tok->next()->linenr() - tok->linenr();
}
return tok2;
}
//---------------------------------------------------------------------------
// InsertTokens - Copy and insert tokens
//---------------------------------------------------------------------------
void TokenList::insertTokens(Token *dest, const Token *src, nonneg int n)
{
// TODO: put the linking in a helper?
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->column(src->column());
dest->varId(src->varId());
dest->tokType(src->tokType());
dest->flags(src->flags());
dest->setMacroName(src->getMacroName());
src = src->next();
--n;
}
}
//---------------------------------------------------------------------------
// Tokenize - tokenizes a given file.
//---------------------------------------------------------------------------
bool TokenList::createTokens(std::istream &code, const std::string& file0)
{
ASSERT_LANG(!file0.empty());
appendFileIfNew(file0);
return createTokensInternal(code, file0);
}
//---------------------------------------------------------------------------
bool TokenList::createTokens(std::istream &code, Standards::Language lang)
{
ASSERT_LANG(lang != Standards::Language::None);
if (mLang == Standards::Language::None) {
mLang = lang;
} else {
ASSERT_LANG(lang == mLang);
}
return createTokensInternal(code, "");
}
//---------------------------------------------------------------------------
bool TokenList::createTokensInternal(std::istream &code, const std::string& file0)
{
simplecpp::OutputList outputList;
simplecpp::TokenList tokens(code, mFiles, file0, &outputList);
createTokens(std::move(tokens));
return outputList.empty();
}
//---------------------------------------------------------------------------
// NOLINTNEXTLINE(cppcoreguidelines-rvalue-reference-param-not-moved)
void TokenList::createTokens(simplecpp::TokenList&& tokenList)
{
// TODO: what to do if the list has been filled already? clear mTokensFrontBack?
// tokenList.cfront() might be NULL if the file contained nothing to tokenize so we need to check the files instead
if (!tokenList.getFiles().empty()) {
// this is a copy
// TODO: this points to mFiles when called from createTokens(std::istream &, const std::string&)
mOrigFiles = mFiles = tokenList.getFiles();
}
else
mFiles.clear();
determineCppC();
for (const simplecpp::Token *tok = tokenList.cfront(); tok;) {
// TODO: move from TokenList
std::string str = tok->str();
// Float literal
if (str.size() > 1 && str[0] == '.' && std::isdigit(str[1]))
str = '0' + str;
if (mTokensFrontBack.back) {
mTokensFrontBack.back->insertToken(str);
} else {
mTokensFrontBack.front = new Token(mTokensFrontBack);
mTokensFrontBack.back = mTokensFrontBack.front;
mTokensFrontBack.back->str(str);
}
mTokensFrontBack.back->fileIndex(tok->location.fileIndex);
mTokensFrontBack.back->linenr(tok->location.line);
mTokensFrontBack.back->column(tok->location.col);
mTokensFrontBack.back->setMacroName(tok->macro);
tok = tok->next;
if (tok)
tokenList.deleteToken(tok->previous);
}
if (mSettings && mSettings->relativePaths) {
for (std::string & mFile : mFiles)
mFile = Path::getRelativePath(mFile, mSettings->basePaths);
}
Token::assignProgressValues(mTokensFrontBack.front);
}
//---------------------------------------------------------------------------
std::size_t TokenList::calculateHash() const
{
std::string hashData;
for (const Token* tok = front(); tok; tok = tok->next()) {
hashData += std::to_string(tok->flags());
hashData += std::to_string(tok->varId());
hashData += std::to_string(tok->tokType());
hashData += tok->str();
hashData += tok->originalName();
}
return (std::hash<std::string>{})(hashData);
}
//---------------------------------------------------------------------------
namespace {
struct AST_state {
std::stack<Token*> op;
int depth{};
int inArrayAssignment{};
bool cpp;
int assign{};
bool inCase{}; // true from case to :
bool stopAtColon{}; // help to properly parse ternary operators
const Token* functionCallEndPar{};
explicit AST_state(bool cpp) : cpp(cpp) {}
};
}
static Token* skipDecl(Token* tok, std::vector<Token*>* inner = nullptr)
{
auto isDecltypeFuncParam = [](const Token* tok) -> bool {
if (!Token::simpleMatch(tok, ")"))
return false;
tok = tok->next();
while (Token::Match(tok, "*|&|&&|const"))
tok = tok->next();
if (Token::simpleMatch(tok, "("))
tok = tok->link()->next();
return Token::Match(tok, "%name%| ,|)");
};
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, "%var% [:=({]")) {
return vartok;
} else if (Token::Match(vartok, "decltype|typeof (") && !isDecltypeFuncParam(tok->linkAt(1))) {
if (inner)
inner->push_back(vartok->tokAt(2));
return vartok->linkAt(1)->next();
}
vartok = vartok->next();
}
return tok;
}
static bool iscast(const Token *tok, bool cpp)
{
if (!Token::Match(tok, "( ::| %name%"))
return false;
if (Token::simpleMatch(tok->link(), ") ( )"))
return false;
if (Token::Match(tok->link(), ") %assign%|,|..."))
return false;
if (tok->previous() && tok->previous()->isName() && tok->strAt(-1) != "return" &&
(!cpp || !Token::Match(tok->previous(), "delete|throw")))
return false;
if (Token::simpleMatch(tok->previous(), ">") && tok->linkAt(-1))
return false;
if (Token::Match(tok, "( (| typeof (") && Token::Match(tok->link(), ") %num%"))
return true;
if (Token::Match(tok->link(), ") }|)|]|;"))
return false;
if (Token::Match(tok->link(), ") ++|-- [;)]"))
return false;
if (Token::Match(tok->link(), ") %cop%") && !Token::Match(tok->link(), ") [&*+-~!]"))
return false;
if (Token::Match(tok->previous(), "= ( %name% ) {") && tok->next()->varId() == 0)
return true;
bool type = false;
for (const Token *tok2 = tok->next(); tok2; tok2 = tok2->next()) {
if (tok2->varId() != 0)
return false;
if (cpp && !type && tok2->str() == "new")
return false;
while (tok2->link() && Token::Match(tok2, "(|[|<"))
tok2 = tok2->link()->next();
if (tok2->str() == ")") {
if (Token::simpleMatch(tok2, ") (") && Token::simpleMatch(tok2->linkAt(1), ") ."))
return true;
if (Token::simpleMatch(tok2, ") {") && !type) {
const Token *tok3 = tok2->linkAt(1);
while (tok3 != tok2 && Token::Match(tok3, "[{}]"))
tok3 = tok3->previous();
return tok3->str() != ";";
}
const bool res = type || tok2->strAt(-1) == "*" || Token::simpleMatch(tok2, ") ~") ||
(Token::Match(tok2, ") %any%") &&
(!tok2->next()->isOp() || Token::Match(tok2->next(), "!|~|++|--")) &&
!Token::Match(tok2->next(), "[[]);,?:.]"));
return res;
}
if (Token::Match(tok2, "&|&& )"))
return true;
if (!Token::Match(tok2, "%name%|*|::"))
return false;
if (tok2->isStandardType() && (tok2->strAt(1) != "(" || Token::Match(tok2->next(), "( * *| )")))
type = true;
}
return false;
}
// int(1), int*(2), ..
static Token * findCppTypeInitPar(Token *tok)
{
if (!tok || !Token::Match(tok->previous(), "[,()] %name%"))
return nullptr;
bool istype = false;
while (Token::Match(tok, "%name%|::|<")) {
if (tok->str() == "<") {
tok = tok->link();
if (!tok)
return nullptr;
}
istype |= tok->isStandardType();
tok = tok->next();
}
if (!istype)
return nullptr;
if (!Token::Match(tok, "[*&]"))
return nullptr;
while (Token::Match(tok, "[*&]"))
tok = tok->next();
return (tok && tok->str() == "(") ? tok : nullptr;
}
// X{} X<Y>{} etc
static bool iscpp11init_impl(const Token * tok);
static bool iscpp11init(const Token * const tok)
{
if (tok->isCpp11init() == TokenImpl::Cpp11init::UNKNOWN)
tok->setCpp11init(iscpp11init_impl(tok));
return tok->isCpp11init() == TokenImpl::Cpp11init::CPP11INIT;
}
static bool iscpp11init_impl(const Token * const tok)
{
if (Token::simpleMatch(tok, "{") && Token::simpleMatch(tok->link()->previous(), "; }"))
return false;
const Token *nameToken = tok;
while (nameToken && nameToken->str() == "{") {
if (nameToken->isCpp11init() != TokenImpl::Cpp11init::UNKNOWN)
return nameToken->isCpp11init() == TokenImpl::Cpp11init::CPP11INIT;
nameToken = nameToken->previous();
if (nameToken && nameToken->str() == "," && Token::simpleMatch(nameToken->previous(), "} ,"))
nameToken = nameToken->linkAt(-1);
}
if (!nameToken)
return false;
if (nameToken->str() == ")" && Token::simpleMatch(nameToken->link()->previous(), "decltype (") &&
!Token::simpleMatch(nameToken->link()->tokAt(-2), "."))
nameToken = nameToken->link()->previous();
if (Token::simpleMatch(nameToken, ", {"))
return true;
if (nameToken->str() == ">" && nameToken->link())
nameToken = nameToken->link()->previous();
if (Token::Match(nameToken, "]|*")) {
const Token* newTok = nameToken->link() ? nameToken->link()->previous() : nameToken->previous();
while (Token::Match(newTok, "%type%|::|*") && !newTok->isKeyword())
newTok = newTok->previous();
if (Token::simpleMatch(newTok, "new"))
return true;
}
auto isCaseStmt = [](const Token* colonTok) {
if (!Token::Match(colonTok->tokAt(-1), "%name%|%num%|%char%|) :"))
return false;
if (const Token* castTok = colonTok->linkAt(-1)) {
if (Token::simpleMatch(castTok->astParent(), "case"))
return true;
}
const Token* caseTok = colonTok->tokAt(-2);
while (caseTok && Token::Match(caseTok->tokAt(-1), "::|%name%"))
caseTok = caseTok->tokAt(-1);
return Token::simpleMatch(caseTok, "case");
};
const Token *endtok = nullptr;
if (Token::Match(nameToken, "%name%|return|: {") && !isCaseStmt(nameToken) &&
(!Token::simpleMatch(nameToken->tokAt(2), "[") || findLambdaEndScope(nameToken->tokAt(2))))
endtok = nameToken->linkAt(1);
else if (Token::Match(nameToken,"%name% <") && Token::simpleMatch(nameToken->linkAt(1),"> {"))
endtok = nameToken->linkAt(1)->linkAt(1);
else if (Token::Match(nameToken->previous(), "%name%|> ( {"))
endtok = nameToken->linkAt(1);
else if (Token::simpleMatch(nameToken, "decltype") && nameToken->linkAt(1))
endtok = nameToken->linkAt(1)->linkAt(1);
else
return false;
if (Token::Match(nameToken, "else|try|do|const|constexpr|override|volatile|&|&&"))
return false;
if (Token::simpleMatch(nameToken->previous(), ". void {") && nameToken->previous()->originalName() == "->")
return false; // trailing return type. The only function body that can contain no semicolon is a void function.
if (Token::simpleMatch(nameToken->previous(), "namespace") || Token::simpleMatch(nameToken, "namespace") /*anonymous namespace*/)
return false;
if (precedes(nameToken->next(), endtok) && !Token::Match(nameToken, "return|:")) {
// If there is semicolon between {..} this is not a initlist
for (const Token *tok2 = nameToken->next(); tok2 != endtok; tok2 = tok2->next()) {
if (tok2->str() == ";")
return false;
const Token * lambdaEnd = findLambdaEndScope(tok2);
if (lambdaEnd)
tok2 = lambdaEnd;
}
}
// There is no initialisation for example here: 'class Fred {};'
if (!Token::simpleMatch(endtok, "} ;"))
return true;
const Token *prev = nameToken;
while (Token::Match(prev, "%name%|::|:|<|>|(|)|,|%num%|%cop%|...")) {
if (Token::Match(prev, "class|struct|union|enum"))
return false;
prev = prev->previous();
}
return true;
}
static bool isQualifier(const Token* tok)
{
while (Token::Match(tok, "&|&&|*"))
tok = tok->next();
return Token::Match(tok, "{|;");
}
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 (state.depth > AST_MAX_DEPTH)
throw InternalError(tok, "maximum AST depth exceeded", InternalError::AST);
if (tok)
f(tok, state);
state.depth--;
}
if (!state.op.empty() && (!precedes(state.op.top(), unaryop) || unaryop->isIncDecOp() || Token::Match(unaryop, "[({[]"))) { // nullary functions, empty lists/arrays
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();
if (Token::Match(binop, "::|. ~"))
tok = tok->next();
state.depth++;
if (tok && state.depth <= AST_MAX_DEPTH)
f(tok, state);
if (state.depth > AST_MAX_DEPTH)
throw InternalError(tok, "maximum AST depth exceeded", InternalError::AST);
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 && Token::Match(tok->previous(), "[{,] . %name%")) { // Jump over . in C style struct initialization
state.op.push(tok);
tok->astOperand1(tok->next());
tok = tok->tokAt(2);
}
if (state.inArrayAssignment && Token::Match(tok->previous(), "[{,] [ %num%|%name% ]")) {
state.op.push(tok);
tok->astOperand1(tok->next());
tok = tok->tokAt(3);
}
if (tok->isLiteral()) {
state.op.push(tok);
do {
tok = tok->next();
} while (Token::Match(tok, "%name%|%str%"));
} else if (tok->isName()) {
if (Token::Match(tok, "return|case") || (state.cpp && (tok->str() == "throw"))) {
if (tok->str() == "case")
state.inCase = true;
const bool tokIsReturn = tok->str() == "return";
const bool stopAtColon = state.stopAtColon;
state.stopAtColon=true;
compileUnaryOp(tok, state, compileExpression);
state.stopAtColon=stopAtColon;
if (tokIsReturn)
state.op.pop();
if (state.inCase && Token::simpleMatch(tok, ": ;")) {
state.inCase = false;
tok = tok->next();
}
} else if (Token::Match(tok, "sizeof !!(")) {
compileUnaryOp(tok, state, compileExpression);
state.op.pop();
} else if (state.cpp && findCppTypeInitPar(tok)) { // int(0), int*(123), ..
tok = findCppTypeInitPar(tok);
state.op.push(tok);
tok = tok->tokAt(2);
} else if (state.cpp && iscpp11init(tok)) { // X{} X<Y>{} etc
state.op.push(tok);
tok = tok->next();
if (tok->str() == "<")
tok = tok->link()->next();
if (Token::Match(tok, "{ . %name% =|{")) {
const Token* end = tok->link();
const int inArrayAssignment = state.inArrayAssignment;
state.inArrayAssignment = 1;
compileBinOp(tok, state, compileExpression);
state.inArrayAssignment = inArrayAssignment;
if (tok == end)
tok = tok->next();
else
throw InternalError(tok, "Syntax error. Unexpected tokens in designated initializer.", InternalError::AST);
}
} else if (!state.cpp || !Token::Match(tok, "new|delete %name%|*|&|::|(|[")) {
std::vector<Token*> inner;
tok = skipDecl(tok, &inner);
for (Token* tok3 : inner) {
AST_state state1(state.cpp);
compileExpression(tok3, state1);
}
bool repeat = true;
while (repeat) {
repeat = false;
if (Token::Match(tok->next(), "%name%")) {
tok = tok->next();
repeat = true;
}
if (Token::simpleMatch(tok->next(), "<") && Token::Match(tok->linkAt(1), "> %name%")) {
tok = tok->linkAt(1)->next();
repeat = true;
}
}
state.op.push(tok);
if (Token::Match(tok, "%name% <") && tok->linkAt(1))
tok = tok->linkAt(1);
else if (Token::Match(tok, "%name% ...") || (state.op.size() == 1 && state.depth == 0 && Token::Match(tok->tokAt(-3), "!!& ) ( %name% ) =")))
tok = tok->next();
tok = tok->next();
if (Token::Match(tok, "%str%")) {
while (Token::Match(tok, "%name%|%str%"))
tok = tok->next();
}
if (Token::Match(tok, "%name% %assign%"))
tok = tok->next();
}
} else if (tok->str() == "{") {
const Token *prev = tok->previous();
if (Token::simpleMatch(prev, ") {") && iscast(prev->link(), state.cpp))
prev = prev->link()->previous();
if (Token::simpleMatch(tok->link(),"} [")) {
tok = tok->next();
} else if ((state.cpp && iscpp11init(tok)) || Token::simpleMatch(tok->previous(), "] {")) {
Token *const end = tok->link();
if (state.op.empty() || Token::Match(tok->previous(), "[{,]") || Token::Match(tok->tokAt(-2), "%name% (")) {
if (Token::Match(tok->tokAt(-1), "!!, { . %name% =|{")) {
const int inArrayAssignment = state.inArrayAssignment;
state.inArrayAssignment = 1;
compileBinOp(tok, state, compileExpression);
state.inArrayAssignment = inArrayAssignment;
} else if (Token::simpleMatch(tok, "{ }")) {
state.op.push(tok);
tok = tok->next();
} else {
compileUnaryOp(tok, state, compileExpression);
if (precedes(tok,end)) // typically for something like `MACRO(x, { if (c) { ... } })`, where end is the last curly, and tok is the open curly for the if
tok = end;
}
} else
compileBinOp(tok, state, compileExpression);
if (tok != end)
throw InternalError(tok, "Syntax error. Unexpected tokens in initializer.", InternalError::AST);
if (tok->next())
tok = tok->next();
} else if (state.cpp && Token::Match(tok->tokAt(-2), "%name% ( {") && !Token::findsimplematch(tok, ";", tok->link())) {
if (Token::simpleMatch(tok, "{ }"))
tok = tok->tokAt(2);
else {
Token *tok1 = tok;
state.inArrayAssignment++;
compileUnaryOp(tok, state, compileExpression);
state.inArrayAssignment--;
tok = tok1->link()->next();
}
} else if (!state.inArrayAssignment && !Token::simpleMatch(prev, "=")) {
state.op.push(tok);
tok = tok->link()->next();
} else {
if (tok->link() != tok->next()) {
state.inArrayAssignment++;
compileUnaryOp(tok, state, compileExpression);
if (Token::Match(tok, "} [,};]") && state.inArrayAssignment > 0) {
tok = tok->next();
state.inArrayAssignment--;
}
} else {
state.op.push(tok);
tok = tok->tokAt(2);
}
}
}
}
static void compileScope(Token *&tok, AST_state& state)
{
compileTerm(tok, state);
while (tok) {
if (tok->str() == "::") {
const Token *lastOp = state.op.empty() ? nullptr : state.op.top();
if (Token::Match(lastOp, ":: %name%"))
lastOp = lastOp->next();
if (Token::Match(lastOp, "%name%") &&
(lastOp->next() == tok || (Token::Match(lastOp, "%name% <") && lastOp->linkAt(1) && tok == lastOp->linkAt(1)->next())))
compileBinOp(tok, state, compileTerm);
else
compileUnaryOp(tok, state, compileTerm);
} else break;
}
}
static bool isPrefixUnary(const Token* tok, bool cpp)
{
if (cpp && Token::simpleMatch(tok->previous(), "* [") && Token::simpleMatch(tok->link(), "] {")) {
for (const Token* prev = tok->previous(); Token::Match(prev, "%name%|::|*|&|>|>>"); prev = prev->previous()) {
if (Token::Match(prev, ">|>>")) {
if (!prev->link())
break;
prev = prev->link();
}
if (prev->str() == "new")
return false;
}
}
if (!tok->previous()
|| ((Token::Match(tok->previous(), "(|[|{|%op%|;|?|:|,|.|case|return|::") || (cpp && tok->strAt(-1) == "throw"))
&& (tok->previous()->tokType() != Token::eIncDecOp || tok->tokType() == Token::eIncDecOp)))
return true;
if (tok->strAt(-1) == "}") {
const Token* parent = tok->linkAt(-1)->tokAt(-1);
return !Token::Match(parent, "%type%") || parent->isKeyword();
}
if (tok->str() == "*" && tok->previous()->tokType() == Token::eIncDecOp && isPrefixUnary(tok->previous(), cpp))
return true;
return tok->strAt(-1) == ")" && iscast(tok->linkAt(-1), cpp);
}
static void compilePrecedence2(Token *&tok, AST_state& state)
{
auto doCompileScope = [&](const Token* tok) -> bool {
const bool isStartOfCpp11Init = state.cpp && tok && tok->str() == "{" && iscpp11init(tok);
if (isStartOfCpp11Init || Token::simpleMatch(tok, "(")) {
tok = tok->previous();
while (Token::simpleMatch(tok, "*"))
tok = tok->previous();
while (tok && Token::Match(tok->previous(), ":: %type%"))
tok = tok->tokAt(-2);
if (tok && !tok->isKeyword())
tok = tok->previous();
return !Token::Match(tok, "new ::| %type%");
}
return !findLambdaEndTokenWithoutAST(tok);
};
bool isNew = true;
if (doCompileScope(tok)) {
compileScope(tok, state);
isNew = false;
}
while (tok) {
if (tok->tokType() == Token::eIncDecOp && !isPrefixUnary(tok, state.cpp)) {
compileUnaryOp(tok, state, compileScope);
} else if (tok->str() == "...") {
if (!Token::simpleMatch(tok->previous(), ")"))
state.op.push(tok);
tok = tok->next();
break;
} else if (tok->str() == "." && tok->strAt(1) != "*") {
if (tok->strAt(1) == ".") {
state.op.push(tok);
tok = tok->tokAt(3);
break;
}
if (!Token::Match(tok->tokAt(-1), "[{,]"))
compileBinOp(tok, state, compileScope);
else
compileUnaryOp(tok, state, compileScope);
} else if (tok->str() == "[") {
if (state.cpp && isPrefixUnary(tok, /*cpp*/ true) && Token::Match(tok->link(), "] (|{|<")) { // 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* const squareBracket = tok;
// Parse arguments in the capture list
if (tok->strAt(1) != "]") {
Token* tok2 = tok->next();
AST_state state2(state.cpp);
compileExpression(tok2, state2);
if (!state2.op.empty()) {
squareBracket->astOperand2(state2.op.top());
}
}
const bool hasTemplateArg = Token::simpleMatch(squareBracket->link(), "] <") &&
Token::simpleMatch(squareBracket->link()->linkAt(1), "> (");
if (Token::simpleMatch(squareBracket->link(), "] (") || hasTemplateArg) {
Token* const roundBracket = hasTemplateArg ? squareBracket->link()->linkAt(1)->next() : squareBracket->link()->next();
Token* curlyBracket = roundBracket->link()->next();
while (Token::Match(curlyBracket, "mutable|const|constexpr|consteval"))
curlyBracket = curlyBracket->next();
if (Token::simpleMatch(curlyBracket, "noexcept")) {
if (Token::simpleMatch(curlyBracket->next(), "("))