Cppcheck
preprocessor.cpp
Go to the documentation of this file.
00001 /*
00002  * Cppcheck - A tool for static C/C++ code analysis
00003  * Copyright (C) 2007-2013 Daniel Marjamäki and Cppcheck team.
00004  *
00005  * This program is free software: you can redistribute it and/or modify
00006  * it under the terms of the GNU General Public License as published by
00007  * the Free Software Foundation, either version 3 of the License, or
00008  * (at your option) any later version.
00009  *
00010  * This program is distributed in the hope that it will be useful,
00011  * but WITHOUT ANY WARRANTY; without even the implied warranty of
00012  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
00013  * GNU General Public License for more details.
00014  *
00015  * You should have received a copy of the GNU General Public License
00016  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
00017  */
00018 
00019 
00020 #include "preprocessor.h"
00021 #include "tokenize.h"
00022 #include "token.h"
00023 #include "path.h"
00024 #include "errorlogger.h"
00025 #include "settings.h"
00026 
00027 #include <algorithm>
00028 #include <sstream>
00029 #include <fstream>
00030 #include <cstdlib>
00031 #include <cctype>
00032 #include <vector>
00033 #include <set>
00034 #include <stack>
00035 
00036 bool Preprocessor::missingIncludeFlag;
00037 
00038 char Preprocessor::macroChar = char(1);
00039 
00040 Preprocessor::Preprocessor(Settings *settings, ErrorLogger *errorLogger) : _settings(settings), _errorLogger(errorLogger)
00041 {
00042 
00043 }
00044 
00045 void Preprocessor::writeError(const std::string &fileName, const unsigned int linenr, ErrorLogger *errorLogger, const std::string &errorType, const std::string &errorText)
00046 {
00047     if (!errorLogger)
00048         return;
00049 
00050     std::list<ErrorLogger::ErrorMessage::FileLocation> locationList;
00051     ErrorLogger::ErrorMessage::FileLocation loc;
00052     loc.line = linenr;
00053     loc.setfile(fileName);
00054     locationList.push_back(loc);
00055     errorLogger->reportErr(ErrorLogger::ErrorMessage(locationList,
00056                            Severity::error,
00057                            errorText,
00058                            errorType,
00059                            false));
00060 }
00061 
00062 static unsigned char readChar(std::istream &istr, unsigned int bom)
00063 {
00064     unsigned char ch = (unsigned char)istr.get();
00065 
00066     // For UTF-16 encoded files the BOM is 0xfeff/0xfffe. If the
00067     // character is non-ASCII character then replace it with 0xff
00068     if (bom == 0xfeff || bom == 0xfffe) {
00069         unsigned char ch2 = (unsigned char)istr.get();
00070         int ch16 = (bom == 0xfeff) ? (ch<<8 | ch2) : (ch2<<8 | ch);
00071         ch = (unsigned char)((ch16 >= 0x80) ? 0xff : ch16);
00072     }
00073 
00074     // Handling of newlines..
00075     if (ch == '\r') {
00076         ch = '\n';
00077         if (bom == 0 && (char)istr.peek() == '\n')
00078             (void)istr.get();
00079         else if (bom == 0xfeff || bom == 0xfffe) {
00080             int c1 = istr.get();
00081             int c2 = istr.get();
00082             int ch16 = (bom == 0xfeff) ? (c1<<8 | c2) : (c2<<8 | c1);
00083             if (ch16 != '\n') {
00084                 istr.unget();
00085                 istr.unget();
00086             }
00087         }
00088     }
00089 
00090     return ch;
00091 }
00092 
00093 // Concatenates a list of strings, inserting a separator between parts
00094 static std::string join(const std::set<std::string>& list, char separator)
00095 {
00096     std::string s;
00097     for (std::set<std::string>::const_iterator it = list.begin(); it != list.end(); ++it) {
00098         if (!s.empty())
00099             s += separator;
00100 
00101         s += *it;
00102     }
00103     return s;
00104 }
00105 
00106 // Removes duplicate string portions separated by the specified separator
00107 static std::string unify(const std::string &s, char separator)
00108 {
00109     std::set<std::string> parts;
00110 
00111     std::string::size_type prevPos = 0;
00112     for (std::string::size_type pos = 0; pos < s.length(); ++pos) {
00113         if (s[pos] == separator) {
00114             if (pos > prevPos)
00115                 parts.insert(s.substr(prevPos, pos - prevPos));
00116             prevPos = pos + 1;
00117         }
00118     }
00119     if (prevPos < s.length())
00120         parts.insert(s.substr(prevPos));
00121 
00122     return join(parts, separator);
00123 }
00124 
00125 /** Just read the code into a string. Perform simple cleanup of the code */
00126 std::string Preprocessor::read(std::istream &istr, const std::string &filename)
00127 {
00128     // The UTF-16 BOM is 0xfffe or 0xfeff.
00129     unsigned int bom = 0;
00130     if (istr.peek() >= 0xfe) {
00131         bom = ((unsigned int)istr.get() << 8);
00132         if (istr.peek() >= 0xfe)
00133             bom |= (unsigned int)istr.get();
00134     }
00135 
00136     // ------------------------------------------------------------------------------------------
00137     //
00138     // handling <backslash><newline>
00139     // when this is encountered the <backslash><newline> will be "skipped".
00140     // on the next <newline>, extra newlines will be added
00141     std::ostringstream code;
00142     unsigned int newlines = 0;
00143     for (unsigned char ch = readChar(istr,bom); istr.good(); ch = readChar(istr,bom)) {
00144         // Replace assorted special chars with spaces..
00145         if (((ch & 0x80) == 0) && (ch != '\n') && (std::isspace(ch) || std::iscntrl(ch)))
00146             ch = ' ';
00147 
00148         // <backslash><newline>..
00149         // for gcc-compatibility the trailing spaces should be ignored
00150         // for vs-compatibility the trailing spaces should be kept
00151         // See tickets #640 and #1869
00152         // The solution for now is to have a compiler-dependent behaviour.
00153         if (ch == '\\') {
00154             unsigned char chNext;
00155 
00156             std::string spaces;
00157 
00158 #ifdef __GNUC__
00159             // gcc-compatibility: ignore spaces
00160             for (;; spaces += ' ') {
00161                 chNext = (unsigned char)istr.peek();
00162                 if (chNext != '\n' && chNext != '\r' &&
00163                     (std::isspace(chNext) || std::iscntrl(chNext))) {
00164                     // Skip whitespace between <backslash> and <newline>
00165                     (void)readChar(istr,bom);
00166                     continue;
00167                 }
00168 
00169                 break;
00170             }
00171 #else
00172             // keep spaces
00173             chNext = (unsigned char)istr.peek();
00174 #endif
00175             if (chNext == '\n' || chNext == '\r') {
00176                 ++newlines;
00177                 (void)readChar(istr,bom);   // Skip the "<backslash><newline>"
00178             } else {
00179                 code << "\\" << spaces;
00180             }
00181         } else {
00182             code << char(ch);
00183 
00184             // if there has been <backslash><newline> sequences, add extra newlines..
00185             if (ch == '\n' && newlines > 0) {
00186                 code << std::string(newlines, '\n');
00187                 newlines = 0;
00188             }
00189         }
00190     }
00191     std::string result = code.str();
00192     code.str("");
00193 
00194     // ------------------------------------------------------------------------------------------
00195     //
00196     // Remove all comments..
00197     result = removeComments(result, filename);
00198 
00199     // ------------------------------------------------------------------------------------------
00200     //
00201     // Clean up all preprocessor statements
00202     result = preprocessCleanupDirectives(result);
00203 
00204     // ------------------------------------------------------------------------------------------
00205     //
00206     // Clean up preprocessor #if statements with Parentheses
00207     result = removeParentheses(result);
00208 
00209     // Remove '#if 0' blocks
00210     if (result.find("#if 0\n") != std::string::npos)
00211         result = removeIf0(result);
00212 
00213     return result;
00214 }
00215 
00216 std::string Preprocessor::preprocessCleanupDirectives(const std::string &processedFile)
00217 {
00218     std::ostringstream code;
00219     std::istringstream sstr(processedFile);
00220 
00221     std::string line;
00222     while (std::getline(sstr, line)) {
00223         // Trim lines..
00224         if (!line.empty() && line[0] == ' ')
00225             line.erase(0, line.find_first_not_of(" "));
00226         if (!line.empty() && line[line.size()-1] == ' ')
00227             line.erase(line.find_last_not_of(" ") + 1);
00228 
00229         // Preprocessor
00230         if (!line.empty() && line[0] == '#') {
00231             enum {
00232                 ESC_NONE,
00233                 ESC_SINGLE,
00234                 ESC_DOUBLE
00235             } escapeStatus = ESC_NONE;
00236 
00237             char prev = ' '; // hack to make it skip spaces between # and the directive
00238             code << "#";
00239             std::string::const_iterator i = line.begin();
00240             ++i;
00241 
00242             // need space.. #if( => #if (
00243             bool needSpace = true;
00244             while (i != line.end()) {
00245                 // disable esc-mode
00246                 if (escapeStatus != ESC_NONE) {
00247                     if (prev != '\\' && escapeStatus == ESC_SINGLE && *i == '\'') {
00248                         escapeStatus = ESC_NONE;
00249                     }
00250                     if (prev != '\\' && escapeStatus == ESC_DOUBLE && *i == '"') {
00251                         escapeStatus = ESC_NONE;
00252                     }
00253                 } else {
00254                     // enable esc-mode
00255                     if (escapeStatus == ESC_NONE && *i == '"')
00256                         escapeStatus = ESC_DOUBLE;
00257                     if (escapeStatus == ESC_NONE && *i == '\'')
00258                         escapeStatus = ESC_SINGLE;
00259                 }
00260                 // skip double whitespace between arguments
00261                 if (escapeStatus == ESC_NONE && prev == ' ' && *i == ' ') {
00262                     ++i;
00263                     continue;
00264                 }
00265                 // Convert #if( to "#if ("
00266                 if (escapeStatus == ESC_NONE) {
00267                     if (needSpace) {
00268                         if (*i == '(' || *i == '!')
00269                             code << " ";
00270                         else if (!std::isalpha(*i))
00271                             needSpace = false;
00272                     }
00273                     if (*i == '#')
00274                         needSpace = true;
00275                 }
00276                 code << *i;
00277                 if (escapeStatus != ESC_NONE && prev == '\\' && *i == '\\') {
00278                     prev = ' ';
00279                 } else {
00280                     prev = *i;
00281                 }
00282                 ++i;
00283             }
00284             if (escapeStatus != ESC_NONE) {
00285                 // unmatched quotes.. compiler should probably complain about this..
00286             }
00287         } else {
00288             // Do not mess with regular code..
00289             code << line;
00290         }
00291         code << (sstr.eof()?"":"\n");
00292     }
00293 
00294     return code.str();
00295 }
00296 
00297 static bool hasbom(const std::string &str)
00298 {
00299     return bool(str.size() >= 3 &&
00300                 static_cast<unsigned char>(str[0]) == 0xef &&
00301                 static_cast<unsigned char>(str[1]) == 0xbb &&
00302                 static_cast<unsigned char>(str[2]) == 0xbf);
00303 }
00304 
00305 
00306 // This wrapper exists because Sun's CC does not allow a static_cast
00307 // from extern "C" int(*)(int) to int(*)(int).
00308 static int tolowerWrapper(int c)
00309 {
00310     return std::tolower(c);
00311 }
00312 
00313 
00314 static bool isFallThroughComment(std::string comment)
00315 {
00316     // convert comment to lower case without whitespace
00317     for (std::string::iterator i = comment.begin(); i != comment.end();) {
00318         if (std::isspace(static_cast<unsigned char>(*i)))
00319             i = comment.erase(i);
00320         else
00321             ++i;
00322     }
00323     std::transform(comment.begin(), comment.end(), comment.begin(), tolowerWrapper);
00324 
00325     return comment.find("fallthr") != std::string::npos ||
00326            comment.find("fallsthr") != std::string::npos ||
00327            comment.find("fall-thr") != std::string::npos ||
00328            comment.find("dropthr") != std::string::npos ||
00329            comment.find("passthr") != std::string::npos ||
00330            comment.find("nobreak") != std::string::npos ||
00331            comment == "fall";
00332 }
00333 
00334 std::string Preprocessor::removeComments(const std::string &str, const std::string &filename)
00335 {
00336     // For the error report
00337     unsigned int lineno = 1;
00338 
00339     // handling <backslash><newline>
00340     // when this is encountered the <backslash><newline> will be "skipped".
00341     // on the next <newline>, extra newlines will be added
00342     unsigned int newlines = 0;
00343     std::ostringstream code;
00344     unsigned char previous = 0;
00345     bool inPreprocessorLine = false;
00346     std::vector<std::string> suppressionIDs;
00347     bool fallThroughComment = false;
00348 
00349     for (std::string::size_type i = hasbom(str) ? 3U : 0U; i < str.length(); ++i) {
00350         unsigned char ch = static_cast<unsigned char>(str[i]);
00351         if (ch & 0x80) {
00352             std::ostringstream errmsg;
00353             errmsg << "The code contains characters that are unhandled. "
00354                    << "Neither unicode nor extended ASCII are supported. "
00355                    << "(line=" << lineno << ", character code=" << std::hex << (int(ch) & 0xff) << ")";
00356             writeError(filename, lineno, _errorLogger, "syntaxError", errmsg.str());
00357         }
00358 
00359         if ((str.compare(i, 7, "#error ") == 0 && (!_settings || _settings->userDefines.empty())) ||
00360             str.compare(i, 9, "#warning ") == 0) {
00361 
00362             if (str.compare(i, 6, "#error") == 0)
00363                 code << "#error";
00364 
00365             i = str.find("\n", i);
00366             if (i == std::string::npos)
00367                 break;
00368 
00369             --i;
00370             continue;
00371         }
00372 
00373         // First skip over any whitespace that may be present
00374         if (std::isspace(ch)) {
00375             if (ch == ' ' && previous == ' ') {
00376                 // Skip double white space
00377             } else {
00378                 code << char(ch);
00379                 previous = ch;
00380             }
00381 
00382             // if there has been <backslash><newline> sequences, add extra newlines..
00383             if (ch == '\n') {
00384                 if (previous != '\\')
00385                     inPreprocessorLine = false;
00386                 ++lineno;
00387                 if (newlines > 0) {
00388                     code << std::string(newlines, '\n');
00389                     newlines = 0;
00390                     previous = '\n';
00391                 }
00392             }
00393 
00394             continue;
00395         }
00396 
00397         // Remove comments..
00398         if (str.compare(i, 2, "//", 0, 2) == 0) {
00399             std::size_t commentStart = i + 2;
00400             i = str.find('\n', i);
00401             if (i == std::string::npos)
00402                 break;
00403             std::string comment(str, commentStart, i - commentStart);
00404 
00405             if (_settings && _settings->_inlineSuppressions) {
00406                 std::istringstream iss(comment);
00407                 std::string word;
00408                 iss >> word;
00409                 if (word == "cppcheck-suppress") {
00410                     iss >> word;
00411                     if (iss)
00412                         suppressionIDs.push_back(word);
00413                 }
00414             }
00415 
00416             if (isFallThroughComment(comment)) {
00417                 fallThroughComment = true;
00418             }
00419 
00420             code << "\n";
00421             previous = '\n';
00422             ++lineno;
00423         } else if (str.compare(i, 2, "/*", 0, 2) == 0) {
00424             std::size_t commentStart = i + 2;
00425             unsigned char chPrev = 0;
00426             ++i;
00427             while (i < str.length() && (chPrev != '*' || ch != '/')) {
00428                 chPrev = ch;
00429                 ++i;
00430                 ch = static_cast<unsigned char>(str[i]);
00431                 if (ch == '\n') {
00432                     ++newlines;
00433                     ++lineno;
00434                 }
00435             }
00436             std::string comment(str, commentStart, i - commentStart - 1);
00437 
00438             if (isFallThroughComment(comment)) {
00439                 fallThroughComment = true;
00440             }
00441 
00442             if (_settings && _settings->_inlineSuppressions) {
00443                 std::istringstream iss(comment);
00444                 std::string word;
00445                 iss >> word;
00446                 if (word == "cppcheck-suppress") {
00447                     iss >> word;
00448                     if (iss)
00449                         suppressionIDs.push_back(word);
00450                 }
00451             }
00452         } else if ((i==0 || std::isspace(str[i-1])) && str.compare(i,5,"__asm",0,5) == 0) {
00453             while (i < str.size() && !std::isspace(str[i]))
00454                 code << str[i++];
00455             while (i < str.size() && std::isspace(str[i]))
00456                 code << str[i++];
00457             if (str[i] == '{') {
00458                 while (i < str.size() && str[i] != '}') {
00459                     if (str[i] == ';')
00460                         i = str.find("\n", i);
00461                     code << str[i++];
00462                 }
00463                 code << '}';
00464             } else
00465                 --i;
00466         } else if (ch == '#' && previous == '\n') {
00467             code << ch;
00468             previous = ch;
00469             inPreprocessorLine = true;
00470 
00471             // Add any pending inline suppressions that have accumulated.
00472             if (!suppressionIDs.empty()) {
00473                 if (_settings != NULL) {
00474                     // Add the suppressions.
00475                     for (std::size_t j = 0; j < suppressionIDs.size(); ++j) {
00476                         const std::string errmsg(_settings->nomsg.addSuppression(suppressionIDs[j], filename, lineno));
00477                         if (!errmsg.empty()) {
00478                             writeError(filename, lineno, _errorLogger, "cppcheckError", errmsg);
00479                         }
00480                     }
00481                 }
00482                 suppressionIDs.clear();
00483             }
00484         } else {
00485             if (!inPreprocessorLine) {
00486                 // Not whitespace, not a comment, and not preprocessor.
00487                 // Must be code here!
00488 
00489                 // First check for a "fall through" comment match, but only
00490                 // add a suppression if the next token is 'case' or 'default'
00491                 if (_settings && _settings->isEnabled("style") && _settings->experimental && fallThroughComment) {
00492                     std::string::size_type j = str.find_first_not_of("abcdefghijklmnopqrstuvwxyz", i);
00493                     std::string tok = str.substr(i, j - i);
00494                     if (tok == "case" || tok == "default")
00495                         suppressionIDs.push_back("switchCaseFallThrough");
00496                     fallThroughComment = false;
00497                 }
00498 
00499                 // Add any pending inline suppressions that have accumulated.
00500                 if (!suppressionIDs.empty()) {
00501                     if (_settings != NULL) {
00502                         // Add the suppressions.
00503                         for (std::size_t j = 0; j < suppressionIDs.size(); ++j) {
00504                             const std::string errmsg(_settings->nomsg.addSuppression(suppressionIDs[j], filename, lineno));
00505                             if (!errmsg.empty()) {
00506                                 writeError(filename, lineno, _errorLogger, "cppcheckError", errmsg);
00507                             }
00508                         }
00509                     }
00510                     suppressionIDs.clear();
00511                 }
00512             }
00513 
00514             // String or char constants..
00515             if (ch == '\"' || ch == '\'') {
00516                 code << char(ch);
00517                 char chNext;
00518                 do {
00519                     ++i;
00520                     chNext = str[i];
00521                     if (chNext == '\\') {
00522                         ++i;
00523                         char chSeq = str[i];
00524                         if (chSeq == '\n')
00525                             ++newlines;
00526                         else {
00527                             code << chNext;
00528                             code << chSeq;
00529                             previous = static_cast<unsigned char>(chSeq);
00530                         }
00531                     } else {
00532                         code << chNext;
00533                         previous = static_cast<unsigned char>(chNext);
00534                     }
00535                 } while (i < str.length() && chNext != ch && chNext != '\n');
00536             }
00537 
00538             // Rawstring..
00539             else if (str.compare(i,2,"R\"")==0) {
00540                 std::string delim;
00541                 for (std::string::size_type i2 = i+2; i2 < str.length(); ++i2) {
00542                     if (i2 > 16 ||
00543                         std::isspace(str[i2]) ||
00544                         std::iscntrl(str[i2]) ||
00545                         str[i2] == ')' ||
00546                         str[i2] == '\\') {
00547                         delim = " ";
00548                         break;
00549                     } else if (str[i2] == '(')
00550                         break;
00551 
00552                     delim += str[i2];
00553                 }
00554                 const std::string::size_type endpos = str.find(")" + delim + "\"", i);
00555                 if (delim != " " && endpos != std::string::npos) {
00556                     unsigned int rawstringnewlines = 0;
00557                     code << '\"';
00558                     for (std::string::size_type p = i + 3 + delim.size(); p < endpos; ++p) {
00559                         if (str[p] == '\n') {
00560                             rawstringnewlines++;
00561                             code << "\\n";
00562                         } else if (std::iscntrl((unsigned char)str[p]) ||
00563                                    std::isspace((unsigned char)str[p])) {
00564                             code << " ";
00565                         } else if (str[p] == '\"' || str[p] == '\'') {
00566                             code << "\\" << (char)str[p];
00567                         } else {
00568                             code << (char)str[p];
00569                         }
00570                     }
00571                     code << "\"";
00572                     if (rawstringnewlines > 0)
00573                         code << std::string(rawstringnewlines, '\n');
00574                     i = endpos + delim.size() + 1;
00575                 } else {
00576                     code << "R";
00577                     previous = 'R';
00578                 }
00579             } else {
00580                 code << char(ch);
00581                 previous = ch;
00582             }
00583         }
00584     }
00585 
00586     return code.str();
00587 }
00588 
00589 std::string Preprocessor::removeIf0(const std::string &code)
00590 {
00591     std::ostringstream ret;
00592     std::istringstream istr(code);
00593     std::string line;
00594     while (std::getline(istr,line)) {
00595         ret << line << "\n";
00596         if (line == "#if 0") {
00597             // goto the end of the '#if 0' block
00598             unsigned int level = 1;
00599             bool in = false;
00600             while (level > 0 && std::getline(istr,line)) {
00601                 if (line.compare(0,3,"#if") == 0)
00602                     ++level;
00603                 else if (line == "#endif")
00604                     --level;
00605                 else if ((line == "#else") || (line.compare(0, 5, "#elif") == 0)) {
00606                     if (level == 1)
00607                         in = true;
00608                 } else {
00609                     if (in)
00610                         ret << line << "\n";
00611                     else
00612                         // replace code within '#if 0' block with empty lines
00613                         ret << "\n";
00614                     continue;
00615                 }
00616 
00617                 ret << line << "\n";
00618             }
00619         }
00620     }
00621     return ret.str();
00622 }
00623 
00624 
00625 std::string Preprocessor::removeParentheses(const std::string &str)
00626 {
00627     if (str.find("\n#if") == std::string::npos && str.compare(0, 3, "#if") != 0)
00628         return str;
00629 
00630     std::istringstream istr(str);
00631     std::ostringstream ret;
00632     std::string line;
00633     while (std::getline(istr, line)) {
00634         if (line.compare(0, 3, "#if") == 0 || line.compare(0, 5, "#elif") == 0) {
00635             std::string::size_type pos;
00636             pos = 0;
00637             while ((pos = line.find(" (", pos)) != std::string::npos)
00638                 line.erase(pos, 1);
00639             pos = 0;
00640             while ((pos = line.find("( ", pos)) != std::string::npos)
00641                 line.erase(pos + 1, 1);
00642             pos = 0;
00643             while ((pos = line.find(" )", pos)) != std::string::npos)
00644                 line.erase(pos, 1);
00645             pos = 0;
00646             while ((pos = line.find(") ", pos)) != std::string::npos)
00647                 line.erase(pos + 1, 1);
00648 
00649             // Remove inner parentheses "((..))"..
00650             pos = 0;
00651             while ((pos = line.find("((", pos)) != std::string::npos) {
00652                 ++pos;
00653                 std::string::size_type pos2 = line.find_first_of("()", pos + 1);
00654                 if (pos2 != std::string::npos && line[pos2] == ')') {
00655                     line.erase(pos2, 1);
00656                     line.erase(pos, 1);
00657                 }
00658             }
00659 
00660             // "#if(A) => #if A", but avoid "#if (defined A) || defined (B)"
00661             if ((line.compare(0, 4, "#if(") == 0 || line.compare(0, 6, "#elif(") == 0) &&
00662                 line[line.length() - 1] == ')') {
00663                 int ind = 0;
00664                 for (std::string::size_type i = 0; i < line.length(); ++i) {
00665                     if (line[i] == '(')
00666                         ++ind;
00667                     else if (line[i] == ')') {
00668                         --ind;
00669                         if (ind == 0) {
00670                             if (i == line.length() - 1) {
00671                                 line[line.find('(')] = ' ';
00672                                 line.erase(line.length() - 1);
00673                             }
00674                             break;
00675                         }
00676                     }
00677                 }
00678             }
00679 
00680             if (line.compare(0, 4, "#if(") == 0)
00681                 line.insert(3, " ");
00682             else if (line.compare(0, 6, "#elif(") == 0)
00683                 line.insert(5, " ");
00684         }
00685         ret << line << "\n";
00686     }
00687 
00688     return ret.str();
00689 }
00690 
00691 
00692 void Preprocessor::removeAsm(std::string &str)
00693 {
00694     std::string::size_type pos = 0;
00695     while ((pos = str.find("#asm\n", pos)) != std::string::npos) {
00696         str.replace(pos, 4, "asm(");
00697 
00698         std::string::size_type pos2 = str.find("#endasm", pos);
00699         if (pos2 != std::string::npos) {
00700             str.replace(pos2, 7, ");");
00701             pos = pos2;
00702         }
00703     }
00704 }
00705 
00706 
00707 void Preprocessor::preprocess(std::istream &istr, std::map<std::string, std::string> &result, const std::string &filename, const std::list<std::string> &includePaths)
00708 {
00709     std::list<std::string> configs;
00710     std::string data;
00711     preprocess(istr, data, configs, filename, includePaths);
00712     for (std::list<std::string>::const_iterator it = configs.begin(); it != configs.end(); ++it) {
00713         if (_settings && (_settings->userUndefs.find(*it) == _settings->userUndefs.end()))
00714             result[ *it ] = getcode(data, *it, filename);
00715     }
00716 }
00717 
00718 std::string Preprocessor::removeSpaceNearNL(const std::string &str)
00719 {
00720     std::string tmp;
00721     char prev = 0;
00722     for (unsigned int i = 0; i < str.size(); i++) {
00723         if (str[i] == ' ' &&
00724             ((i > 0 && prev == '\n') ||
00725              (i + 1 < str.size() && str[i+1] == '\n')
00726             )
00727            ) {
00728             // Ignore space that has new line in either side of it
00729         } else {
00730             tmp.append(1, str[i]);
00731             prev = str[i];
00732         }
00733     }
00734 
00735     return tmp;
00736 }
00737 
00738 std::string Preprocessor::replaceIfDefined(const std::string &str)
00739 {
00740     std::string ret(str);
00741     std::string::size_type pos;
00742 
00743     pos = 0;
00744     while ((pos = ret.find("#if defined(", pos)) != std::string::npos) {
00745         std::string::size_type pos2 = ret.find(")", pos + 9);
00746         if (pos2 > ret.length() - 1)
00747             break;
00748         if (ret[pos2+1] == '\n') {
00749             ret.erase(pos2, 1);
00750             ret.erase(pos + 3, 9);
00751             ret.insert(pos + 3, "def ");
00752         }
00753         ++pos;
00754     }
00755 
00756     pos = 0;
00757     while ((pos = ret.find("#if !defined(", pos)) != std::string::npos) {
00758         std::string::size_type pos2 = ret.find(")", pos + 9);
00759         if (pos2 > ret.length() - 1)
00760             break;
00761         if (ret[pos2+1] == '\n') {
00762             ret.erase(pos2, 1);
00763             ret.erase(pos + 3, 10);
00764             ret.insert(pos + 3, "ndef ");
00765         }
00766         ++pos;
00767     }
00768 
00769     pos = 0;
00770     while ((pos = ret.find("#elif defined(", pos)) != std::string::npos) {
00771         std::string::size_type pos2 = ret.find(")", pos + 9);
00772         if (pos2 > ret.length() - 1)
00773             break;
00774         if (ret[pos2+1] == '\n') {
00775             ret.erase(pos2, 1);
00776             ret.erase(pos + 6, 8);
00777         }
00778         ++pos;
00779     }
00780 
00781     return ret;
00782 }
00783 
00784 void Preprocessor::preprocessWhitespaces(std::string &processedFile)
00785 {
00786     // Replace all tabs with spaces..
00787     std::replace(processedFile.begin(), processedFile.end(), '\t', ' ');
00788 
00789     // Remove all indentation..
00790     if (!processedFile.empty() && processedFile[0] == ' ')
00791         processedFile.erase(0, processedFile.find_first_not_of(" "));
00792 
00793     // Remove space characters that are after or before new line character
00794     processedFile = removeSpaceNearNL(processedFile);
00795 }
00796 
00797 void Preprocessor::preprocess(std::istream &srcCodeStream, std::string &processedFile, std::list<std::string> &resultConfigurations, const std::string &filename, const std::list<std::string> &includePaths)
00798 {
00799     std::string forcedIncludes;
00800 
00801     if (file0.empty())
00802         file0 = filename;
00803 
00804     processedFile = read(srcCodeStream, filename);
00805 
00806     if (_settings && !_settings->userIncludes.empty()) {
00807         for (std::list<std::string>::iterator it = _settings->userIncludes.begin();
00808              it != _settings->userIncludes.end();
00809              ++it) {
00810             std::string cur = *it;
00811 
00812             // try to open file
00813             std::ifstream fin;
00814 
00815             fin.open(cur.c_str());
00816             if (!fin.is_open()) {
00817                 missingInclude(cur,
00818                                1,
00819                                cur,
00820                                UserHeader
00821                               );
00822                 continue;
00823             }
00824             std::string fileData = read(fin, filename);
00825 
00826             fin.close();
00827 
00828             forcedIncludes =
00829                 forcedIncludes +
00830                 "#file \"" + cur + "\"\n" +
00831                 "#line 1\n" +
00832                 fileData + "\n" +
00833                 "#endfile\n"
00834                 ;
00835         }
00836     }
00837 
00838     if (!forcedIncludes.empty()) {
00839         processedFile =
00840             forcedIncludes +
00841             "#file \"" + filename + "\"\n" +
00842             "#line 1\n" +
00843             processedFile +
00844             "#endfile\n"
00845             ;
00846     }
00847 
00848     // Remove asm(...)
00849     removeAsm(processedFile);
00850 
00851     // Replace "defined A" with "defined(A)"
00852     {
00853         std::istringstream istr(processedFile);
00854         std::ostringstream ostr;
00855         std::string line;
00856         while (std::getline(istr, line)) {
00857             if (line.compare(0, 4, "#if ") == 0 || line.compare(0, 6, "#elif ") == 0) {
00858                 std::string::size_type pos = 0;
00859                 while ((pos = line.find(" defined ")) != std::string::npos) {
00860                     line[pos+8] = '(';
00861                     pos = line.find_first_of(" |&", pos + 8);
00862                     if (pos == std::string::npos)
00863                         line += ")";
00864                     else
00865                         line.insert(pos, ")");
00866                 }
00867             }
00868             ostr << line << "\n";
00869         }
00870         processedFile = ostr.str();
00871     }
00872 
00873     if (_settings && !_settings->userDefines.empty()) {
00874         std::map<std::string, std::string> defs;
00875 
00876         // TODO: break out this code. There is other similar code.
00877         std::string::size_type pos1 = 0;
00878         while (pos1 != std::string::npos) {
00879             const std::string::size_type pos2 = _settings->userDefines.find_first_of(";=", pos1);
00880             const std::string::size_type pos3 = _settings->userDefines.find(";", pos1);
00881 
00882             std::string name, value;
00883             if (pos2 == std::string::npos)
00884                 name = _settings->userDefines.substr(pos1);
00885             else
00886                 name = _settings->userDefines.substr(pos1, pos2 - pos1);
00887             if (pos2 != pos3) {
00888                 if (pos3 == std::string::npos)
00889                     value = _settings->userDefines.substr(pos2+1);
00890                 else
00891                     value = _settings->userDefines.substr(pos2+1, pos3 - pos2 - 1);
00892             }
00893 
00894             defs[name] = value;
00895 
00896             pos1 = pos3;
00897             if (pos1 != std::string::npos)
00898                 pos1++;
00899         }
00900 
00901         processedFile = handleIncludes(processedFile, filename, includePaths, defs);
00902         if (_settings->userIncludes.empty())
00903             resultConfigurations = getcfgs(processedFile, filename);
00904 
00905     } else {
00906 
00907         handleIncludes(processedFile, filename, includePaths);
00908 
00909         processedFile = replaceIfDefined(processedFile);
00910 
00911         // Get all possible configurations..
00912         resultConfigurations = getcfgs(processedFile, filename);
00913 
00914         // Remove configurations that are disabled by -U
00915         handleUndef(resultConfigurations);
00916     }
00917 }
00918 
00919 void Preprocessor::handleUndef(std::list<std::string> &configurations) const
00920 {
00921     if (_settings && !_settings->userUndefs.empty()) {
00922         for (std::list<std::string>::iterator cfg = configurations.begin(); cfg != configurations.end();) {
00923             bool undef = false;
00924             for (std::set<std::string>::const_iterator it = _settings->userUndefs.begin(); it != _settings->userUndefs.end(); ++it) {
00925                 if (*it == *cfg)
00926                     undef = true;
00927                 else if (cfg->compare(0,it->length(),*it)==0 && cfg->find_first_of(";=") == it->length())
00928                     undef = true;
00929                 else if (cfg->find(";" + *it) == std::string::npos)
00930                     ;
00931                 else if (cfg->find(";" + *it + ";") != std::string::npos)
00932                     undef = true;
00933                 else if (cfg->find(";" + *it + "=") != std::string::npos)
00934                     undef = true;
00935                 else if (cfg->find(";" + *it) + it->size() + 1U == cfg->size())
00936                     undef = true;
00937             }
00938 
00939             if (undef)
00940                 configurations.erase(cfg++);
00941             else
00942                 ++cfg;
00943         }
00944     }
00945 }
00946 
00947 // Get the DEF in this line: "#ifdef DEF"
00948 std::string Preprocessor::getdef(std::string line, bool def)
00949 {
00950     if (line.empty() || line[0] != '#')
00951         return "";
00952 
00953     // If def is true, the line must start with "#ifdef"
00954     if (def && line.compare(0, 7, "#ifdef ") != 0 && line.compare(0, 4, "#if ") != 0
00955         && (line.compare(0, 6, "#elif ") != 0 || line.compare(0, 7, "#elif !") == 0)) {
00956         return "";
00957     }
00958 
00959     // If def is false, the line must start with "#ifndef"
00960     if (!def && line.compare(0, 8, "#ifndef ") != 0 && line.compare(0, 7, "#elif !") != 0) {
00961         return "";
00962     }
00963 
00964     // Remove the "#ifdef" or "#ifndef"
00965     if (line.compare(0, 12, "#if defined ") == 0)
00966         line.erase(0, 11);
00967     else if (line.compare(0, 15, "#elif !defined(") == 0) {
00968         line.erase(0, 15);
00969         std::string::size_type pos = line.find(")");
00970         // if pos == ::npos then another part of the code will complain
00971         // about the mismatch
00972         if (pos != std::string::npos)
00973             line.erase(pos, 1);
00974     } else
00975         line.erase(0, line.find(" "));
00976 
00977     // Remove all spaces.
00978     std::string::size_type pos = 0;
00979     while ((pos = line.find(" ", pos)) != std::string::npos) {
00980         const unsigned char chprev(static_cast<unsigned char>((pos > 0) ? line[pos-1] : 0));
00981         const unsigned char chnext(static_cast<unsigned char>((pos + 1 < line.length()) ? line[pos+1] : 0));
00982         if ((std::isalnum(chprev) || chprev == '_') && (std::isalnum(chnext) || chnext == '_'))
00983             ++pos;
00984         else
00985             line.erase(pos, 1);
00986     }
00987 
00988     // The remaining string is our result.
00989     return line;
00990 }
00991 
00992 /** Simplify variable in variable map. */
00993 static Token *simplifyVarMapExpandValue(Token *tok, const std::map<std::string, std::string> &variables, std::set<std::string> seenVariables)
00994 {
00995     // TODO: handle function-macros too.
00996 
00997     // Prevent infinite recursion..
00998     if (seenVariables.find(tok->str()) != seenVariables.end())
00999         return tok;
01000     seenVariables.insert(tok->str());
01001 
01002     const std::map<std::string, std::string>::const_iterator it = variables.find(tok->str());
01003     if (it != variables.end()) {
01004         TokenList tokenList(NULL);
01005         std::istringstream istr(it->second);
01006         if (tokenList.createTokens(istr)) {
01007             // expand token list
01008             for (Token *tok2 = tokenList.front(); tok2; tok2 = tok2->next()) {
01009                 if (tok2->isName()) {
01010                     simplifyVarMapExpandValue(tok2, variables, seenVariables);
01011                 }
01012             }
01013 
01014             // insert token list into "parent" token list
01015             for (const Token *tok2 = tokenList.front(); tok2; tok2 = tok2->next()) {
01016                 if (tok2->previous()) {
01017                     tok->insertToken(tok2->str());
01018                     tok = tok->next();
01019                 } else
01020                     tok->str(tok2->str());
01021             }
01022         }
01023     }
01024 
01025     return tok;
01026 }
01027 
01028 /**
01029  * Simplifies the variable map. For example if the map contains A=>B, B=>1, then A=>B is simplified to A=>1.
01030  * @param [in,out] variables - a map of variable name to variable value. This map will be modified.
01031  */
01032 static void simplifyVarMap(std::map<std::string, std::string> &variables)
01033 {
01034     for (std::map<std::string, std::string>::iterator i = variables.begin(); i != variables.end(); ++i) {
01035         TokenList tokenList(NULL);
01036         std::istringstream istr(i->second);
01037         if (tokenList.createTokens(istr)) {
01038             for (Token *tok = tokenList.front(); tok; tok = tok->next()) {
01039                 if (tok->isName()) {
01040                     std::set<std::string> seenVariables;
01041                     tok = simplifyVarMapExpandValue(tok, variables, seenVariables);
01042                 }
01043             }
01044 
01045             std::string str;
01046             for (const Token *tok = tokenList.front(); tok; tok = tok->next())
01047                 str.append((tok->previous() ? " " : "") + tok->str());
01048             i->second = str;
01049         }
01050     }
01051 }
01052 
01053 std::list<std::string> Preprocessor::getcfgs(const std::string &filedata, const std::string &filename)
01054 {
01055     std::list<std::string> ret;
01056     ret.push_back("");
01057 
01058     std::list<std::string> deflist, ndeflist;
01059 
01060     // constants defined through "#define" in the code..
01061     std::set<std::string> defines;
01062 
01063     // How deep into included files are we currently parsing?
01064     // 0=>Source file, 1=>Included by source file, 2=>included by header that was included by source file, etc
01065     int filelevel = 0;
01066 
01067     bool includeguard = false;
01068 
01069     unsigned int linenr = 0;
01070     std::istringstream istr(filedata);
01071     std::string line;
01072     while (std::getline(istr, line)) {
01073         ++linenr;
01074 
01075         if (_errorLogger)
01076             _errorLogger->reportProgress(filename, "Preprocessing (get configurations 1)", 0);
01077 
01078         if (line.empty())
01079             continue;
01080 
01081         if (line.compare(0, 6, "#file ") == 0) {
01082             includeguard = true;
01083             ++filelevel;
01084             continue;
01085         }
01086 
01087         else if (line == "#endfile") {
01088             includeguard = false;
01089             if (filelevel > 0)
01090                 --filelevel;
01091             continue;
01092         }
01093 
01094         if (line.compare(0, 8, "#define ") == 0) {
01095             bool valid = false;
01096             for (std::string::size_type pos = 8; pos < line.size(); ++pos) {
01097                 char ch = line[pos];
01098                 if (ch=='_' || (ch>='a' && ch<='z') || (ch>='A' && ch<='Z') || (pos>8 && ch>='0' && ch<='9')) {
01099                     valid = true;
01100                     continue;
01101                 }
01102                 if (ch==' ' || ch=='(') {
01103                     if (valid)
01104                         break;
01105                 }
01106                 valid = false;
01107                 break;
01108             }
01109             if (!valid)
01110                 line.clear();
01111             else if (line.find(" ", 8) == std::string::npos)
01112                 defines.insert(line.substr(8));
01113             else {
01114                 std::string s = line.substr(8);
01115                 s[s.find(" ")] = '=';
01116                 defines.insert(s);
01117             }
01118         }
01119 
01120         if (!line.empty() && line.compare(0, 3, "#if") != 0)
01121             includeguard = false;
01122 
01123         if (line.compare(0, 5, "#line") == 0)
01124             continue;
01125 
01126         if (line.empty() || line[0] != '#')
01127             continue;
01128 
01129         if (includeguard)
01130             continue;
01131 
01132         bool from_negation = false;
01133 
01134         std::string def = getdef(line, true);
01135         if (def.empty()) {
01136             def = getdef(line, false);
01137             // sub conditionals of ndef blocks need to be
01138             // constructed _without_ the negated define
01139             if (!def.empty())
01140                 from_negation = true;
01141         }
01142         if (!def.empty()) {
01143             int par = 0;
01144             for (std::string::size_type pos = 0; pos < def.length(); ++pos) {
01145                 if (def[pos] == '(')
01146                     ++par;
01147                 else if (def[pos] == ')') {
01148                     --par;
01149                     if (par < 0)
01150                         break;
01151                 }
01152             }
01153             if (par != 0) {
01154                 std::ostringstream lineStream;
01155                 lineStream << __LINE__;
01156 
01157                 ErrorLogger::ErrorMessage errmsg;
01158                 ErrorLogger::ErrorMessage::FileLocation loc;
01159                 loc.setfile(filename);
01160                 loc.line = linenr;
01161                 errmsg._callStack.push_back(loc);
01162                 errmsg._severity = Severity::fromString("error");
01163                 errmsg.setmsg("mismatching number of '(' and ')' in this line: " + def);
01164                 errmsg._id  = "preprocessor" + lineStream.str();
01165                 _errorLogger->reportErr(errmsg);
01166                 ret.clear();
01167                 return ret;
01168             }
01169 
01170             // Replace defined constants
01171             {
01172                 std::map<std::string, std::string> varmap;
01173                 for (std::set<std::string>::const_iterator it = defines.begin(); it != defines.end(); ++it) {
01174                     std::string::size_type pos = it->find_first_of("=(");
01175                     if (pos == std::string::npos)
01176                         continue;
01177                     if ((*it)[pos] == '(')
01178                         continue;
01179                     const std::string varname(it->substr(0, pos));
01180                     const std::string value(it->substr(pos + 1));
01181                     varmap[varname] = value;
01182                 }
01183                 simplifyCondition(varmap, def, false);
01184             }
01185 
01186             if (! deflist.empty() && line.compare(0, 6, "#elif ") == 0)
01187                 deflist.pop_back();
01188 
01189             // translate A==1 condition to A=1 configuration
01190             if (def.find("==") != std::string::npos) {
01191                 // Check if condition match pattern "%var% == %num%"
01192                 // %var%
01193                 std::string::size_type pos = 0;
01194                 if (std::isalpha(def[pos]) || def[pos] == '_') {
01195                     ++pos;
01196                     while (std::isalnum(def[pos]) || def[pos] == '_')
01197                         ++pos;
01198                 }
01199 
01200                 // ==
01201                 if (def.compare(pos,2,"==",0,2)==0)
01202                     pos += 2;
01203 
01204                 // %num%
01205                 if (pos<def.size() && std::isdigit(def[pos])) {
01206                     if (def.compare(pos,2,"0x",0,2)==0) {
01207                         pos += 2;
01208                         if (pos >= def.size())
01209                             pos = 0;
01210                         while (pos < def.size() && std::isxdigit(def[pos]))
01211                             ++pos;
01212                     } else {
01213                         while (pos < def.size() && std::isdigit(def[pos]))
01214                             ++pos;
01215                     }
01216 
01217                     // Does the condition match the pattern "%var% == %num%"?
01218                     if (pos == def.size()) {
01219                         def.erase(def.find("=="),1);
01220                     }
01221                 }
01222             }
01223 
01224             deflist.push_back(def);
01225             def = "";
01226 
01227             for (std::list<std::string>::const_iterator it = deflist.begin(); it != deflist.end(); ++it) {
01228                 if (*it == "0")
01229                     break;
01230                 if (*it == "1" || *it == "!")
01231                     continue;
01232 
01233                 // don't add "T;T":
01234                 // treat two and more similar nested conditions as one
01235                 if (def != *it) {
01236                     if (! def.empty())
01237                         def += ";";
01238                     def += *it;
01239                 }
01240 
01241                 /* TODO: Fix TestPreprocessor::test7e (#2552)
01242                 else
01243                 {
01244                     std::ostringstream lineStream;
01245                     lineStream << __LINE__;
01246 
01247                     ErrorLogger::ErrorMessage errmsg;
01248                     ErrorLogger::ErrorMessage::FileLocation loc;
01249                     loc.setfile(filename);
01250                     loc.line = linenr;
01251                     errmsg._callStack.push_back(loc);
01252                     errmsg._severity = Severity::error;
01253                     errmsg.setmsg(*it+" is already guaranteed to be defined");
01254                     errmsg._id  = "preprocessor" + lineStream.str();
01255                     _errorLogger->reportErr(errmsg);
01256                 }
01257                 */
01258             }
01259             if (from_negation) {
01260                 ndeflist.push_back(deflist.back());
01261                 deflist.back() = "!";
01262             }
01263 
01264             if (std::find(ret.begin(), ret.end(), def) == ret.end()) {
01265                 ret.push_back(def);
01266             }
01267         }
01268 
01269         else if (line.compare(0, 5, "#else") == 0 && ! deflist.empty()) {
01270             if (deflist.back() == "!") {
01271                 deflist.back() = ndeflist.back();
01272                 ndeflist.pop_back();
01273             } else {
01274                 std::string tempDef((deflist.back() == "1") ? "0" : "1");
01275                 deflist.back() = tempDef;
01276             }
01277         }
01278 
01279         else if (line.compare(0, 6, "#endif") == 0 && ! deflist.empty()) {
01280             if (deflist.back() == "!")
01281                 ndeflist.pop_back();
01282             deflist.pop_back();
01283         }
01284     }
01285 
01286     // Remove defined constants from ifdef configurations..
01287     std::size_t count = 0;
01288     for (std::list<std::string>::iterator it = ret.begin(); it != ret.end(); ++it) {
01289         if (_errorLogger)
01290             _errorLogger->reportProgress(filename, "Preprocessing (get configurations 2)", (100 * count++) / ret.size());
01291 
01292         std::string cfg(*it);
01293         for (std::set<std::string>::const_iterator it2 = defines.begin(); it2 != defines.end(); ++it2) {
01294             std::string::size_type pos = 0;
01295 
01296             // Get name of define
01297             std::string defineName(*it2);
01298             if (defineName.find_first_of("=(") != std::string::npos)
01299                 defineName.erase(defineName.find_first_of("=("));
01300 
01301             // Remove ifdef configurations that match the defineName
01302             while ((pos = cfg.find(defineName, pos)) != std::string::npos) {
01303                 const std::string::size_type pos1 = pos;
01304                 ++pos;
01305                 if (pos1 > 0 && cfg[pos1-1] != ';')
01306                     continue;
01307                 const std::string::size_type pos2 = pos1 + defineName.length();
01308                 if (pos2 < cfg.length() && cfg[pos2] != ';')
01309                     continue;
01310                 --pos;
01311                 cfg.erase(pos, defineName.length());
01312             }
01313         }
01314         if (cfg.length() != it->length()) {
01315             while (cfg.length() > 0 && cfg[0] == ';')
01316                 cfg.erase(0, 1);
01317 
01318             while (cfg.length() > 0 && cfg[cfg.length()-1] == ';')
01319                 cfg.erase(cfg.length() - 1);
01320 
01321             std::string::size_type pos = 0;
01322             while ((pos = cfg.find(";;", pos)) != std::string::npos)
01323                 cfg.erase(pos, 1);
01324 
01325             *it = cfg;
01326         }
01327     }
01328 
01329     // convert configurations: "defined(A) && defined(B)" => "A;B"
01330     for (std::list<std::string>::iterator it = ret.begin(); it != ret.end(); ++it) {
01331         std::string s(*it);
01332 
01333         if (s.find("&&") != std::string::npos) {
01334             Tokenizer tokenizer(_settings, _errorLogger);
01335             if (!tokenizer.tokenizeCondition(s)) {
01336                 std::ostringstream lineStream;
01337                 lineStream << __LINE__;
01338 
01339                 ErrorLogger::ErrorMessage errmsg;
01340                 ErrorLogger::ErrorMessage::FileLocation loc;
01341                 loc.setfile(filename);
01342                 loc.line = 1;
01343                 errmsg._callStack.push_back(loc);
01344                 errmsg._severity = Severity::error;
01345                 errmsg.setmsg("Error parsing this: " + s);
01346                 errmsg._id  = "preprocessor" + lineStream.str();
01347                 _errorLogger->reportErr(errmsg);
01348             }
01349 
01350 
01351             const Token *tok = tokenizer.tokens();
01352             std::set<std::string> varList;
01353             while (tok) {
01354                 if (Token::Match(tok, "defined ( %var% )")) {
01355                     varList.insert(tok->strAt(2));
01356                     tok = tok->tokAt(4);
01357                     if (tok && tok->str() == "&&") {
01358                         tok = tok->next();
01359                     }
01360                 } else if (Token::Match(tok, "%var% ;")) {
01361                     varList.insert(tok->str());
01362                     tok = tok->tokAt(2);
01363                 } else {
01364                     break;
01365                 }
01366             }
01367 
01368             s = join(varList, ';');
01369 
01370             if (!s.empty())
01371                 *it = s;
01372         }
01373     }
01374 
01375     // Convert configurations into a canonical form: B;C;A or C;A;B => A;B;C
01376     for (std::list<std::string>::iterator it = ret.begin(); it != ret.end(); ++it)
01377         *it = unify(*it, ';');
01378 
01379     // Remove duplicates from the ret list..
01380     ret.sort();
01381     ret.unique();
01382 
01383     // cleanup unhandled configurations..
01384     for (std::list<std::string>::iterator it = ret.begin(); it != ret.end();) {
01385         const std::string s(*it + ";");
01386 
01387         bool unhandled = false;
01388 
01389         for (std::string::size_type pos = 0; pos < s.length(); ++pos) {
01390             const unsigned char c = static_cast<unsigned char>(s[pos]);
01391 
01392             // ok with ";"
01393             if (c == ';')
01394                 continue;
01395 
01396             // identifier..
01397             if (std::isalpha(c) || c == '_') {
01398                 while (std::isalnum(s[pos]) || s[pos] == '_')
01399                     ++pos;
01400                 if (s[pos] == '=') {
01401                     ++pos;
01402                     while (std::isdigit(s[pos]))
01403                         ++pos;
01404                     if (s[pos] != ';') {
01405                         unhandled = true;
01406                         break;
01407                     }
01408                 }
01409 
01410                 --pos;
01411                 continue;
01412             }
01413 
01414             // not ok..
01415             else {
01416                 unhandled = true;
01417                 break;
01418             }
01419         }
01420 
01421         if (unhandled) {
01422             // unhandled ifdef configuration..
01423             if (_errorLogger && _settings && _settings->debugwarnings) {
01424                 std::list<ErrorLogger::ErrorMessage::FileLocation> locationList;
01425                 const ErrorLogger::ErrorMessage errmsg(locationList, Severity::debug, "unhandled configuration: " + *it, "debug", false);
01426                 _errorLogger->reportErr(errmsg);
01427             }
01428 
01429             ret.erase(it++);
01430         } else {
01431             ++it;
01432         }
01433     }
01434 
01435     return ret;
01436 }
01437 
01438 
01439 void Preprocessor::simplifyCondition(const std::map<std::string, std::string> &cfg, std::string &condition, bool match)
01440 {
01441     const Settings settings;
01442     Tokenizer tokenizer(&settings, _errorLogger);
01443     if (!tokenizer.tokenizeCondition("(" + condition + ")")) {
01444         // If tokenize returns false, then there is syntax error in the
01445         // code which we can't handle. So stop here.
01446         return;
01447     }
01448 
01449     if (Token::Match(tokenizer.tokens(), "( %var% )")) {
01450         std::map<std::string,std::string>::const_iterator var = cfg.find(tokenizer.tokens()->strAt(1));
01451         if (var != cfg.end()) {
01452             const std::string &value = (*var).second;
01453             condition = (value == "0") ? "0" : "1";
01454         } else if (match)
01455             condition = "0";
01456         return;
01457     }
01458 
01459     if (Token::Match(tokenizer.tokens(), "( ! %var% )")) {
01460         std::map<std::string,std::string>::const_iterator var = cfg.find(tokenizer.tokens()->strAt(2));
01461 
01462         if (var == cfg.end())
01463             condition = "1";
01464         else if (var->second == "0")
01465             condition = "1";
01466         else if (match)
01467             condition = "0";
01468         return;
01469     }
01470 
01471     // replace variable names with values..
01472     for (Token *tok = const_cast<Token *>(tokenizer.tokens()); tok; tok = tok->next()) {
01473         if (!tok->isName())
01474             continue;
01475 
01476         if (Token::Match(tok, "defined ( %var% )")) {
01477             if (cfg.find(tok->strAt(2)) != cfg.end())
01478                 tok->str("1");
01479             else if (match)
01480                 tok->str("0");
01481             else
01482                 continue;
01483             tok->deleteNext(3);
01484             continue;
01485         }
01486 
01487         if (Token::Match(tok, "defined %var%")) {
01488             if (cfg.find(tok->strAt(1)) != cfg.end())
01489                 tok->str("1");
01490             else if (match)
01491                 tok->str("0");
01492             else
01493                 continue;
01494             tok->deleteNext();
01495             continue;
01496         }
01497 
01498         const std::map<std::string, std::string>::const_iterator it = cfg.find(tok->str());
01499         if (it != cfg.end()) {
01500             if (!it->second.empty()) {
01501                 // Tokenize the value
01502                 Tokenizer tokenizer2(&settings,NULL);
01503                 tokenizer2.tokenizeCondition(it->second);
01504 
01505                 // Copy the value tokens
01506                 std::stack<Token *> link;
01507                 for (const Token *tok2 = tokenizer2.tokens(); tok2; tok2 = tok2->next()) {
01508                     tok->str(tok2->str());
01509 
01510                     if (Token::Match(tok2,"[{([]"))
01511                         link.push(tok);
01512                     else if (!link.empty() && Token::Match(tok2,"[})]]")) {
01513                         Token::createMutualLinks(link.top(), tok);
01514                         link.pop();
01515                     }
01516 
01517                     if (tok2->next()) {
01518                         tok->insertToken("");
01519                         tok = tok->next();
01520                     }
01521                 }
01522             } else if ((!tok->previous() || Token::Match(tok->previous(), "&&|%oror%|(")) &&
01523                        (!tok->next() || Token::Match(tok->next(), "&&|%oror%|)")))
01524                 tok->str("1");
01525             else
01526                 tok->deleteThis();
01527         }
01528     }
01529 
01530     // simplify calculations..
01531     tokenizer.concatenateNegativeNumberAndAnyPositive();
01532     bool modified = true;
01533     while (modified) {
01534         modified = false;
01535         modified |= tokenizer.simplifySizeof();
01536         modified |= tokenizer.simplifyCalculations();
01537         modified |= tokenizer.simplifyRedundantParentheses();
01538         for (Token *tok = const_cast<Token *>(tokenizer.tokens()); tok; tok = tok->next()) {
01539             if (Token::Match(tok, "! %num%")) {
01540                 tok->deleteThis();
01541                 tok->str(tok->str() == "0" ? "1" : "0");
01542                 modified = true;
01543             }
01544         }
01545     }
01546 
01547     for (Token *tok = const_cast<Token *>(tokenizer.tokens()); tok; tok = tok->next()) {
01548         if (Token::Match(tok, "(|%oror%|&& %num% &&|%oror%|)")) {
01549             if (tok->next()->str() != "0") {
01550                 tok->next()->str("1");
01551             }
01552         }
01553     }
01554 
01555     for (Token *tok = const_cast<Token *>(tokenizer.tokens()); tok; tok = tok->next()) {
01556         while (Token::Match(tok, "(|%oror% %any% %oror% 1")) {
01557             tok->deleteNext(2);
01558             if (tok->tokAt(-3))
01559                 tok = tok->tokAt(-3);
01560         }
01561     }
01562 
01563     if (Token::simpleMatch(tokenizer.tokens(), "( 1 )") ||
01564         Token::simpleMatch(tokenizer.tokens(), "( 1 ||"))
01565         condition = "1";
01566     else if (Token::simpleMatch(tokenizer.tokens(), "( 0 )"))
01567         condition = "0";
01568 }
01569 
01570 bool Preprocessor::match_cfg_def(std::map<std::string, std::string> cfg, std::string def)
01571 {
01572     /*
01573         std::cout << "cfg: \"";
01574         for (std::map<std::string, std::string>::const_iterator it = cfg.begin(); it != cfg.end(); ++it)
01575         {
01576             std::cout << it->first;
01577             if (!it->second.empty())
01578                 std::cout << "=" << it->second;
01579             std::cout << ";";
01580         }
01581         std::cout << "\"  ";
01582         std::cout << "def: \"" << def << "\"\n";
01583     */
01584 
01585     simplifyVarMap(cfg);
01586     simplifyCondition(cfg, def, true);
01587 
01588     if (cfg.find(def) != cfg.end())
01589         return true;
01590 
01591     if (def == "0")
01592         return false;
01593 
01594     if (def == "1")
01595         return true;
01596 
01597     return false;
01598 }
01599 
01600 
01601 /**
01602  * Get cfgmap - a map of macro names and values
01603  */
01604 static std::map<std::string,std::string> getcfgmap(const std::string &cfg)
01605 {
01606     std::map<std::string, std::string> cfgmap;
01607 
01608     if (!cfg.empty()) {
01609         std::string::size_type pos = 0;
01610         for (;;) {
01611             std::string::size_type pos2 = cfg.find_first_of(";=", pos);
01612             if (pos2 == std::string::npos) {
01613                 cfgmap[cfg.substr(pos)] = "";
01614                 break;
01615             }
01616             if (cfg[pos2] == ';') {
01617                 cfgmap[cfg.substr(pos, pos2-pos)] = "";
01618             } else {
01619                 std::string::size_type pos3 = pos2;
01620                 pos2 = cfg.find(";", pos2);
01621                 if (pos2 == std::string::npos) {
01622                     cfgmap[cfg.substr(pos, pos3-pos)] = cfg.substr(pos3 + 1);
01623                     break;
01624                 } else {
01625                     cfgmap[cfg.substr(pos, pos3-pos)] = cfg.substr(pos3 + 1, pos2 - pos3 - 1);
01626                 }
01627             }
01628             pos = pos2 + 1;
01629         }
01630     }
01631 
01632     return cfgmap;
01633 }
01634 
01635 
01636 std::string Preprocessor::getcode(const std::string &filedata, const std::string &cfg, const std::string &filename, const bool validate)
01637 {
01638     // For the error report
01639     unsigned int lineno = 0;
01640 
01641     std::ostringstream ret;
01642 
01643     bool match = true;
01644     std::list<bool> matching_ifdef;
01645     std::list<bool> matched_ifdef;
01646 
01647     // Create a map for the cfg for faster access to defines
01648     std::map<std::string, std::string> cfgmap(getcfgmap(cfg));
01649     if (((_settings && _settings->enforcedLang == Settings::CPP) || ((!_settings || _settings->enforcedLang == Settings::None) && Path::isCPP(filename))) && cfgmap.find("__cplusplus") == cfgmap.end())
01650         cfgmap["__cplusplus"] = "1";
01651 
01652     std::stack<std::string> filenames;
01653     filenames.push(filename);
01654     std::stack<unsigned int> lineNumbers;
01655     std::istringstream istr(filedata);
01656     std::string line;
01657     while (std::getline(istr, line)) {
01658         ++lineno;
01659 
01660         if (line.compare(0, 11, "#pragma asm") == 0) {
01661             ret << "\n";
01662             bool found_end = false;
01663             while (getline(istr, line)) {
01664                 if (line.compare(0, 14, "#pragma endasm") == 0) {
01665                     found_end = true;
01666                     break;
01667                 }
01668 
01669                 ret << "\n";
01670             }
01671             if (!found_end)
01672                 break;
01673 
01674             if (line.find("=") != std::string::npos) {
01675                 Tokenizer tokenizer(_settings, NULL);
01676                 line.erase(0, sizeof("#pragma endasm"));
01677                 std::istringstream tempIstr(line);
01678                 tokenizer.tokenize(tempIstr, "");
01679                 if (Token::Match(tokenizer.tokens(), "( %var% = %any% )")) {
01680                     ret << "asm(" << tokenizer.tokens()->strAt(1) << ");";
01681                 }
01682             }
01683 
01684             ret << "\n";
01685 
01686             continue;
01687         }
01688 
01689         const std::string def = getdef(line, true);
01690         const std::string ndef = getdef(line, false);
01691 
01692         const bool emptymatch = matching_ifdef.empty() | matched_ifdef.empty();
01693 
01694         if (line.compare(0, 8, "#define ") == 0) {
01695             match = true;
01696 
01697             if (_settings) {
01698                 typedef std::set<std::string>::const_iterator It;
01699                 for (It it = _settings->userUndefs.begin(); it != _settings->userUndefs.end(); ++it) {
01700                     std::string::size_type pos = line.find_first_not_of(' ',8);
01701                     if (pos != std::string::npos) {
01702                         std::string::size_type pos2 = line.find(*it,pos);
01703                         if ((pos2 != std::string::npos) &&
01704                             ((line.size() == pos2 + (*it).size()) ||
01705                              (line[pos2 + (*it).size()] == ' ') ||
01706                              (line[pos2 + (*it).size()] == '('))) {
01707                             match = false;
01708                             break;
01709                         }
01710                     }
01711                 }
01712             }
01713 
01714             for (std::list<bool>::const_iterator it = matching_ifdef.begin(); it != matching_ifdef.end(); ++it)
01715                 match &= bool(*it);
01716 
01717             if (match) {
01718                 std::string::size_type pos = line.find_first_of(" (", 8);
01719                 if (pos == std::string::npos)
01720                     cfgmap[line.substr(8)] = "";
01721                 else if (line[pos] == ' ') {
01722                     std::string value(line.substr(pos + 1));
01723                     if (cfgmap.find(value) != cfgmap.end())
01724                         value = cfgmap[value];
01725                     cfgmap[line.substr(8, pos - 8)] = value;
01726                 } else
01727                     cfgmap[line.substr(8, pos - 8)] = "";
01728             }
01729         }
01730 
01731         else if (line.compare(0, 7, "#undef ") == 0) {
01732             const std::string name(line.substr(7));
01733             cfgmap.erase(name);
01734         }
01735 
01736         else if (!emptymatch && line.compare(0, 7, "#elif !") == 0) {
01737             if (matched_ifdef.back()) {
01738                 matching_ifdef.back() = false;
01739             } else {
01740                 if (!match_cfg_def(cfgmap, ndef)) {
01741                     matching_ifdef.back() = true;
01742                     matched_ifdef.back() = true;
01743                 }
01744             }
01745         }
01746 
01747         else if (!emptymatch && line.compare(0, 6, "#elif ") == 0) {
01748             if (matched_ifdef.back()) {
01749                 matching_ifdef.back() = false;
01750             } else {
01751                 if (match_cfg_def(cfgmap, def)) {
01752                     matching_ifdef.back() = true;
01753                     matched_ifdef.back() = true;
01754                 }
01755             }
01756         }
01757 
01758         else if (! def.empty()) {
01759             matching_ifdef.push_back(match_cfg_def(cfgmap, def));
01760             matched_ifdef.push_back(matching_ifdef.back());
01761         }
01762 
01763         else if (! ndef.empty()) {
01764             matching_ifdef.push_back(! match_cfg_def(cfgmap, ndef));
01765             matched_ifdef.push_back(matching_ifdef.back());
01766         }
01767 
01768         else if (!emptymatch && line == "#else") {
01769             if (! matched_ifdef.empty())
01770                 matching_ifdef.back() = ! matched_ifdef.back();
01771         }
01772 
01773         else if (line.compare(0, 6, "#endif") == 0) {
01774             if (! matched_ifdef.empty())
01775                 matched_ifdef.pop_back();
01776             if (! matching_ifdef.empty())
01777                 matching_ifdef.pop_back();
01778         }
01779 
01780         if (!line.empty() && line[0] == '#') {
01781             match = true;
01782             for (std::list<bool>::const_iterator it = matching_ifdef.begin(); it != matching_ifdef.end(); ++it)
01783                 match &= bool(*it);
01784         }
01785 
01786         // #error => return ""
01787         if (match && line.compare(0, 6, "#error") == 0) {
01788             if (_settings && !_settings->userDefines.empty()) {
01789                 Settings settings2(*_settings);
01790                 Preprocessor preprocessor(&settings2, _errorLogger);
01791                 preprocessor.error(filenames.top(), lineno, line);
01792             }
01793             return "";
01794         }
01795 
01796         if (!match && (line.compare(0, 8, "#define ") == 0 ||
01797                        line.compare(0, 6, "#undef") == 0)) {
01798             // Remove define that is not part of this configuration
01799             line = "";
01800         } else if (line.compare(0, 7, "#file \"") == 0 ||
01801                    line.compare(0, 8, "#endfile") == 0 ||
01802                    line.compare(0, 8, "#define ") == 0 ||
01803                    line.compare(0, 6, "#line ") == 0 ||
01804                    line.compare(0, 6, "#undef") == 0) {
01805             // We must not remove #file tags or line numbers
01806             // are corrupted. File tags are removed by the tokenizer.
01807 
01808             // Keep location info updated
01809             if (line.compare(0, 7, "#file \"") == 0) {
01810                 filenames.push(line.substr(7, line.size() - 8));
01811                 lineNumbers.push(lineno);
01812                 lineno = 0;
01813             } else if (line.compare(0, 8, "#endfile") == 0) {
01814                 if (filenames.size() > 1U)
01815                     filenames.pop();
01816 
01817                 if (!lineNumbers.empty()) {
01818                     lineno = lineNumbers.top();
01819                     lineNumbers.pop();
01820                 }
01821             }
01822         } else if (!match || line.compare(0, 1, "#") == 0) {
01823             // Remove #if, #else, #pragma etc, leaving only
01824             // #define, #undef, #file and #endfile. and also lines
01825             // which are not part of this configuration.
01826             line = "";
01827         }
01828 
01829         ret << line << "\n";
01830     }
01831 
01832     if (validate && !validateCfg(ret.str(), cfg)) {
01833         return "";
01834     }
01835 
01836     return expandMacros(ret.str(), filename, cfg, _errorLogger);
01837 }
01838 
01839 void Preprocessor::error(const std::string &filename, unsigned int linenr, const std::string &msg)
01840 {
01841     std::list<ErrorLogger::ErrorMessage::FileLocation> locationList;
01842     if (!filename.empty()) {
01843         ErrorLogger::ErrorMessage::FileLocation loc;
01844         loc.line = linenr;
01845         loc.setfile(filename);
01846         locationList.push_back(loc);
01847     }
01848     _errorLogger->reportErr(ErrorLogger::ErrorMessage(locationList,
01849                             Severity::error,
01850                             msg,
01851                             "preprocessorErrorDirective",
01852                             false));
01853 }
01854 
01855 Preprocessor::HeaderTypes Preprocessor::getHeaderFileName(std::string &str)
01856 {
01857     std::string result;
01858     std::string::size_type i = str.find_first_of("<\"");
01859     if (i == std::string::npos) {
01860         str = "";
01861         return NoHeader;
01862     }
01863 
01864     char c = str[i];
01865     if (c == '<')
01866         c = '>';
01867 
01868     for (i = i + 1; i < str.length(); ++i) {
01869         if (str[i] == c)
01870             break;
01871 
01872         result.append(1, str[i]);
01873     }
01874 
01875     // Linux can't open include paths with \ separator, so fix them
01876     std::replace(result.begin(), result.end(), '\\', '/');
01877 
01878     str = result;
01879     if (c == '"')
01880         return UserHeader;
01881     else
01882         return SystemHeader;
01883 }
01884 
01885 /**
01886  * Try to open header
01887  * @param filename header name (in/out)
01888  * @param includePaths paths where to look for the file
01889  * @param filePath path to the header file
01890  * @param fin file input stream (in/out)
01891  * @return if file is opened then true is returned
01892  */
01893 static bool openHeader(std::string &filename, const std::list<std::string> &includePaths, const std::string &filePath, std::ifstream &fin)
01894 {
01895     fin.open((filePath + filename).c_str());
01896     if (fin.is_open()) {
01897         filename = filePath + filename;
01898         return true;
01899     }
01900 
01901     std::list<std::string> includePaths2(includePaths);
01902     includePaths2.push_front("");
01903 
01904     for (std::list<std::string>::const_iterator iter = includePaths2.begin(); iter != includePaths2.end(); ++iter) {
01905         const std::string nativePath(Path::toNativeSeparators(*iter));
01906         fin.open((nativePath + filename).c_str());
01907         if (fin.is_open()) {
01908             filename = nativePath + filename;
01909             return true;
01910         }
01911         fin.clear();
01912     }
01913 
01914     return false;
01915 }
01916 
01917 
01918 std::string Preprocessor::handleIncludes(const std::string &code, const std::string &filePath, const std::list<std::string> &includePaths, std::map<std::string,std::string> &defs, std::list<std::string> includes)
01919 {
01920     const std::string path(filePath.substr(0, 1 + filePath.find_last_of("\\/")));
01921 
01922     // current #if indent level.
01923     std::stack<bool>::size_type indent = 0;
01924 
01925     // how deep does the #if match? this can never be bigger than "indent".
01926     std::stack<bool>::size_type indentmatch = 0;
01927 
01928     // has there been a true #if condition at the current indentmatch level?
01929     // then no more #elif or #else can be true before the #endif is seen.
01930     std::stack<bool> elseIsTrueStack;
01931 
01932     unsigned int linenr = 0;
01933 
01934     std::set<std::string> undefs = _settings ? _settings->userUndefs : std::set<std::string>();
01935 
01936     if (_errorLogger)
01937         _errorLogger->reportProgress(filePath, "Preprocessor (handleIncludes)", 0);
01938 
01939     if (_settings && _settings->terminated())
01940         return "";
01941 
01942     std::ostringstream ostr;
01943     std::istringstream istr(code);
01944     std::string line;
01945     bool suppressCurrentCodePath = false;
01946     while (std::getline(istr,line)) {
01947         ++linenr;
01948 
01949         // has there been a true #if condition at the current indentmatch level?
01950         // then no more #elif or #else can be true before the #endif is seen.
01951         while (elseIsTrueStack.size() != indentmatch + 1) {
01952             if (elseIsTrueStack.size() < indentmatch + 1) {
01953                 elseIsTrueStack.push(true);
01954             } else {
01955                 elseIsTrueStack.pop();
01956             }
01957         }
01958 
01959         std::stack<bool>::reference elseIsTrue = elseIsTrueStack.top();
01960 
01961         if (line.compare(0,7,"#ifdef ") == 0) {
01962             if (indent == indentmatch) {
01963                 const std::string tag = getdef(line,true);
01964                 if (defs.find(tag) != defs.end()) {
01965                     elseIsTrue = false;
01966                     indentmatch++;
01967                 } else if (undefs.find(tag) != undefs.end()) {
01968                     elseIsTrue = true;
01969                     indentmatch++;
01970                     suppressCurrentCodePath = true;
01971                 }
01972             }
01973             ++indent;
01974 
01975             if (indent == indentmatch + 1)
01976                 elseIsTrue = true;
01977         } else if (line.compare(0,8,"#ifndef ") == 0) {
01978             if (indent == indentmatch) {
01979                 const std::string tag = getdef(line,false);
01980                 if (defs.find(tag) == defs.end()) {
01981                     elseIsTrue = false;
01982                     indentmatch++;
01983                 } else if (undefs.find(tag) != undefs.end()) {
01984                     elseIsTrue = false;
01985                     indentmatch++;
01986                     suppressCurrentCodePath = false;
01987                 }
01988             }
01989             ++indent;
01990 
01991             if (indent == indentmatch + 1)
01992                 elseIsTrue = true;
01993 
01994         } else if (!suppressCurrentCodePath && line.compare(0,4,"#if ") == 0) {
01995             if (indent == indentmatch && match_cfg_def(defs, line.substr(4))) {
01996                 elseIsTrue = false;
01997                 indentmatch++;
01998             }
01999             ++indent;
02000 
02001             if (indent == indentmatch + 1)
02002                 elseIsTrue = true;
02003         } else if (line.compare(0,6,"#elif ") == 0 || line.compare(0,5,"#else") == 0) {
02004             if (!elseIsTrue) {
02005                 if (indentmatch == indent) {
02006                     indentmatch = indent - 1;
02007                 }
02008             } else {
02009                 if (indentmatch == indent) {
02010                     indentmatch = indent - 1;
02011                 } else if (indentmatch == indent - 1) {
02012                     if (line.compare(0,5,"#else")==0 || match_cfg_def(defs,line.substr(6))) {
02013                         indentmatch = indent;
02014                         elseIsTrue = false;
02015                     }
02016                 }
02017             }
02018             if (suppressCurrentCodePath) {
02019                 suppressCurrentCodePath = false;
02020                 indentmatch = indent;
02021             }
02022         } else if (line.compare(0, 6, "#endif") == 0) {
02023             if (indent > 0)
02024                 --indent;
02025             if (indentmatch > indent || indent == 0) {
02026                 indentmatch = indent;
02027                 elseIsTrue = false;
02028                 suppressCurrentCodePath = false;
02029             }
02030         } else if (indentmatch == indent) {
02031             if (!suppressCurrentCodePath && line.compare(0, 8, "#define ") == 0) {
02032                 const unsigned int endOfDefine = 8;
02033                 std::string::size_type endOfTag = line.find_first_of("( ", endOfDefine);
02034                 std::string tag;
02035 
02036                 // define a symbol
02037                 if (endOfTag == std::string::npos) {
02038                     tag = line.substr(endOfDefine);
02039                     defs[tag] = "";
02040                 } else {
02041                     tag = line.substr(endOfDefine, endOfTag-endOfDefine);
02042 
02043                     // define a function-macro
02044                     if (line[endOfTag] == '(') {
02045                         defs[tag] = "";
02046                     }
02047                     // define value
02048                     else {
02049                         ++endOfTag;
02050 
02051                         const std::string& value = line.substr(endOfTag, line.size()-endOfTag);
02052 
02053                         if (defs.find(value) != defs.end())
02054                             defs[tag] = defs[value];
02055                         else
02056                             defs[tag] = value;
02057                     }
02058                 }
02059 
02060                 if (undefs.find(tag) != undefs.end()) {
02061                     defs.erase(tag);
02062                 }
02063             }
02064 
02065             else if (!suppressCurrentCodePath && line.compare(0,7,"#undef ") == 0) {
02066                 defs.erase(line.substr(7));
02067             }
02068 
02069             else if (!suppressCurrentCodePath && line.compare(0,7,"#error ") == 0) {
02070                 error(filePath, linenr, line.substr(7));
02071             }
02072 
02073             else if (!suppressCurrentCodePath && line.compare(0,9,"#include ")==0) {
02074                 std::string filename(line.substr(9));
02075 
02076                 const HeaderTypes headerType = getHeaderFileName(filename);
02077                 if (headerType == NoHeader) {
02078                     ostr << std::endl;
02079                     continue;
02080                 }
02081 
02082                 // try to open file
02083                 std::string filepath;
02084                 if (headerType == UserHeader)
02085                     filepath = path;
02086                 std::ifstream fin;
02087                 if (!openHeader(filename, includePaths, filepath, fin)) {
02088                     missingInclude(Path::toNativeSeparators(filePath),
02089                                    linenr,
02090                                    filename,
02091                                    headerType
02092                                   );
02093                     ostr << std::endl;
02094                     continue;
02095                 }
02096 
02097                 // Prevent that files are recursively included
02098                 if (std::find(includes.begin(), includes.end(), filename) != includes.end()) {
02099                     ostr << std::endl;
02100                     continue;
02101                 }
02102 
02103                 includes.push_back(filename);
02104 
02105                 ostr << "#file \"" << filename << "\"\n"
02106                      << handleIncludes(read(fin, filename), filename, includePaths, defs, includes) << std::endl
02107                      << "#endfile\n";
02108                 continue;
02109             }
02110 
02111             if (!suppressCurrentCodePath)
02112                 ostr << line;
02113         }
02114 
02115         // A line has been read..
02116         ostr << "\n";
02117     }
02118 
02119     return ostr.str();
02120 }
02121 
02122 
02123 void Preprocessor::handleIncludes(std::string &code, const std::string &filePath, const std::list<std::string> &includePaths)
02124 {
02125     std::list<std::string> paths;
02126     std::string path;
02127     path = filePath;
02128     path.erase(1 + path.find_last_of("\\/"));
02129     paths.push_back(path);
02130     std::string::size_type pos = 0;
02131     std::string::size_type endfilePos = 0;
02132     std::set<std::string> handledFiles;
02133     while ((pos = code.find("#include", pos)) != std::string::npos) {
02134         // Accept only includes that are at the start of a line
02135         if (pos > 0 && code[pos-1] != '\n') {
02136             pos += 8; // length of "#include"
02137             continue;
02138         }
02139 
02140         // If endfile is encountered, we have moved to a next file in our stack,
02141         // so remove last path in our list.
02142         while ((endfilePos = code.find("\n#endfile", endfilePos)) != std::string::npos && endfilePos < pos) {
02143             paths.pop_back();
02144             endfilePos += 9; // size of #endfile
02145         }
02146 
02147         endfilePos = pos;
02148         std::string::size_type end = code.find("\n", pos);
02149         std::string filename = code.substr(pos, end - pos);
02150 
02151         // Remove #include clause
02152         code.erase(pos, end - pos);
02153 
02154         HeaderTypes headerType = getHeaderFileName(filename);
02155         if (headerType == NoHeader)
02156             continue;
02157 
02158         // filename contains now a file name e.g. "menu.h"
02159         std::string processedFile;
02160         std::string filepath;
02161         if (headerType == UserHeader && !paths.empty())
02162             filepath = paths.back();
02163         std::ifstream fin;
02164         const bool fileOpened(openHeader(filename, includePaths, filepath, fin));
02165 
02166         if (fileOpened) {
02167             filename = Path::simplifyPath(filename.c_str());
02168             std::string tempFile = filename;
02169             std::transform(tempFile.begin(), tempFile.end(), tempFile.begin(), tolowerWrapper);
02170             if (handledFiles.find(tempFile) != handledFiles.end()) {
02171                 // We have processed this file already once, skip
02172                 // it this time to avoid eternal loop.
02173                 fin.close();
02174                 continue;
02175             }
02176 
02177             handledFiles.insert(tempFile);
02178             processedFile = Preprocessor::read(fin, filename);
02179             fin.close();
02180         }
02181 
02182         if (!processedFile.empty()) {
02183             // Remove space characters that are after or before new line character
02184             processedFile = "#file \"" + Path::fromNativeSeparators(filename) + "\"\n" + processedFile + "\n#endfile";
02185             code.insert(pos, processedFile);
02186 
02187             path = filename;
02188             path.erase(1 + path.find_last_of("\\/"));
02189             paths.push_back(path);
02190         } else if (!fileOpened && _settings) {
02191             std::string f = filePath;
02192 
02193             // Determine line number of include
02194             unsigned int linenr = 1;
02195             unsigned int level = 0;
02196             for (std::string::size_type p = 1; p <= pos; ++p) {
02197                 if (level == 0 && code[pos-p] == '\n')
02198                     ++linenr;
02199                 else if (code.compare(pos-p, 9, "#endfile\n") == 0) {
02200                     ++level;
02201                 } else if (code.compare(pos-p, 6, "#file ") == 0) {
02202                     if (level == 0) {
02203                         linenr--;
02204                         const std::string::size_type pos1 = pos - p + 7;
02205                         const std::string::size_type pos2 = code.find_first_of("\"\n", pos1);
02206                         f = code.substr(pos1, (pos2 == std::string::npos) ? pos2 : (pos2 - pos1));
02207                         break;
02208                     }
02209                     --level;
02210                 }
02211             }
02212 
02213             missingInclude(Path::toNativeSeparators(f),
02214                            linenr,
02215                            filename,
02216                            headerType);
02217         }
02218     }
02219 }
02220 
02221 // Report that include is missing
02222 void Preprocessor::missingInclude(const std::string &filename, unsigned int linenr, const std::string &header, HeaderTypes headerType)
02223 {
02224     const std::string msgtype = (headerType==SystemHeader)?"missingIncludeSystem":"missingInclude";
02225     if (!_settings->nomsg.isSuppressed(msgtype, Path::fromNativeSeparators(filename), linenr)) {
02226         missingIncludeFlag = true;
02227         if (_errorLogger && _settings->checkConfiguration) {
02228 
02229             std::list<ErrorLogger::ErrorMessage::FileLocation> locationList;
02230             if (!filename.empty()) {
02231                 ErrorLogger::ErrorMessage::FileLocation loc;
02232                 loc.line = linenr;
02233                 loc.setfile(Path::toNativeSeparators(filename));
02234                 locationList.push_back(loc);
02235             }
02236             ErrorLogger::ErrorMessage errmsg(locationList, Severity::information,
02237                                              (headerType==SystemHeader) ? "Include file: <" + header + "> not found." : "Include file: \"" + header + "\" not found.",
02238                                              msgtype, false);
02239             errmsg.file0 = file0;
02240             _errorLogger->reportInfo(errmsg);
02241         }
02242     }
02243 }
02244 
02245 /**
02246  * Skip string in line. A string begins and ends with either a &quot; or a &apos;
02247  * @param line the string
02248  * @param pos in=start position of string, out=end position of string
02249  */
02250 static void skipstring(const std::string &line, std::string::size_type &pos)
02251 {
02252     const char ch = line[pos];
02253 
02254     ++pos;
02255     while (pos < line.size() && line[pos] != ch) {
02256         if (line[pos] == '\\')
02257             ++pos;
02258         ++pos;
02259     }
02260 }
02261 
02262 /**
02263  * @brief get parameters from code. For example 'foo(1,2)' => '1','2'
02264  * @param line in: The code
02265  * @param pos  in: Position to the '('. out: Position to the ')'
02266  * @param params out: The extracted parameters
02267  * @param numberOfNewlines out: number of newlines in the macro call
02268  * @param endFound out: was the end parentheses found?
02269  */
02270 static void getparams(const std::string &line,
02271                       std::string::size_type &pos,
02272                       std::vector<std::string> &params,
02273                       unsigned int &numberOfNewlines,
02274                       bool &endFound)
02275 {
02276     params.clear();
02277     numberOfNewlines = 0;
02278     endFound = false;
02279 
02280     if (line[pos] == ' ')
02281         pos++;
02282 
02283     if (line[pos] != '(')
02284         return;
02285 
02286     // parentheses level
02287     int parlevel = 0;
02288 
02289     // current parameter data
02290     std::string par;
02291 
02292     // scan for parameters..
02293     for (; pos < line.length(); ++pos) {
02294         // increase parentheses level
02295         if (line[pos] == '(') {
02296             ++parlevel;
02297             if (parlevel == 1)
02298                 continue;
02299         }
02300 
02301         // decrease parentheses level
02302         else if (line[pos] == ')') {
02303             --parlevel;
02304             if (parlevel <= 0) {
02305                 endFound = true;
02306                 params.push_back(par);
02307                 break;
02308             }
02309         }
02310 
02311         // string
02312         else if (line[pos] == '\"' || line[pos] == '\'') {
02313             const std::string::size_type p = pos;
02314             skipstring(line, pos);
02315             if (pos == line.length())
02316                 break;
02317             par += line.substr(p, pos + 1 - p);
02318             continue;
02319         }
02320 
02321         // count newlines. the expanded macro must have the same number of newlines
02322         else if (line[pos] == '\n') {
02323             ++numberOfNewlines;
02324             continue;
02325         }
02326 
02327         // new parameter
02328         if (parlevel == 1 && line[pos] == ',') {
02329             params.push_back(par);
02330             par = "";
02331         }
02332 
02333         // spaces are only added if needed
02334         else if (line[pos] == ' ') {
02335             // Add space only if it is needed
02336             if (par.size() && std::isalnum(par[par.length()-1])) {
02337                 par += ' ';
02338             }
02339         }
02340 
02341         // add character to current parameter
02342         else if (parlevel >= 1) {
02343             par.append(1, line[pos]);
02344         }
02345     }
02346 }
02347 
02348 /** @brief Class that the preprocessor uses when it expands macros. This class represents a preprocessor macro */
02349 class PreprocessorMacro {
02350 private:
02351     Settings settings;
02352 
02353     /** tokens of this macro */
02354     Tokenizer tokenizer;
02355 
02356     /** macro parameters */
02357     std::vector<std::string> _params;
02358 
02359     /** name of macro */
02360     std::string _name;
02361 
02362     /** macro definition in plain text */
02363     const std::string _macro;
02364 
02365     /** prefix that is used by cppcheck to separate macro parameters. Always "__cppcheck__" */
02366     const std::string _prefix;
02367 
02368     /** does this macro take a variable number of parameters? */
02369     bool _variadic;
02370 
02371     /** The macro has parentheses but no parameters.. "AAA()" */
02372     bool _nopar;
02373 
02374     /** disabled assignment operator */
02375     void operator=(const PreprocessorMacro &);
02376 
02377     /** @brief expand inner macro */
02378     std::vector<std::string> expandInnerMacros(const std::vector<std::string> &params1,
02379             const std::map<std::string, PreprocessorMacro *> &macros) const {
02380         std::string innerMacroName;
02381 
02382         // Is there an inner macro..
02383         {
02384             const Token *tok = Token::findsimplematch(tokens(), ")");
02385             if (!Token::Match(tok, ") %var% ("))
02386                 return params1;
02387             innerMacroName = tok->strAt(1);
02388             tok = tok->tokAt(3);
02389             unsigned int par = 0;
02390             while (Token::Match(tok, "%var% ,|)")) {
02391                 tok = tok->tokAt(2);
02392                 par++;
02393             }
02394             if (tok || par != params1.size())
02395                 return params1;
02396         }
02397 
02398         std::vector<std::string> params2(params1);
02399 
02400         for (unsigned int ipar = 0; ipar < params1.size(); ++ipar) {
02401             const std::string s(innerMacroName + "(");
02402             std::string param(params1[ipar]);
02403             if (param.compare(0,s.length(),s)==0 && param[param.length()-1]==')') {
02404                 std::vector<std::string> innerparams;
02405                 std::string::size_type pos = s.length() - 1;
02406                 unsigned int num = 0;
02407                 bool endFound = false;
02408                 getparams(param, pos, innerparams, num, endFound);
02409                 if (pos == param.length()-1 && num==0 && endFound && innerparams.size() == params1.size()) {
02410                     // Is inner macro defined?
02411                     std::map<std::string, PreprocessorMacro *>::const_iterator it = macros.find(innerMacroName);
02412                     if (it != macros.end()) {
02413                         // expand the inner macro
02414                         const PreprocessorMacro *innerMacro = it->second;
02415 
02416                         std::string innercode;
02417                         std::map<std::string,PreprocessorMacro *> innermacros = macros;
02418                         innermacros.erase(innerMacroName);
02419                         innerMacro->code(innerparams, innermacros, innercode);
02420                         params2[ipar] = innercode;
02421                     }
02422                 }
02423             }
02424         }
02425 
02426         return params2;
02427     }
02428 
02429 public:
02430     /**
02431      * @brief Constructor for PreprocessorMacro. This is the "setter"
02432      * for this class - everything is setup here.
02433      * @param macro The code after define, until end of line,
02434      * e.g. "A(x) foo(x);"
02435      */
02436     explicit PreprocessorMacro(const std::string &macro)
02437         : _macro(macro), _prefix("__cppcheck__") {
02438         tokenizer.setSettings(&settings);
02439 
02440         // Tokenize the macro to make it easier to handle
02441         std::istringstream istr(macro);
02442         tokenizer.list.createTokens(istr);
02443 
02444         // macro name..
02445         if (tokens() && tokens()->isName())
02446             _name = tokens()->str();
02447 
02448         // initialize parameters to default values
02449         _variadic = _nopar = false;
02450 
02451         std::string::size_type pos = macro.find_first_of(" (");
02452         if (pos != std::string::npos && macro[pos] == '(') {
02453             // Extract macro parameters
02454             if (Token::Match(tokens(), "%var% ( %var%")) {
02455                 for (const Token *tok = tokens()->tokAt(2); tok; tok = tok->next()) {
02456                     if (tok->str() == ")")
02457                         break;
02458                     if (Token::simpleMatch(tok, ". . . )")) {
02459                         if (tok->previous()->str() == ",")
02460                             _params.push_back("__VA_ARGS__");
02461                         _variadic = true;
02462                         break;
02463                     }
02464                     if (tok->isName())
02465                         _params.push_back(tok->str());
02466                 }
02467             }
02468 
02469             else if (Token::Match(tokens(), "%var% ( . . . )"))
02470                 _variadic = true;
02471 
02472             else if (Token::Match(tokens(), "%var% ( )"))
02473                 _nopar = true;
02474         }
02475     }
02476 
02477     /** return tokens of this macro */
02478     const Token *tokens() const {
02479         return tokenizer.tokens();
02480     }
02481 
02482     /** read parameters of this macro */
02483     const std::vector<std::string> &params() const {
02484         return _params;
02485     }
02486 
02487     /** check if this is macro has a variable number of parameters */
02488     bool variadic() const {
02489         return _variadic;
02490     }
02491 
02492     /** Check if this macro has parentheses but no parameters */
02493     bool nopar() const {
02494         return _nopar;
02495     }
02496 
02497     /** name of macro */
02498     const std::string &name() const {
02499         return _name;
02500     }
02501 
02502     /**
02503      * get expanded code for this macro
02504      * @param params2 macro parameters
02505      * @param macros macro definitions (recursion)
02506      * @param macrocode output string
02507      * @return true if the expanding was successful
02508      */
02509     bool code(const std::vector<std::string> &params2, const std::map<std::string, PreprocessorMacro *> &macros, std::string &macrocode) const {
02510         if (_nopar || (_params.empty() && _variadic)) {
02511             macrocode = _macro.substr(1 + _macro.find(")"));
02512             if (macrocode.empty())
02513                 return true;
02514 
02515             std::string::size_type pos = 0;
02516             // Remove leading spaces
02517             if ((pos = macrocode.find_first_not_of(" ")) > 0)
02518                 macrocode.erase(0, pos);
02519             // Remove ending newline
02520             if ((pos = macrocode.find_first_of("\r\n")) != std::string::npos)
02521                 macrocode.erase(pos);
02522 
02523             // Replace "__VA_ARGS__" with parameters
02524             if (!_nopar) {
02525                 std::string s;
02526                 for (unsigned int i = 0; i < params2.size(); ++i) {
02527                     if (i > 0)
02528                         s += ",";
02529                     s += params2[i];
02530                 }
02531 
02532                 pos = 0;
02533                 while ((pos = macrocode.find("__VA_ARGS__", pos)) != std::string::npos) {
02534                     macrocode.erase(pos, 11);
02535                     macrocode.insert(pos, s);
02536                     pos += s.length();
02537                 }
02538             }
02539         }
02540 
02541         else if (_params.empty()) {
02542             std::string::size_type pos = _macro.find_first_of(" \"");
02543             if (pos == std::string::npos)
02544                 macrocode = "";
02545             else {
02546                 if (_macro[pos] == ' ')
02547                     pos++;
02548                 macrocode = _macro.substr(pos);
02549                 if ((pos = macrocode.find_first_of("\r\n")) != std::string::npos)
02550                     macrocode.erase(pos);
02551             }
02552         }
02553 
02554         else {
02555             const std::vector<std::string> givenparams = expandInnerMacros(params2, macros);
02556 
02557             const Token *tok = tokens();
02558             while (tok && tok->str() != ")")
02559                 tok = tok->next();
02560             if (tok) {
02561                 bool optcomma = false;
02562                 while (NULL != (tok = tok->next())) {
02563                     std::string str = tok->str();
02564                     if (str == "##")
02565                         continue;
02566                     if (str[0] == '#' || tok->isName()) {
02567                         const bool stringify(str[0] == '#');
02568                         if (stringify) {
02569                             str = str.erase(0, 1);
02570                         }
02571                         for (unsigned int i = 0; i < _params.size(); ++i) {
02572                             if (str == _params[i]) {
02573                                 if (_variadic &&
02574                                     (i == _params.size() - 1 ||
02575                                      (givenparams.size() + 2 == _params.size() && i + 1 == _params.size() - 1))) {
02576                                     str = "";
02577                                     for (unsigned int j = (unsigned int)_params.size() - 1; j < givenparams.size(); ++j) {
02578                                         if (optcomma || j > _params.size() - 1)
02579                                             str += ",";
02580                                         optcomma = false;
02581                                         str += givenparams[j];
02582                                     }
02583                                 } else if (i >= givenparams.size()) {
02584                                     // Macro had more parameters than caller used.
02585                                     macrocode = "";
02586                                     return false;
02587                                 } else if (stringify) {
02588                                     const std::string &s(givenparams[i]);
02589                                     std::ostringstream ostr;
02590                                     ostr << "\"";
02591                                     for (std::string::size_type j = 0; j < s.size(); ++j) {
02592                                         if (s[j] == '\\' || s[j] == '\"')
02593                                             ostr << '\\';
02594                                         ostr << s[j];
02595                                     }
02596                                     str = ostr.str() + "\"";
02597                                 } else
02598                                     str = givenparams[i];
02599 
02600                                 break;
02601                             }
02602                         }
02603 
02604                         // expand nopar macro
02605                         if (tok->strAt(-1) != "##") {
02606                             const std::map<std::string, PreprocessorMacro *>::const_iterator it = macros.find(str);
02607                             if (it != macros.end() && it->second->_macro.find("(") == std::string::npos) {
02608                                 str = it->second->_macro;
02609                                 if (str.find(" ") != std::string::npos)
02610                                     str.erase(0, str.find(" "));
02611                                 else
02612                                     str = "";
02613                             }
02614                         }
02615                     }
02616                     if (_variadic && tok->str() == "," && tok->next() && tok->next()->str() == "##") {
02617                         optcomma = true;
02618                         continue;
02619                     }
02620                     optcomma = false;
02621                     macrocode += str;
02622                     if (Token::Match(tok, "%var% %var%") ||
02623                         Token::Match(tok, "%var% %num%") ||
02624                         Token::Match(tok, "%num% %var%") ||
02625                         Token::simpleMatch(tok, "> >"))
02626                         macrocode += " ";
02627                 }
02628             }
02629         }
02630 
02631         return true;
02632     }
02633 };
02634 
02635 /**
02636  * Get data from a input string. This is an extended version of std::getline.
02637  * The std::getline only get a single line at a time. It can therefore happen that it
02638  * contains a partial statement. This function ensures that the returned data
02639  * doesn't end in the middle of a statement. The "getlines" name indicate that
02640  * this function will return multiple lines if needed.
02641  * @param istr input stream
02642  * @param line output data
02643  * @return success
02644  */
02645 static bool getlines(std::istream &istr, std::string &line)
02646 {
02647     if (!istr.good())
02648         return false;
02649     line = "";
02650     int parlevel = 0;
02651     for (char ch = (char)istr.get(); istr.good(); ch = (char)istr.get()) {
02652         if (ch == '\'' || ch == '\"') {
02653             line += ch;
02654             char c = 0;
02655             while (istr.good() && c != ch) {
02656                 if (c == '\\') {
02657                     c = (char)istr.get();
02658                     if (!istr.good())
02659                         return true;
02660                     line += c;
02661                 }
02662 
02663                 c = (char)istr.get();
02664                 if (!istr.good())
02665                     return true;
02666                 if (c == '\n' && line.compare(0, 1, "#") == 0)
02667                     return true;
02668                 line += c;
02669             }
02670             continue;
02671         }
02672         if (ch == '(')
02673             ++parlevel;
02674         else if (ch == ')')
02675             --parlevel;
02676         else if (ch == '\n') {
02677             if (line.compare(0, 1, "#") == 0)
02678                 return true;
02679 
02680             if (istr.peek() == '#') {
02681                 line += ch;
02682                 return true;
02683             }
02684         } else if (line.compare(0, 1, "#") != 0 && parlevel <= 0 && ch == ';') {
02685             line += ";";
02686             return true;
02687         }
02688 
02689         line += ch;
02690     }
02691     return true;
02692 }
02693 
02694 bool Preprocessor::validateCfg(const std::string &code, const std::string &cfg)
02695 {
02696     // fill up "macros" with empty configuration macros
02697     std::set<std::string> macros;
02698     for (std::string::size_type pos = 0; pos < cfg.size();) {
02699         const std::string::size_type pos2 = cfg.find_first_of(";=", pos);
02700         if (pos2 == std::string::npos) {
02701             macros.insert(cfg.substr(pos));
02702             break;
02703         }
02704         if (cfg[pos2] == ';')
02705             macros.insert(cfg.substr(pos, pos2-pos));
02706         pos = cfg.find(";", pos2);
02707         if (pos != std::string::npos)
02708             ++pos;
02709     }
02710 
02711     // check if any empty macros are used in code
02712     for (std::set<std::string>::const_iterator it = macros.begin(); it != macros.end(); ++it) {
02713         const std::string &macro = *it;
02714         std::string::size_type pos = 0;
02715         while ((pos = code.find_first_of(std::string("#\"'")+macro[0], pos)) != std::string::npos) {
02716             const std::string::size_type pos1 = pos;
02717             const std::string::size_type pos2 = pos + macro.size();
02718             pos++;
02719 
02720             // skip string..
02721             if (code[pos1] == '\"' || code[pos1] == '\'') {
02722                 while (pos < code.size() && code[pos] != code[pos1]) {
02723                     if (code[pos] == '\\')
02724                         ++pos;
02725                     ++pos;
02726                 }
02727                 ++pos;
02728             }
02729 
02730             // skip preprocessor statement..
02731             else if (code[pos1] == '#') {
02732                 if (pos1 == 0 || code[pos1-1] == '\n')
02733                     pos = code.find("\n",pos);
02734             }
02735 
02736             // is macro used in code?
02737             else if (code.compare(pos1,macro.size(),macro) == 0) {
02738                 if (pos1 > 0 && (std::isalnum(code[pos1-1U]) || code[pos1-1U] == '_'))
02739                     continue;
02740                 if (pos2 < code.size() && (std::isalnum(code[pos2]) || code[pos2] == '_'))
02741                     continue;
02742                 // macro is used in code, return false
02743                 if (_settings->isEnabled("information"))
02744                     validateCfgError(cfg);
02745                 return false;
02746             }
02747         }
02748     }
02749 
02750     return true;
02751 }
02752 
02753 void Preprocessor::validateCfgError(const std::string &cfg)
02754 {
02755     const std::string id = "ConfigurationNotChecked";
02756     std::list<ErrorLogger::ErrorMessage::FileLocation> locationList;
02757     ErrorLogger::ErrorMessage::FileLocation loc;
02758     loc.line = 1;
02759     loc.setfile(file0);
02760     locationList.push_back(loc);
02761     ErrorLogger::ErrorMessage errmsg(locationList, Severity::information, "Skipping configuration '" + cfg + "' because it seems to be invalid. Use -D if you want to check it.", id, false);
02762     _errorLogger->reportInfo(errmsg);
02763 }
02764 
02765 std::string Preprocessor::expandMacros(const std::string &code, std::string filename, const std::string &cfg, ErrorLogger *errorLogger)
02766 {
02767     // Search for macros and expand them..
02768     // --------------------------------------------
02769 
02770     // Available macros (key=macroname, value=macro).
02771     std::map<std::string, PreprocessorMacro *> macros;
02772 
02773     {
02774         // fill up "macros" with user defined macros
02775         const std::map<std::string,std::string> cfgmap(getcfgmap(cfg));
02776         std::map<std::string, std::string>::const_iterator it;
02777         for (it = cfgmap.begin(); it != cfgmap.end(); ++it) {
02778             std::string s = it->first;
02779             if (!it->second.empty())
02780                 s += " " + it->second;
02781             PreprocessorMacro *macro = new PreprocessorMacro(s);
02782             macros[it->first] = macro;
02783         }
02784     }
02785 
02786     // Current line number
02787     unsigned int linenr = 1;
02788 
02789     // linenr, filename
02790     std::stack< std::pair<unsigned int, std::string> > fileinfo;
02791 
02792     // output stream
02793     std::ostringstream ostr;
02794 
02795     // read code..
02796     std::istringstream istr(code);
02797     std::string line;
02798     while (getlines(istr, line)) {
02799         // defining a macro..
02800         if (line.compare(0, 8, "#define ") == 0) {
02801             PreprocessorMacro *macro = new PreprocessorMacro(line.substr(8));
02802             if (macro->name().empty() || macro->name() == "NULL") {
02803                 delete macro;
02804             } else if (macro->name() == "BOOST_FOREACH") {
02805                 // BOOST_FOREACH is currently too complex to parse, so skip it.
02806                 delete macro;
02807             } else {
02808                 std::map<std::string, PreprocessorMacro *>::iterator it;
02809                 it = macros.find(macro->name());
02810                 if (it != macros.end())
02811                     delete it->second;
02812                 macros[macro->name()] = macro;
02813             }
02814             line = "\n";
02815         }
02816 
02817         // undefining a macro..
02818         else if (line.compare(0, 7, "#undef ") == 0) {
02819             std::map<std::string, PreprocessorMacro *>::iterator it;
02820             it = macros.find(line.substr(7));
02821             if (it != macros.end()) {
02822                 delete it->second;
02823                 macros.erase(it);
02824             }
02825             line = "\n";
02826         }
02827 
02828         // entering a file, update position..
02829         else if (line.compare(0, 7, "#file \"") == 0) {
02830             fileinfo.push(std::pair<unsigned int, std::string>(linenr, filename));
02831             filename = line.substr(7, line.length() - 8);
02832             linenr = 0;
02833             line += "\n";
02834         }
02835 
02836         // leaving a file, update position..
02837         else if (line == "#endfile") {
02838             if (!fileinfo.empty()) {
02839                 linenr = fileinfo.top().first;
02840                 filename = fileinfo.top().second;
02841                 fileinfo.pop();
02842             }
02843             line += "\n";
02844         }
02845 
02846         // all other preprocessor directives are just replaced with a newline
02847         else if (line.compare(0, 1, "#") == 0) {
02848             line += "\n";
02849         }
02850 
02851         // expand macros..
02852         else {
02853             // Limit for each macro.
02854             // The limit specify a position in the "line" variable.
02855             // For a "recursive macro" where the expanded text contains
02856             // the macro again, the macro should not be expanded again.
02857             // The limits are used to prevent recursive expanding.
02858             // * When a macro is expanded its limit position is set to
02859             //   the last expanded character.
02860             // * macros are only allowed to be expanded when the
02861             //   the position is beyond the limit.
02862             // * The limit is relative to the end of the "line"
02863             //   variable. Inserting and deleting text before the limit
02864             //   without updating the limit is safe.
02865             // * when pos goes beyond a limit the limit needs to be
02866             //   deleted because it is unsafe to insert/delete text
02867             //   after the limit otherwise
02868             std::map<const PreprocessorMacro *, std::size_t> limits;
02869 
02870             // pos is the current position in line
02871             std::string::size_type pos = 0;
02872 
02873             // scan line to see if there are any macros to expand..
02874             unsigned int tmpLinenr = 0;
02875             while (pos < line.size()) {
02876                 if (line[pos] == '\n')
02877                     ++tmpLinenr;
02878 
02879                 // skip strings..
02880                 if (line[pos] == '\"' || line[pos] == '\'') {
02881                     const char ch = line[pos];
02882 
02883                     skipstring(line, pos);
02884                     ++pos;
02885 
02886                     if (pos >= line.size()) {
02887                         writeError(filename,
02888                                    linenr + tmpLinenr,
02889                                    errorLogger,
02890                                    "noQuoteCharPair",
02891                                    std::string("No pair for character (") + ch + "). Can't process file. File is either invalid or unicode, which is currently not supported.");
02892 
02893                         std::map<std::string, PreprocessorMacro *>::iterator it;
02894                         for (it = macros.begin(); it != macros.end(); ++it)
02895                             delete it->second;
02896                         macros.clear();
02897                         return "";
02898                     }
02899 
02900                     continue;
02901                 }
02902 
02903                 if (!std::isalpha(line[pos]) && line[pos] != '_')
02904                     ++pos;
02905 
02906                 // found an identifier..
02907                 // the "while" is used in case the expanded macro will immediately call another macro
02908                 while (pos < line.length() && (std::isalpha(line[pos]) || line[pos] == '_')) {
02909                     // pos1 = start position of macro
02910                     const std::string::size_type pos1 = pos++;
02911 
02912                     // find the end of the identifier
02913                     while (pos < line.size() && (std::isalnum(line[pos]) || line[pos] == '_'))
02914                         ++pos;
02915 
02916                     // get identifier
02917                     const std::string id = line.substr(pos1, pos - pos1);
02918 
02919                     // is there a macro with this name?
02920                     std::map<std::string, PreprocessorMacro *>::const_iterator it;
02921                     it = macros.find(id);
02922                     if (it == macros.end())
02923                         break;  // no macro with this name exist
02924 
02925                     const PreprocessorMacro * const macro = it->second;
02926 
02927                     // check that pos is within allowed limits for this
02928                     // macro
02929                     {
02930                         const std::map<const PreprocessorMacro *, std::size_t>::const_iterator it2 = limits.find(macro);
02931                         if (it2 != limits.end() && pos <= line.length() - it2->second)
02932                             break;
02933                     }
02934 
02935                     // get parameters from line..
02936                     std::vector<std::string> params;
02937                     std::string::size_type pos2 = pos;
02938                     if (macro->params().size() && pos2 >= line.length())
02939                         break;
02940 
02941                     // number of newlines within macro use
02942                     unsigned int numberOfNewlines = 0;
02943 
02944                     // if the macro has parentheses, get parameters
02945                     if (macro->variadic() || macro->nopar() || macro->params().size()) {
02946                         // is the end parentheses found?
02947                         bool endFound = false;
02948 
02949                         getparams(line,pos2,params,numberOfNewlines,endFound);
02950 
02951 
02952                         // something went wrong so bail out
02953                         if (!endFound)
02954                             break;
02955                     }
02956 
02957                     // Just an empty parameter => clear
02958                     if (params.size() == 1 && params[0] == "")
02959                         params.clear();
02960 
02961                     // Check that it's the same number of parameters..
02962                     if (!macro->variadic() && params.size() != macro->params().size())
02963                         break;
02964 
02965                     // Create macro code..
02966                     std::string tempMacro;
02967                     if (!macro->code(params, macros, tempMacro)) {
02968                         // Syntax error in code
02969                         writeError(filename,
02970                                    linenr + tmpLinenr,
02971                                    errorLogger,
02972                                    "syntaxError",
02973                                    std::string("Syntax error. Not enough parameters for macro '") + macro->name() + "'.");
02974 
02975                         std::map<std::string, PreprocessorMacro *>::iterator iter;
02976                         for (iter = macros.begin(); iter != macros.end(); ++iter)
02977                             delete iter->second;
02978                         macros.clear();
02979                         return "";
02980                     }
02981 
02982                     // make sure number of newlines remain the same..
02983                     std::string macrocode(std::string(numberOfNewlines, '\n') + tempMacro);
02984 
02985                     // Insert macro code..
02986                     if (macro->variadic() || macro->nopar() || !macro->params().empty())
02987                         ++pos2;
02988 
02989                     // Remove old limits
02990                     for (std::map<const PreprocessorMacro *, std::size_t>::iterator iter = limits.begin();
02991                          iter != limits.end();) {
02992                         if ((line.length() - pos1) < iter->second) {
02993                             // We have gone past this limit, so just delete it
02994                             limits.erase(iter++);
02995                         } else {
02996                             ++iter;
02997                         }
02998                     }
02999 
03000                     // don't allow this macro to be expanded again before pos2
03001                     limits[macro] = line.length() - pos2;
03002 
03003                     // erase macro
03004                     line.erase(pos1, pos2 - pos1);
03005 
03006                     // Don't glue this macro into variable or number after it
03007                     if (!line.empty() && (std::isalnum(line[pos1]) || line[pos1] == '_'))
03008                         macrocode.append(1,' ');
03009 
03010                     // insert expanded macro code
03011                     line.insert(pos1, macroChar + macrocode);
03012 
03013                     // position = start position.
03014                     pos = pos1;
03015                 }
03016             }
03017         }
03018 
03019         // the line has been processed in various ways. Now add it to the output stream
03020         ostr << line;
03021 
03022         // update linenr
03023         for (std::string::size_type p = 0; p < line.length(); ++p) {
03024             if (line[p] == '\n')
03025                 ++linenr;
03026         }
03027     }
03028 
03029     for (std::map<std::string, PreprocessorMacro *>::iterator it = macros.begin(); it != macros.end(); ++it)
03030         delete it->second;
03031     macros.clear();
03032 
03033     return ostr.str();
03034 }
03035 
03036 
03037 void Preprocessor::getErrorMessages(ErrorLogger *errorLogger, const Settings *settings)
03038 {
03039     Settings settings2(*settings);
03040     Preprocessor preprocessor(&settings2, errorLogger);
03041     settings2.checkConfiguration=true;
03042     preprocessor.missingInclude("", 1, "", UserHeader);
03043     preprocessor.missingInclude("", 1, "", SystemHeader);
03044     preprocessor.validateCfgError("X");
03045     preprocessor.error("", 1, "#error message");   // #error ..
03046 }