--------------------------------------------------------------------------- For C++ code, warn if C-style casts are used on pointer types ---------------------------------------------------------------------------
| 330 | // For C++ code, warn if C-style casts are used on pointer types |
| 331 | //--------------------------------------------------------------------------- |
| 332 | void CheckOtherImpl::warningOldStylePointerCast() |
| 333 | { |
| 334 | // Only valid on C++ code |
| 335 | if (!mTokenizer->isCPP()) |
| 336 | return; |
| 337 | |
| 338 | if (!mSettings.severity.isEnabled(Severity::style) && !mSettings.isPremiumEnabled("cstyleCast")) |
| 339 | return; |
| 340 | |
| 341 | logChecker("CheckOther::warningOldStylePointerCast"); // style,c++ |
| 342 | |
| 343 | const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase(); |
| 344 | for (const Scope * scope : symbolDatabase->functionScopes) { |
| 345 | const Token* tok; |
| 346 | if (scope->function && scope->function->isConstructor()) |
| 347 | tok = scope->classDef; |
| 348 | else |
| 349 | tok = scope->bodyStart; |
| 350 | for (; tok && tok != scope->bodyEnd; tok = tok->next()) { |
| 351 | // Old style pointer casting.. |
| 352 | if (!tok->isCast() || tok->isBinaryOp()) |
| 353 | continue; |
| 354 | if (isDangerousTypeConversion(tok)) |
| 355 | continue; |
| 356 | const Token* const errtok = tok; |
| 357 | const Token* castTok = tok->next(); |
| 358 | while (Token::Match(castTok, "const|volatile|class|struct|union|%type%|::")) { |
| 359 | castTok = castTok->next(); |
| 360 | if (Token::simpleMatch(castTok, "<") && castTok->link()) |
| 361 | castTok = castTok->link()->next(); |
| 362 | } |
| 363 | if (castTok == tok->next()) |
| 364 | continue; |
| 365 | bool isPtr = false, isRef = false; |
| 366 | while (Token::Match(castTok, "*|const|&")) { |
| 367 | if (castTok->str() == "*") |
| 368 | isPtr = true; |
| 369 | else if (castTok->str() == "&") |
| 370 | isRef = true; |
| 371 | castTok = castTok->next(); |
| 372 | } |
| 373 | if ((!isPtr && !isRef) || !Token::Match(castTok, ") (| %name%|%bool%|%char%|%str%|&")) |
| 374 | continue; |
| 375 | |
| 376 | if (Token::Match(tok->previous(), "%type%")) |
| 377 | continue; |
| 378 | |
| 379 | // skip first "const" in "const Type* const" |
| 380 | while (Token::Match(tok->next(), "const|volatile|class|struct|union")) |
| 381 | tok = tok->next(); |
| 382 | const Token* typeTok = tok->next(); |
| 383 | // skip second "const" in "const Type* const" |
| 384 | if (tok->strAt(3) == "const") |
| 385 | tok = tok->next(); |
| 386 | |
| 387 | const Token *p = tok->tokAt(4); |
| 388 | if (p->hasKnownIntValue() && p->getKnownIntValue()==0) // Casting nullpointers is safe |
| 389 | continue; |