forked from danmar/cppcheck
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtemplatesimplifier.h
517 lines (457 loc) · 17.7 KB
/
templatesimplifier.h
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
/* -*- C++ -*-
* 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/>.
*/
//---------------------------------------------------------------------------
#ifndef templatesimplifierH
#define templatesimplifierH
//---------------------------------------------------------------------------
#include "config.h"
#include <cstdint>
#include <ctime>
#include <list>
#include <map>
#include <set>
#include <string>
#include <unordered_map>
#include <vector>
class ErrorLogger;
class Settings;
class Token;
class Tokenizer;
class TokenList;
struct newInstantiation;
/// @addtogroup Core
/// @{
/** @brief Simplify templates from the preprocessed and partially simplified code. */
class CPPCHECKLIB TemplateSimplifier {
friend class TestSimplifyTemplate;
public:
explicit TemplateSimplifier(Tokenizer &tokenizer);
const std::string& dump() const {
return mDump;
}
/**
*/
void checkComplicatedSyntaxErrorsInTemplates();
/**
* is the token pointing at a template parameters block
* < int , 3 > => yes
* \param tok start token that must point at "<"
* \return number of parameters (invalid parameters => 0)
*/
static unsigned int templateParameters(const Token *tok);
/**
* Token and its full scopename
*/
class TokenAndName {
Token *mToken;
std::string mScope;
std::string mName;
std::string mFullName;
const Token *mNameToken;
const Token *mParamEnd;
unsigned int mFlags;
enum : std::uint16_t {
fIsClass = (1 << 0), // class template
fIsFunction = (1 << 1), // function template
fIsVariable = (1 << 2), // variable template
fIsAlias = (1 << 3), // alias template
fIsSpecialization = (1 << 4), // user specialized template
fIsPartialSpecialization = (1 << 5), // user partial specialized template
fIsForwardDeclaration = (1 << 6), // forward declaration
fIsVariadic = (1 << 7), // variadic template
fIsFriend = (1 << 8), // friend template
fFamilyMask = (fIsClass | fIsFunction | fIsVariable)
};
void isClass(bool state) {
setFlag(fIsClass, state);
}
void isFunction(bool state) {
setFlag(fIsFunction, state);
}
void isVariable(bool state) {
setFlag(fIsVariable, state);
}
void isAlias(bool state) {
setFlag(fIsAlias, state);
}
void isSpecialization(bool state) {
setFlag(fIsSpecialization, state);
}
void isPartialSpecialization(bool state) {
setFlag(fIsPartialSpecialization, state);
}
void isForwardDeclaration(bool state) {
setFlag(fIsForwardDeclaration, state);
}
void isVariadic(bool state) {
setFlag(fIsVariadic, state);
}
void isFriend(bool state) {
setFlag(fIsFriend, state);
}
/**
* Get specified flag state.
* @param flag flag to get state of
* @return true if flag set or false in flag not set
*/
bool getFlag(unsigned int flag) const {
return ((mFlags & flag) != 0);
}
/**
* Set specified flag state.
* @param flag flag to set state
* @param state new state of flag
*/
void setFlag(unsigned int flag, bool state) {
mFlags = state ? mFlags | flag : mFlags & ~flag;
}
public:
/**
* Constructor used for instantiations.
* \param token template instantiation name token "name<...>"
* \param scope full qualification of template(scope)
*/
TokenAndName(Token *token, std::string scope);
/**
* Constructor used for declarations.
* \param token template declaration token "template < ... >"
* \param scope full qualification of template(scope)
* \param nameToken template name token "template < ... > class name"
* \param paramEnd template parameter end token ">"
*/
TokenAndName(Token *token, std::string scope, const Token *nameToken, const Token *paramEnd);
TokenAndName(const TokenAndName& other);
~TokenAndName();
bool operator == (const TokenAndName & rhs) const {
return mToken == rhs.mToken && mScope == rhs.mScope && mName == rhs.mName && mFullName == rhs.mFullName &&
mNameToken == rhs.mNameToken && mParamEnd == rhs.mParamEnd && mFlags == rhs.mFlags;
}
std::string dump(const std::vector<std::string>& fileNames) const;
// TODO: do not return non-const pointer from const object
Token * token() const {
return mToken;
}
void token(Token * token) {
mToken = token;
}
const std::string & scope() const {
return mScope;
}
const std::string & name() const {
return mName;
}
const std::string & fullName() const {
return mFullName;
}
const Token * nameToken() const {
return mNameToken;
}
const Token * paramEnd() const {
return mParamEnd;
}
void paramEnd(const Token *end) {
mParamEnd = end;
}
bool isClass() const {
return getFlag(fIsClass);
}
bool isFunction() const {
return getFlag(fIsFunction);
}
bool isVariable() const {
return getFlag(fIsVariable);
}
bool isAlias() const {
return getFlag(fIsAlias);
}
bool isSpecialization() const {
return getFlag(fIsSpecialization);
}
bool isPartialSpecialization() const {
return getFlag(fIsPartialSpecialization);
}
bool isForwardDeclaration() const {
return getFlag(fIsForwardDeclaration);
}
bool isVariadic() const {
return getFlag(fIsVariadic);
}
bool isFriend() const {
return getFlag(fIsFriend);
}
/**
* Get alias start token.
* template < ... > using X = foo < ... >;
* ^
* @return alias start token
*/
const Token * aliasStartToken() const;
/**
* Get alias end token.
* template < ... > using X = foo < ... >;
* ^
* @return alias end token
*/
const Token * aliasEndToken() const;
/**
* Is token an alias token?
* template < ... > using X = foo < ... >;
* ^
* @param tok token to check
* @return true if alias token, false if not
*/
bool isAliasToken(const Token *tok) const;
/**
* Is declaration the same family (class, function or variable).
*
* @param decl declaration to compare to
* @return true if same family, false if different family
*/
bool isSameFamily(const TemplateSimplifier::TokenAndName &decl) const {
// Make sure a family flag is set and matches.
// This works because at most only one flag will be set.
return ((mFlags & fFamilyMask) && (decl.mFlags & fFamilyMask));
}
};
/**
* Find last token of a template declaration.
* @param tok start token of declaration "template" or token after "template < ... >"
* @return last token of declaration or nullptr if syntax error
*/
static Token *findTemplateDeclarationEnd(Token *tok);
static const Token *findTemplateDeclarationEnd(const Token *tok);
/**
* Match template declaration/instantiation
* @param instance template instantiation
* @param numberOfArguments number of template arguments
* @param variadic last template argument is variadic
* @param patternAfter pattern that must match the tokens after the ">"
* @return match => true
*/
static bool instantiateMatch(const Token *instance, std::size_t numberOfArguments, bool variadic, const char patternAfter[]);
/**
* Match template declaration/instantiation
* @param tok The ">" token e.g. before "class"
* @return -1 to bail out or positive integer to identity the position
* of the template name.
*/
int getTemplateNamePosition(const Token *tok);
/**
* Get class template name position
* @param tok The ">" token e.g. before "class"
* @param namepos return offset to name
* @return true if name found, false if not
* */
static bool getTemplateNamePositionTemplateClass(const Token *tok, int &namepos);
/**
* Get function template name position
* @param tok The ">" token
* @param namepos return offset to name
* @return true if name found, false if not
* */
static bool getTemplateNamePositionTemplateFunction(const Token *tok, int &namepos);
/**
* Get variable template name position
* @param tok The ">" token
* @param namepos return offset to name
* @return true if name found, false if not
* */
static bool getTemplateNamePositionTemplateVariable(const Token *tok, int &namepos);
/**
* Simplify templates
* @param maxtime time when the simplification should be stopped
*/
void simplifyTemplates(std::time_t maxtime);
/**
* Simplify constant calculations such as "1+2" => "3"
* @param tok start token
* @return true if modifications to token-list are done.
* false if no modifications are done.
*/
static bool simplifyNumericCalculations(Token *tok, bool isTemplate = true);
/**
* Simplify constant calculations such as "1+2" => "3".
* This also performs simple cleanup of parentheses etc.
* @return true if modifications to token-list are done.
* false if no modifications are done.
*/
bool simplifyCalculations(Token* frontToken = nullptr, const Token *backToken = nullptr, bool isTemplate = true);
/** Simplify template instantiation arguments.
* @param start first token of arguments
* @param end token following last argument token
*/
void simplifyTemplateArgs(Token *start, const Token *end, std::vector<newInstantiation>* newInst = nullptr);
private:
/**
* Get template declarations
* @return true if code has templates.
*/
bool getTemplateDeclarations();
/** Add template instantiation.
* @param token first token of instantiation
* @param scope scope of instantiation
*/
void addInstantiation(Token *token, const std::string &scope);
/**
* Get template instantiations
*/
void getTemplateInstantiations();
/**
* Fix forward declared default argument values by copying them
* when they are not present in the declaration.
*/
void fixForwardDeclaredDefaultArgumentValues();
/**
* simplify template instantiations (use default argument values)
*/
void useDefaultArgumentValues();
/**
* simplify template instantiations (use default argument values)
* @param declaration template declaration or forward declaration
*/
void useDefaultArgumentValues(TokenAndName &declaration);
/**
* Try to locate a matching declaration for each user defined
* specialization.
*/
void getSpecializations();
/**
* Try to locate a matching declaration for each user defined
* partial specialization.
*/
void getPartialSpecializations();
/**
* simplify template aliases
*/
void simplifyTemplateAliases();
/**
* Simplify templates : expand all instantiations for a template
* @todo It seems that inner templates should be instantiated recursively
* @param templateDeclaration template declaration
* @param specializations template specializations (list each template name token)
* @param maxtime time when the simplification will stop
* @param expandedtemplates all templates that has been expanded so far. The full names are stored.
* @return true if the template was instantiated
*/
bool simplifyTemplateInstantiations(
const TokenAndName &templateDeclaration,
const std::list<const Token *> &specializations,
std::time_t maxtime,
std::set<std::string> &expandedtemplates);
/**
* Simplify templates : add namespace to template name
* @param templateDeclaration template declaration
* @param tok place to insert namespace
*/
void addNamespace(const TokenAndName &templateDeclaration, const Token *tok);
/**
* Simplify templates : check if namespace already present
* @param templateDeclaration template declaration
* @param tok place to start looking for namespace
* @return true if namespace already present
*/
static bool alreadyHasNamespace(const TokenAndName &templateDeclaration, const Token *tok);
/**
* Expand a template. Create "expanded" class/function at end of tokenlist.
* @param templateDeclaration Template declaration information
* @param templateInstantiation Full name of template
* @param typeParametersInDeclaration The type parameters of the template
* @param newName New name of class/function.
* @param copy copy or expand in place
*/
void expandTemplate(
const TokenAndName &templateDeclaration,
const TokenAndName &templateInstantiation,
const std::vector<const Token *> &typeParametersInDeclaration,
const std::string &newName,
bool copy);
/**
* Replace all matching template usages 'Foo < int >' => 'Foo<int>'
* @param instantiation Template instantiation information.
* @param typeStringsUsedInTemplateInstantiation template parameters. list of token strings.
* @param newName The new type name
*/
void replaceTemplateUsage(const TokenAndName &instantiation,
const std::list<std::string> &typeStringsUsedInTemplateInstantiation,
const std::string &newName);
/**
* @brief TemplateParametersInDeclaration
* @param tok template < typename T, typename S >
* ^ tok
* @param typeParametersInDeclaration template < typename T, typename S >
* ^ [0] ^ [1]
*/
static void getTemplateParametersInDeclaration(
const Token * tok,
std::vector<const Token *> & typeParametersInDeclaration);
/**
* Remove a specific "template < ..." template class/function
*/
static bool removeTemplate(Token *tok, std::map<Token*, Token*>* forwardDecls = nullptr);
/** Syntax error */
NORETURN static void syntaxError(const Token *tok);
static bool matchSpecialization(
const Token *templateDeclarationNameToken,
const Token *templateInstantiationNameToken,
const std::list<const Token *> & specializations);
/*
* Same as Token::eraseTokens() but tries to fix up lists with pointers to the deleted tokens.
* @param begin Tokens after this will be erased.
* @param end Tokens before this will be erased.
*/
static void eraseTokens(Token *begin, const Token *end);
/**
* Delete specified token without invalidating pointer to following token.
* tok will be invalidated.
* @param tok token to delete
*/
static void deleteToken(Token *tok);
/**
* Get the new token name.
* @param tok2 name token
* @param typeStringsUsedInTemplateInstantiation type strings use in template instantiation
* @return new token name
*/
std::string getNewName(
Token *tok2,
std::list<std::string> &typeStringsUsedInTemplateInstantiation);
void printOut(
const TokenAndName &tokenAndName,
const std::string &indent = " ") const;
void printOut(const std::string &text = "") const;
Tokenizer &mTokenizer;
TokenList &mTokenList;
const Settings &mSettings;
ErrorLogger &mErrorLogger;
bool mChanged{};
std::list<TokenAndName> mTemplateDeclarations;
std::list<TokenAndName> mTemplateForwardDeclarations;
std::map<Token *, Token *> mTemplateForwardDeclarationsMap;
std::map<Token *, Token *> mTemplateSpecializationMap;
std::map<Token *, Token *> mTemplatePartialSpecializationMap;
std::list<TokenAndName> mTemplateInstantiations;
std::list<TokenAndName> mInstantiatedTemplates;
std::list<TokenAndName> mMemberFunctionsToDelete;
std::vector<TokenAndName> mExplicitInstantiationsToDelete;
std::vector<TokenAndName> mTypesUsedInTemplateInstantiation;
std::unordered_map<const Token*, int> mTemplateNamePos;
std::string mDump;
};
/// @}
//---------------------------------------------------------------------------
#endif // templatesimplifierH