Cppcheck
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
preprocessor.cpp
Go to the documentation of this file.
1 /*
2  * Cppcheck - A tool for static C/C++ code analysis
3  * Copyright (C) 2007-2014 Daniel Marjamäki and Cppcheck team.
4  *
5  * This program is free software: you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation, either version 3 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program. If not, see <http://www.gnu.org/licenses/>.
17  */
18 
19 
20 #include "preprocessor.h"
21 #include "tokenize.h"
22 #include "token.h"
23 #include "path.h"
24 #include "errorlogger.h"
25 #include "settings.h"
26 
27 #include <algorithm>
28 #include <sstream>
29 #include <fstream>
30 #include <cstdlib>
31 #include <cctype>
32 #include <vector>
33 #include <set>
34 #include <stack>
35 
37 
38 char Preprocessor::macroChar = char(1);
39 
40 Preprocessor::Preprocessor(Settings *settings, ErrorLogger *errorLogger) : _settings(settings), _errorLogger(errorLogger)
41 {
42 
43 }
44 
45 void Preprocessor::writeError(const std::string &fileName, const unsigned int linenr, ErrorLogger *errorLogger, const std::string &errorType, const std::string &errorText)
46 {
47  if (!errorLogger)
48  return;
49 
50  std::list<ErrorLogger::ErrorMessage::FileLocation> locationList;
52  loc.line = linenr;
53  loc.setfile(fileName);
54  locationList.push_back(loc);
55  errorLogger->reportErr(ErrorLogger::ErrorMessage(locationList,
57  errorText,
58  errorType,
59  false));
60 }
61 
62 static unsigned char readChar(std::istream &istr, unsigned int bom)
63 {
64  unsigned char ch = (unsigned char)istr.get();
65 
66  // For UTF-16 encoded files the BOM is 0xfeff/0xfffe. If the
67  // character is non-ASCII character then replace it with 0xff
68  if (bom == 0xfeff || bom == 0xfffe) {
69  unsigned char ch2 = (unsigned char)istr.get();
70  int ch16 = (bom == 0xfeff) ? (ch<<8 | ch2) : (ch2<<8 | ch);
71  ch = (unsigned char)((ch16 >= 0x80) ? 0xff : ch16);
72  }
73 
74  // Handling of newlines..
75  if (ch == '\r') {
76  ch = '\n';
77  if (bom == 0 && (char)istr.peek() == '\n')
78  (void)istr.get();
79  else if (bom == 0xfeff || bom == 0xfffe) {
80  int c1 = istr.get();
81  int c2 = istr.get();
82  int ch16 = (bom == 0xfeff) ? (c1<<8 | c2) : (c2<<8 | c1);
83  if (ch16 != '\n') {
84  istr.unget();
85  istr.unget();
86  }
87  }
88  }
89 
90  return ch;
91 }
92 
93 // Concatenates a list of strings, inserting a separator between parts
94 static std::string join(const std::set<std::string>& list, char separator)
95 {
96  std::string s;
97  for (std::set<std::string>::const_iterator it = list.begin(); it != list.end(); ++it) {
98  if (!s.empty())
99  s += separator;
100 
101  s += *it;
102  }
103  return s;
104 }
105 
106 // Removes duplicate string portions separated by the specified separator
107 static std::string unify(const std::string &s, char separator)
108 {
109  std::set<std::string> parts;
110 
111  std::string::size_type prevPos = 0;
112  for (std::string::size_type pos = 0; pos < s.length(); ++pos) {
113  if (s[pos] == separator) {
114  if (pos > prevPos)
115  parts.insert(s.substr(prevPos, pos - prevPos));
116  prevPos = pos + 1;
117  }
118  }
119  if (prevPos < s.length())
120  parts.insert(s.substr(prevPos));
121 
122  return join(parts, separator);
123 }
124 
125 
126 bool Preprocessor::cplusplus(const Settings *settings, const std::string &filename)
127 {
128  const bool undef = settings && settings->userUndefs.find("__cplusplus") != settings->userUndefs.end();
129  const bool cpplang = settings && settings->enforcedLang == Settings::CPP;
130  const bool cppfile = (!settings || settings->enforcedLang == Settings::None) && Path::isCPP(filename);
131  return (!undef && (cpplang || cppfile));
132 }
133 
134 /**
135  * Get cfgmap - a map of macro names and values
136  */
137 static std::map<std::string,std::string> getcfgmap(const std::string &cfg, const Settings *settings, const std::string &filename)
138 {
139  std::map<std::string, std::string> cfgmap;
140 
141  if (!cfg.empty()) {
142  std::string::size_type pos = 0;
143  for (;;) {
144  std::string::size_type pos2 = cfg.find_first_of(";=", pos);
145  if (pos2 == std::string::npos) {
146  cfgmap[cfg.substr(pos)] = "";
147  break;
148  }
149  if (cfg[pos2] == ';') {
150  cfgmap[cfg.substr(pos, pos2-pos)] = "";
151  } else {
152  std::string::size_type pos3 = pos2;
153  pos2 = cfg.find(";", pos2);
154  if (pos2 == std::string::npos) {
155  cfgmap[cfg.substr(pos, pos3-pos)] = cfg.substr(pos3 + 1);
156  break;
157  } else {
158  cfgmap[cfg.substr(pos, pos3-pos)] = cfg.substr(pos3 + 1, pos2 - pos3 - 1);
159  }
160  }
161  pos = pos2 + 1;
162  }
163  }
164 
165  if (cfgmap.find("__cplusplus") == cfgmap.end() && Preprocessor::cplusplus(settings,filename))
166  cfgmap["__cplusplus"] = "1";
167 
168  return cfgmap;
169 }
170 
171 
172 /** Just read the code into a string. Perform simple cleanup of the code */
173 std::string Preprocessor::read(std::istream &istr, const std::string &filename)
174 {
175  // The UTF-16 BOM is 0xfffe or 0xfeff.
176  unsigned int bom = 0;
177  if (istr.peek() >= 0xfe) {
178  bom = ((unsigned int)istr.get() << 8);
179  if (istr.peek() >= 0xfe)
180  bom |= (unsigned int)istr.get();
181  else
182  bom = 0; // allowed boms are 0/0xfffe/0xfeff
183  }
184 
185  if (_settings && _settings->terminated())
186  return "";
187 
189  return readpreprocessor(istr,bom);
190 
191  // ------------------------------------------------------------------------------------------
192  //
193  // handling <backslash><newline>
194  // when this is encountered the <backslash><newline> will be "skipped".
195  // on the next <newline>, extra newlines will be added
196  std::ostringstream code;
197  unsigned int newlines = 0;
198  for (unsigned char ch = readChar(istr,bom); istr.good(); ch = readChar(istr,bom)) {
199  // Replace assorted special chars with spaces..
200  if (((ch & 0x80) == 0) && (ch != '\n') && (std::isspace(ch) || std::iscntrl(ch)))
201  ch = ' ';
202 
203  // <backslash><newline>..
204  // for gcc-compatibility the trailing spaces should be ignored
205  // for vs-compatibility the trailing spaces should be kept
206  // See tickets #640 and #1869
207  // The solution for now is to have a compiler-dependent behaviour.
208  if (ch == '\\') {
209  unsigned char chNext;
210 
211  std::string spaces;
212 
213 #ifdef __GNUC__
214  // gcc-compatibility: ignore spaces
215  for (;; spaces += ' ') {
216  chNext = (unsigned char)istr.peek();
217  if (chNext != '\n' && chNext != '\r' &&
218  (std::isspace(chNext) || std::iscntrl(chNext))) {
219  // Skip whitespace between <backslash> and <newline>
220  (void)readChar(istr,bom);
221  continue;
222  }
223 
224  break;
225  }
226 #else
227  // keep spaces
228  chNext = (unsigned char)istr.peek();
229 #endif
230  if (chNext == '\n' || chNext == '\r') {
231  ++newlines;
232  (void)readChar(istr,bom); // Skip the "<backslash><newline>"
233  } else {
234  code << "\\" << spaces;
235  }
236  } else {
237  code << char(ch);
238 
239  // if there has been <backslash><newline> sequences, add extra newlines..
240  if (ch == '\n' && newlines > 0) {
241  code << std::string(newlines, '\n');
242  newlines = 0;
243  }
244  }
245  }
246  std::string result = code.str();
247  code.str("");
248 
249  // ------------------------------------------------------------------------------------------
250  //
251  // Remove all comments..
252  result = removeComments(result, filename);
253  if (_settings && _settings->terminated())
254  return "";
255 
256  // ------------------------------------------------------------------------------------------
257  //
258  // Clean up all preprocessor statements
259  result = preprocessCleanupDirectives(result);
260  if (_settings && _settings->terminated())
261  return "";
262 
263  // ------------------------------------------------------------------------------------------
264  //
265  // Clean up preprocessor #if statements with Parentheses
266  result = removeParentheses(result);
267  if (_settings && _settings->terminated())
268  return "";
269 
270  // Remove '#if 0' blocks
271  if (result.find("#if 0\n") != std::string::npos)
272  result = removeIf0(result);
273  if (_settings && _settings->terminated())
274  return "";
275 
276  return result;
277 }
278 
279 
280 /** read preprocessor statements */
281 std::string Preprocessor::readpreprocessor(std::istream &istr, const unsigned int bom) const
282 {
283  enum { NEWLINE, SPACE, PREPROCESSOR, BACKSLASH, OTHER } state = NEWLINE;
284  std::ostringstream code;
285  unsigned int newlines = 1;
286  unsigned char chPrev = ' ';
287  for (unsigned char ch = readChar(istr,bom); istr.good(); ch = readChar(istr,bom)) {
288  // Replace assorted special chars with spaces..
289  if (((ch & 0x80) == 0) && (ch != '\n') && (std::isspace(ch) || std::iscntrl(ch)))
290  ch = ' ';
291 
292  if (ch == ' ' && chPrev == ' ')
293  continue;
294  if (state == PREPROCESSOR && chPrev == '/' && (ch == '/' || ch == '*'))
295  state = OTHER;
296  chPrev = ch;
297 
298  if (ch == '\n') {
299  if (state != BACKSLASH) {
300  state = NEWLINE;
301  code << std::string(newlines, '\n');
302  newlines = 1;
303  } else {
304  ++newlines;
305  state = PREPROCESSOR;
306  }
307  continue;
308  }
309 
310  switch (state) {
311  case NEWLINE:
312  if (ch==' ')
313  state = SPACE;
314  else if (ch == '#') {
315  state = PREPROCESSOR;
316  code << ch;
317  } else
318  state = OTHER;
319  break;
320  case SPACE:
321  if (ch == '#') {
322  state = PREPROCESSOR;
323  code << ch;
324  } else if (ch != ' ')
325  state = OTHER;
326  break;
327  case PREPROCESSOR:
328  code << ch;
329  if (ch == '\\')
330  state = BACKSLASH;
331  break;
332  case BACKSLASH:
333  code << ch;
334  if (ch != ' ')
335  state = PREPROCESSOR;
336  break;
337  case OTHER:
338  break;
339  };
340  }
341 
342  std::string result = preprocessCleanupDirectives(code.str());
343  result = removeParentheses(result);
344  return removeIf0(result);
345 }
346 
347 std::string Preprocessor::preprocessCleanupDirectives(const std::string &processedFile)
348 {
349  std::ostringstream code;
350  std::istringstream sstr(processedFile);
351 
352  std::string line;
353  while (std::getline(sstr, line)) {
354  // Trim lines..
355  if (!line.empty() && line[0] == ' ')
356  line.erase(0, line.find_first_not_of(" "));
357  if (!line.empty() && line[line.size()-1] == ' ')
358  line.erase(line.find_last_not_of(" ") + 1);
359 
360  // Preprocessor
361  if (!line.empty() && line[0] == '#') {
362  enum {
363  ESC_NONE,
364  ESC_SINGLE,
365  ESC_DOUBLE
366  } escapeStatus = ESC_NONE;
367 
368  char prev = ' '; // hack to make it skip spaces between # and the directive
369  code << "#";
370  std::string::const_iterator i = line.begin();
371  ++i;
372 
373  // need space.. #if( => #if (
374  bool needSpace = true;
375  while (i != line.end()) {
376  // disable esc-mode
377  if (escapeStatus != ESC_NONE) {
378  if (prev != '\\' && escapeStatus == ESC_SINGLE && *i == '\'') {
379  escapeStatus = ESC_NONE;
380  }
381  if (prev != '\\' && escapeStatus == ESC_DOUBLE && *i == '"') {
382  escapeStatus = ESC_NONE;
383  }
384  } else {
385  // enable esc-mode
386  if (escapeStatus == ESC_NONE && *i == '"')
387  escapeStatus = ESC_DOUBLE;
388  if (escapeStatus == ESC_NONE && *i == '\'')
389  escapeStatus = ESC_SINGLE;
390  }
391  // skip double whitespace between arguments
392  if (escapeStatus == ESC_NONE && prev == ' ' && *i == ' ') {
393  ++i;
394  continue;
395  }
396  // Convert #if( to "#if ("
397  if (escapeStatus == ESC_NONE) {
398  if (needSpace) {
399  if (*i == '(' || *i == '!')
400  code << " ";
401  else if (!std::isalpha((unsigned char)*i))
402  needSpace = false;
403  }
404  if (*i == '#')
405  needSpace = true;
406  }
407  code << *i;
408  if (escapeStatus != ESC_NONE && prev == '\\' && *i == '\\') {
409  prev = ' ';
410  } else {
411  prev = *i;
412  }
413  ++i;
414  }
415  if (escapeStatus != ESC_NONE) {
416  // unmatched quotes.. compiler should probably complain about this..
417  }
418  } else {
419  // Do not mess with regular code..
420  code << line;
421  }
422  code << (sstr.eof()?"":"\n");
423  }
424 
425  return code.str();
426 }
427 
428 static bool hasbom(const std::string &str)
429 {
430  return bool(str.size() >= 3 &&
431  static_cast<unsigned char>(str[0]) == 0xef &&
432  static_cast<unsigned char>(str[1]) == 0xbb &&
433  static_cast<unsigned char>(str[2]) == 0xbf);
434 }
435 
436 
437 // This wrapper exists because Sun's CC does not allow a static_cast
438 // from extern "C" int(*)(int) to int(*)(int).
439 static int tolowerWrapper(int c)
440 {
441  return std::tolower(c);
442 }
443 
444 
445 static bool isFallThroughComment(std::string comment)
446 {
447  // convert comment to lower case without whitespace
448  for (std::string::iterator i = comment.begin(); i != comment.end();) {
449  if (std::isspace(static_cast<unsigned char>(*i)))
450  i = comment.erase(i);
451  else
452  ++i;
453  }
454  std::transform(comment.begin(), comment.end(), comment.begin(), tolowerWrapper);
455 
456  return comment.find("fallthr") != std::string::npos ||
457  comment.find("fallsthr") != std::string::npos ||
458  comment.find("fall-thr") != std::string::npos ||
459  comment.find("dropthr") != std::string::npos ||
460  comment.find("passthr") != std::string::npos ||
461  comment.find("nobreak") != std::string::npos ||
462  comment == "fall";
463 }
464 
465 std::string Preprocessor::removeComments(const std::string &str, const std::string &filename)
466 {
467  // For the error report
468  unsigned int lineno = 1;
469 
470  // handling <backslash><newline>
471  // when this is encountered the <backslash><newline> will be "skipped".
472  // on the next <newline>, extra newlines will be added
473  unsigned int newlines = 0;
474  std::ostringstream code;
475  unsigned char previous = 0;
476  bool inPreprocessorLine = false;
477  std::vector<std::string> suppressionIDs;
478  bool fallThroughComment = false;
479 
480  for (std::string::size_type i = hasbom(str) ? 3U : 0U; i < str.length(); ++i) {
481  unsigned char ch = static_cast<unsigned char>(str[i]);
482  if (ch & 0x80) {
483  std::ostringstream errmsg;
484  errmsg << "The code contains characters that are unhandled. "
485  << "Neither unicode nor extended ASCII are supported. "
486  << "(line=" << lineno << ", character code=" << std::hex << (int(ch) & 0xff) << ")";
487  writeError(filename, lineno, _errorLogger, "syntaxError", errmsg.str());
488  }
489 
490  if (_settings && _settings->terminated())
491  return "";
492 
493  if ((str.compare(i, 7, "#error ") == 0 && (!_settings || _settings->userDefines.empty())) ||
494  str.compare(i, 9, "#warning ") == 0) {
495 
496  if (str.compare(i, 6, "#error") == 0)
497  code << "#error";
498 
499  i = str.find("\n", i);
500  if (i == std::string::npos)
501  break;
502 
503  --i;
504  continue;
505  }
506 
507  // First skip over any whitespace that may be present
508  if (std::isspace(ch)) {
509  if (ch == ' ' && previous == ' ') {
510  // Skip double white space
511  } else {
512  code << char(ch);
513  previous = ch;
514  }
515 
516  // if there has been <backslash><newline> sequences, add extra newlines..
517  if (ch == '\n') {
518  if (previous != '\\')
519  inPreprocessorLine = false;
520  ++lineno;
521  if (newlines > 0) {
522  code << std::string(newlines, '\n');
523  newlines = 0;
524  previous = '\n';
525  }
526  }
527 
528  continue;
529  }
530 
531  // Remove comments..
532  if (str.compare(i, 2, "//") == 0) {
533  std::size_t commentStart = i + 2;
534  i = str.find('\n', i);
535  if (i == std::string::npos)
536  break;
537  std::string comment(str, commentStart, i - commentStart);
538 
540  std::istringstream iss(comment);
541  std::string word;
542  iss >> word;
543  if (word == "cppcheck-suppress") {
544  iss >> word;
545  if (iss)
546  suppressionIDs.push_back(word);
547  }
548  }
549 
550  if (isFallThroughComment(comment)) {
551  fallThroughComment = true;
552  }
553 
554  code << "\n";
555  previous = '\n';
556  ++lineno;
557  } else if (str.compare(i, 2, "/*") == 0) {
558  std::size_t commentStart = i + 2;
559  unsigned char chPrev = 0;
560  ++i;
561  while (i < str.length() && (chPrev != '*' || ch != '/')) {
562  chPrev = ch;
563  ++i;
564  ch = static_cast<unsigned char>(str[i]);
565  if (ch == '\n') {
566  ++newlines;
567  ++lineno;
568  }
569  }
570  std::string comment(str, commentStart, i - commentStart - 1);
571 
572  if (isFallThroughComment(comment)) {
573  fallThroughComment = true;
574  }
575 
577  std::istringstream iss(comment);
578  std::string word;
579  iss >> word;
580  if (word == "cppcheck-suppress") {
581  iss >> word;
582  if (iss)
583  suppressionIDs.push_back(word);
584  }
585  }
586  } else if ((i == 0 || std::isspace((unsigned char)str[i-1])) && str.compare(i, 5, "__asm") == 0) {
587  while (i < str.size() && (std::isalpha((unsigned char)str[i]) || str[i] == '_'))
588  code << str[i++];
589  while (i < str.size() && std::isspace((unsigned char)str[i]))
590  code << str[i++];
591  if (str[i] == '{') {
592  // Ticket 4873: Extract comments from the __asm / __asm__'s content
593  std::string asmBody;
594  while (i < str.size() && str[i] != '}') {
595  if (str[i] == ';') {
596  std::string::size_type backslashN = str.find("\n", i);
597  if (backslashN != std::string::npos) // Ticket #4922: Don't go in infinite loop or crash if there is no '\n'
598  i = backslashN;
599  }
600  asmBody += str[i++];
601  }
602  code << removeComments(asmBody, filename);
603  code << '}';
604  } else
605  --i;
606  } else if (ch == '#' && previous == '\n') {
607  code << ch;
608  previous = ch;
609  inPreprocessorLine = true;
610 
611  // Add any pending inline suppressions that have accumulated.
612  if (!suppressionIDs.empty()) {
613  if (_settings != nullptr) {
614  // Add the suppressions.
615  for (std::size_t j = 0; j < suppressionIDs.size(); ++j) {
616  const std::string errmsg(_settings->nomsg.addSuppression(suppressionIDs[j], filename, lineno));
617  if (!errmsg.empty()) {
618  writeError(filename, lineno, _errorLogger, "cppcheckError", errmsg);
619  }
620  }
621  }
622  suppressionIDs.clear();
623  }
624  } else {
625  if (!inPreprocessorLine) {
626  // Not whitespace, not a comment, and not preprocessor.
627  // Must be code here!
628 
629  // First check for a "fall through" comment match, but only
630  // add a suppression if the next token is 'case' or 'default'
631  if (_settings && _settings->isEnabled("style") && _settings->experimental && fallThroughComment) {
632  std::string::size_type j = str.find_first_not_of("abcdefghijklmnopqrstuvwxyz", i);
633  std::string tok = str.substr(i, j - i);
634  if (tok == "case" || tok == "default")
635  suppressionIDs.push_back("switchCaseFallThrough");
636  fallThroughComment = false;
637  }
638 
639  // Add any pending inline suppressions that have accumulated.
640  if (!suppressionIDs.empty()) {
641  if (_settings != nullptr) {
642  // Relative filename
643  std::string relativeFilename(filename);
644  if (_settings->_relativePaths) {
645  for (std::size_t j = 0U; j < _settings->_basePaths.size(); ++j) {
646  const std::string bp = _settings->_basePaths[j] + "/";
647  if (relativeFilename.compare(0,bp.size(),bp)==0) {
648  relativeFilename = relativeFilename.substr(bp.size());
649  }
650  }
651  }
652 
653  // Add the suppressions.
654  for (std::size_t j = 0; j < suppressionIDs.size(); ++j) {
655  const std::string errmsg(_settings->nomsg.addSuppression(suppressionIDs[j], relativeFilename, lineno));
656  if (!errmsg.empty()) {
657  writeError(filename, lineno, _errorLogger, "cppcheckError", errmsg);
658  }
659  }
660  }
661  suppressionIDs.clear();
662  }
663  }
664 
665  // String or char constants..
666  if (ch == '\"' || ch == '\'') {
667  code << char(ch);
668  char chNext;
669  do {
670  ++i;
671  chNext = str[i];
672  if (chNext == '\\') {
673  ++i;
674  char chSeq = str[i];
675  if (chSeq == '\n')
676  ++newlines;
677  else {
678  code << chNext;
679  code << chSeq;
680  previous = static_cast<unsigned char>(chSeq);
681  }
682  } else {
683  code << chNext;
684  previous = static_cast<unsigned char>(chNext);
685  }
686  } while (i < str.length() && chNext != ch && chNext != '\n');
687  }
688 
689  // Rawstring..
690  else if (str.compare(i,2,"R\"")==0) {
691  std::string delim;
692  for (std::string::size_type i2 = i+2; i2 < str.length(); ++i2) {
693  if (i2 > 16 ||
694  std::isspace(str[i2]) ||
695  std::iscntrl(str[i2]) ||
696  str[i2] == ')' ||
697  str[i2] == '\\') {
698  delim = " ";
699  break;
700  } else if (str[i2] == '(')
701  break;
702 
703  delim += str[i2];
704  }
705  const std::string::size_type endpos = str.find(")" + delim + "\"", i);
706  if (delim != " " && endpos != std::string::npos) {
707  unsigned int rawstringnewlines = 0;
708  code << '\"';
709  for (std::string::size_type p = i + 3 + delim.size(); p < endpos; ++p) {
710  if (str[p] == '\n') {
711  rawstringnewlines++;
712  code << "\\n";
713  } else if (std::iscntrl((unsigned char)str[p]) ||
714  std::isspace((unsigned char)str[p])) {
715  code << " ";
716  } else if (str[p] == '\"' || str[p] == '\'') {
717  code << "\\" << (char)str[p];
718  } else {
719  code << (char)str[p];
720  }
721  }
722  code << "\"";
723  if (rawstringnewlines > 0)
724  code << std::string(rawstringnewlines, '\n');
725  i = endpos + delim.size() + 1;
726  } else {
727  code << "R";
728  previous = 'R';
729  }
730  } else {
731  code << char(ch);
732  previous = ch;
733  }
734  }
735  }
736 
737  return code.str();
738 }
739 
740 std::string Preprocessor::removeIf0(const std::string &code)
741 {
742  std::ostringstream ret;
743  std::istringstream istr(code);
744  std::string line;
745  while (std::getline(istr,line)) {
746  ret << line << "\n";
747  if (line == "#if 0") {
748  // goto the end of the '#if 0' block
749  unsigned int level = 1;
750  bool in = false;
751  while (level > 0 && std::getline(istr,line)) {
752  if (line.compare(0,3,"#if") == 0)
753  ++level;
754  else if (line == "#endif")
755  --level;
756  else if ((line == "#else") || (line.compare(0, 5, "#elif") == 0)) {
757  if (level == 1)
758  in = true;
759  } else {
760  if (in)
761  ret << line << "\n";
762  else
763  // replace code within '#if 0' block with empty lines
764  ret << "\n";
765  continue;
766  }
767 
768  ret << line << "\n";
769  }
770  }
771  }
772  return ret.str();
773 }
774 
775 
776 std::string Preprocessor::removeParentheses(const std::string &str)
777 {
778  if (str.find("\n#if") == std::string::npos && str.compare(0, 3, "#if") != 0)
779  return str;
780 
781  std::istringstream istr(str);
782  std::ostringstream ret;
783  std::string line;
784  while (std::getline(istr, line)) {
785  if (line.compare(0, 3, "#if") == 0 || line.compare(0, 5, "#elif") == 0) {
786  std::string::size_type pos;
787  pos = 0;
788  while ((pos = line.find(" (", pos)) != std::string::npos)
789  line.erase(pos, 1);
790  pos = 0;
791  while ((pos = line.find("( ", pos)) != std::string::npos)
792  line.erase(pos + 1, 1);
793  pos = 0;
794  while ((pos = line.find(" )", pos)) != std::string::npos)
795  line.erase(pos, 1);
796  pos = 0;
797  while ((pos = line.find(") ", pos)) != std::string::npos)
798  line.erase(pos + 1, 1);
799 
800  // Remove inner parentheses "((..))"..
801  pos = 0;
802  while ((pos = line.find("((", pos)) != std::string::npos) {
803  ++pos;
804  std::string::size_type pos2 = line.find_first_of("()", pos + 1);
805  if (pos2 != std::string::npos && line[pos2] == ')') {
806  line.erase(pos2, 1);
807  line.erase(pos, 1);
808  }
809  }
810 
811  // "#if(A) => #if A", but avoid "#if (defined A) || defined (B)"
812  if ((line.compare(0, 4, "#if(") == 0 || line.compare(0, 6, "#elif(") == 0) &&
813  line[line.length() - 1] == ')') {
814  int ind = 0;
815  for (std::string::size_type i = 0; i < line.length(); ++i) {
816  if (line[i] == '(')
817  ++ind;
818  else if (line[i] == ')') {
819  --ind;
820  if (ind == 0) {
821  if (i == line.length() - 1) {
822  line[line.find('(')] = ' ';
823  line.erase(line.length() - 1);
824  }
825  break;
826  }
827  }
828  }
829  }
830 
831  if (line.compare(0, 4, "#if(") == 0)
832  line.insert(3, " ");
833  else if (line.compare(0, 6, "#elif(") == 0)
834  line.insert(5, " ");
835  }
836  ret << line << "\n";
837  }
838 
839  return ret.str();
840 }
841 
842 
843 void Preprocessor::removeAsm(std::string &str)
844 {
845  std::string::size_type pos = 0;
846  while ((pos = str.find("#asm\n", pos)) != std::string::npos) {
847  str.replace(pos, 4, "asm(");
848 
849  std::string::size_type pos2 = str.find("#endasm", pos);
850  if (pos2 != std::string::npos) {
851  str.replace(pos2, 7, ");");
852  pos = pos2;
853  }
854  }
855 }
856 
857 
858 void Preprocessor::preprocess(std::istream &istr, std::map<std::string, std::string> &result, const std::string &filename, const std::list<std::string> &includePaths)
859 {
860  std::list<std::string> configs;
861  std::string data;
862  preprocess(istr, data, configs, filename, includePaths);
863  for (std::list<std::string>::const_iterator it = configs.begin(); it != configs.end(); ++it) {
864  if (_settings && (_settings->userUndefs.find(*it) == _settings->userUndefs.end())) {
865  result[ *it ] = getcode(data, *it, filename);
866  }
867  }
868 }
869 
870 std::string Preprocessor::removeSpaceNearNL(const std::string &str)
871 {
872  std::string tmp;
873  char prev = 0;
874  for (unsigned int i = 0; i < str.size(); i++) {
875  if (str[i] == ' ' &&
876  ((i > 0 && prev == '\n') ||
877  (i + 1 < str.size() && str[i+1] == '\n')
878  )
879  ) {
880  // Ignore space that has new line in either side of it
881  } else {
882  tmp.append(1, str[i]);
883  prev = str[i];
884  }
885  }
886 
887  return tmp;
888 }
889 
890 std::string Preprocessor::replaceIfDefined(const std::string &str) const
891 {
892  std::string ret(str);
893  std::string::size_type pos;
894 
895  pos = 0;
896  while ((pos = ret.find("#if defined(", pos)) != std::string::npos) {
897  std::string::size_type pos2 = ret.find(")", pos + 9);
898  if (pos2 > ret.length() - 1)
899  break;
900  if (ret[pos2+1] == '\n') {
901  ret.erase(pos2, 1);
902  ret.erase(pos + 3, 9);
903  ret.insert(pos + 3, "def ");
904  }
905  ++pos;
906 
907  if (_settings && _settings->terminated())
908  return "";
909  }
910 
911  pos = 0;
912  while ((pos = ret.find("#if !defined(", pos)) != std::string::npos) {
913  std::string::size_type pos2 = ret.find(")", pos + 9);
914  if (pos2 > ret.length() - 1)
915  break;
916  if (ret[pos2+1] == '\n') {
917  ret.erase(pos2, 1);
918  ret.erase(pos + 3, 10);
919  ret.insert(pos + 3, "ndef ");
920  }
921  ++pos;
922 
923  if (_settings && _settings->terminated())
924  return "";
925  }
926 
927  pos = 0;
928  while ((pos = ret.find("#elif defined(", pos)) != std::string::npos) {
929  std::string::size_type pos2 = ret.find(")", pos + 9);
930  if (pos2 > ret.length() - 1)
931  break;
932  if (ret[pos2+1] == '\n') {
933  ret.erase(pos2, 1);
934  ret.erase(pos + 6, 8);
935  }
936  ++pos;
937 
938  if (_settings && _settings->terminated())
939  return "";
940  }
941 
942  return ret;
943 }
944 
945 void Preprocessor::preprocessWhitespaces(std::string &processedFile)
946 {
947  // Replace all tabs with spaces..
948  std::replace(processedFile.begin(), processedFile.end(), '\t', ' ');
949 
950  // Remove all indentation..
951  if (!processedFile.empty() && processedFile[0] == ' ')
952  processedFile.erase(0, processedFile.find_first_not_of(" "));
953 
954  // Remove space characters that are after or before new line character
955  processedFile = removeSpaceNearNL(processedFile);
956 }
957 
958 void Preprocessor::preprocess(std::istream &srcCodeStream, std::string &processedFile, std::list<std::string> &resultConfigurations, const std::string &filename, const std::list<std::string> &includePaths)
959 {
960  std::string forcedIncludes;
961 
962  if (file0.empty())
963  file0 = filename;
964 
965  processedFile = read(srcCodeStream, filename);
966 
967  if (_settings) {
968  for (std::list<std::string>::iterator it = _settings->userIncludes.begin();
969  it != _settings->userIncludes.end();
970  ++it) {
971  std::string cur = *it;
972 
973  // try to open file
974  std::ifstream fin;
975 
976  fin.open(cur.c_str());
977  if (!fin.is_open()) {
978  missingInclude(cur,
979  1,
980  cur,
981  UserHeader
982  );
983  continue;
984  }
985  const std::string fileData = read(fin, filename);
986 
987  fin.close();
988 
989  forcedIncludes =
990  forcedIncludes +
991  "#file \"" + cur + "\"\n" +
992  "#line 1\n" +
993  fileData + "\n" +
994  "#endfile\n"
995  ;
996  }
997 
998  for (std::vector<std::string>::iterator it = _settings->library.defines.begin();
999  it != _settings->library.defines.end();
1000  ++it) {
1001  forcedIncludes += *it;
1002  }
1003  }
1004 
1005  if (!forcedIncludes.empty()) {
1006  processedFile =
1007  forcedIncludes +
1008  "#file \"" + filename + "\"\n" +
1009  "#line 1\n" +
1010  processedFile +
1011  "#endfile\n"
1012  ;
1013  }
1014 
1015  // Remove asm(...)
1016  removeAsm(processedFile);
1017 
1018  // Replace "defined A" with "defined(A)"
1019  {
1020  std::istringstream istr(processedFile);
1021  std::ostringstream ostr;
1022  std::string line;
1023  while (std::getline(istr, line)) {
1024  if (line.compare(0, 4, "#if ") == 0 || line.compare(0, 6, "#elif ") == 0) {
1025  std::string::size_type pos = 0;
1026  while ((pos = line.find(" defined ")) != std::string::npos) {
1027  line[pos+8] = '(';
1028  pos = line.find_first_of(" |&", pos + 8);
1029  if (pos == std::string::npos)
1030  line += ")";
1031  else
1032  line.insert(pos, ")");
1033 
1034  if (_settings && _settings->terminated())
1035  return;
1036  }
1037  }
1038  ostr << line << "\n";
1039  }
1040  processedFile = ostr.str();
1041  }
1042 
1043  std::map<std::string, std::string> defs(getcfgmap(_settings ? _settings->userDefines : std::string(""), _settings, filename));
1044 
1045  if (_settings && _settings->_maxConfigs == 1U) {
1046  std::set<std::string> pragmaOnce;
1047  std::list<std::string> includes;
1048  processedFile = handleIncludes(processedFile, filename, includePaths, defs, pragmaOnce, includes);
1049  resultConfigurations = getcfgs(processedFile, filename, defs);
1050  } else {
1051  handleIncludes(processedFile, filename, includePaths);
1052 
1053  processedFile = replaceIfDefined(processedFile);
1054 
1055  // Get all possible configurations..
1056  resultConfigurations = getcfgs(processedFile, filename, defs);
1057 
1058  // Remove configurations that are disabled by -U
1059  handleUndef(resultConfigurations);
1060  }
1061 }
1062 
1063 void Preprocessor::handleUndef(std::list<std::string> &configurations) const
1064 {
1065  if (_settings && !_settings->userUndefs.empty()) {
1066  for (std::list<std::string>::iterator cfg = configurations.begin(); cfg != configurations.end();) {
1067  bool undef = false;
1068  for (std::set<std::string>::const_iterator it = _settings->userUndefs.begin(); it != _settings->userUndefs.end(); ++it) {
1069  if (*it == *cfg)
1070  undef = true;
1071  else if (cfg->compare(0,it->length(),*it)==0 && cfg->find_first_of(";=") == it->length())
1072  undef = true;
1073  else if (cfg->find(";" + *it) == std::string::npos)
1074  ;
1075  else if (cfg->find(";" + *it + ";") != std::string::npos)
1076  undef = true;
1077  else if (cfg->find(";" + *it + "=") != std::string::npos)
1078  undef = true;
1079  else if (cfg->find(";" + *it) + it->size() + 1U == cfg->size())
1080  undef = true;
1081  }
1082 
1083  if (undef)
1084  configurations.erase(cfg++);
1085  else
1086  ++cfg;
1087  }
1088  }
1089 }
1090 
1091 // Get the DEF in this line: "#ifdef DEF"
1092 std::string Preprocessor::getdef(std::string line, bool def)
1093 {
1094  if (line.empty() || line[0] != '#')
1095  return "";
1096 
1097  // If def is true, the line must start with "#ifdef"
1098  if (def && line.compare(0, 7, "#ifdef ") != 0 && line.compare(0, 4, "#if ") != 0
1099  && (line.compare(0, 6, "#elif ") != 0 || line.compare(0, 7, "#elif !") == 0)) {
1100  return "";
1101  }
1102 
1103  // If def is false, the line must start with "#ifndef"
1104  if (!def && line.compare(0, 8, "#ifndef ") != 0 && line.compare(0, 7, "#elif !") != 0) {
1105  return "";
1106  }
1107 
1108  // Remove the "#ifdef" or "#ifndef"
1109  if (line.compare(0, 12, "#if defined ") == 0)
1110  line.erase(0, 11);
1111  else if (line.compare(0, 15, "#elif !defined(") == 0) {
1112  line.erase(0, 15);
1113  std::string::size_type pos = line.find(")");
1114  // if pos == ::npos then another part of the code will complain
1115  // about the mismatch
1116  if (pos != std::string::npos)
1117  line.erase(pos, 1);
1118  } else
1119  line.erase(0, line.find(" "));
1120 
1121  // Remove all spaces.
1122  std::string::size_type pos = 0;
1123  while ((pos = line.find(" ", pos)) != std::string::npos) {
1124  const unsigned char chprev(static_cast<unsigned char>((pos > 0) ? line[pos-1] : 0));
1125  const unsigned char chnext(static_cast<unsigned char>((pos + 1 < line.length()) ? line[pos+1] : 0));
1126  if ((std::isalnum(chprev) || chprev == '_') && (std::isalnum(chnext) || chnext == '_'))
1127  ++pos;
1128  else
1129  line.erase(pos, 1);
1130  }
1131 
1132  // The remaining string is our result.
1133  return line;
1134 }
1135 
1136 /** Simplify variable in variable map. */
1137 static Token *simplifyVarMapExpandValue(Token *tok, const std::map<std::string, std::string> &variables, std::set<std::string> seenVariables)
1138 {
1139  // TODO: handle function-macros too.
1140 
1141  // Prevent infinite recursion..
1142  if (seenVariables.find(tok->str()) != seenVariables.end())
1143  return tok;
1144  seenVariables.insert(tok->str());
1145 
1146  const std::map<std::string, std::string>::const_iterator it = variables.find(tok->str());
1147  if (it != variables.end()) {
1148  TokenList tokenList(nullptr);
1149  std::istringstream istr(it->second);
1150  if (tokenList.createTokens(istr)) {
1151  // expand token list
1152  for (Token *tok2 = tokenList.front(); tok2; tok2 = tok2->next()) {
1153  if (tok2->isName()) {
1154  tok2 = simplifyVarMapExpandValue(tok2, variables, seenVariables);
1155  }
1156  }
1157 
1158  // insert token list into "parent" token list
1159  for (const Token *tok2 = tokenList.front(); tok2; tok2 = tok2->next()) {
1160  if (tok2->previous()) {
1161  tok->insertToken(tok2->str());
1162  tok = tok->next();
1163  } else
1164  tok->str(tok2->str());
1165  }
1166  }
1167  }
1168 
1169  return tok;
1170 }
1171 
1172 /**
1173  * Simplifies the variable map. For example if the map contains A=>B, B=>1, then A=>B is simplified to A=>1.
1174  * @param [in,out] variables - a map of variable name to variable value. This map will be modified.
1175  */
1176 static void simplifyVarMap(std::map<std::string, std::string> &variables)
1177 {
1178  for (std::map<std::string, std::string>::iterator i = variables.begin(); i != variables.end(); ++i) {
1179  TokenList tokenList(nullptr);
1180  std::istringstream istr(i->second);
1181  if (tokenList.createTokens(istr)) {
1182  for (Token *tok = tokenList.front(); tok; tok = tok->next()) {
1183  if (tok->isName()) {
1184  std::set<std::string> seenVariables;
1185  tok = simplifyVarMapExpandValue(tok, variables, seenVariables);
1186  }
1187  }
1188 
1189  std::string str;
1190  for (const Token *tok = tokenList.front(); tok; tok = tok->next())
1191  str.append((tok->previous() ? " " : "") + tok->str());
1192  i->second = str;
1193  }
1194  }
1195 }
1196 
1197 std::list<std::string> Preprocessor::getcfgs(const std::string &filedata, const std::string &filename, const std::map<std::string, std::string> &defs)
1198 {
1199  std::list<std::string> ret;
1200  ret.push_back("");
1201 
1202  std::list<std::string> deflist, ndeflist;
1203 
1204  // constants defined through "#define" in the code..
1205  std::set<std::string> defines;
1206  std::map<std::string, std::string> alldefinesmap(defs);
1207  std::stack<std::pair<std::string,bool> > includeStack;
1208  includeStack.push(std::pair<std::string,bool>(filename,false));
1209 
1210  // How deep into included files are we currently parsing?
1211  // 0=>Source file, 1=>Included by source file, 2=>included by header that was included by source file, etc
1212  int filelevel = 0;
1213 
1214  bool includeguard = false;
1215  unsigned int linenr = 0;
1216  std::istringstream istr(filedata);
1217  std::string line;
1218  while (std::getline(istr, line)) {
1219  ++linenr;
1220 
1221  if (_settings && _settings->terminated())
1222  return ret;
1223 
1224  if (_errorLogger)
1225  _errorLogger->reportProgress(filename, "Preprocessing (get configurations 1)", 0);
1226 
1227  if (line.empty())
1228  continue;
1229 
1230  if (line.compare(0, 6, "#file ") == 0) {
1231  includeguard = true;
1232  std::string::size_type start=line.find("\"");
1233  std::string::size_type end=line.find("\"",start+1);
1234  std::string includeFile=line.substr(start+1,end-start-1);
1235  bool fileExcluded = false;
1236  ++filelevel;
1237  if (! _settings) {
1238  fileExcluded = false;
1239  } else {
1240  fileExcluded = _settings->configurationExcluded(includeFile);
1241  }
1242  includeStack.push(std::pair<std::string,bool>(includeFile,fileExcluded));
1243  continue;
1244  }
1245 
1246  else if (line == "#endfile") {
1247  includeguard = false;
1248  includeStack.pop();
1249  if (filelevel > 0)
1250  --filelevel;
1251  continue;
1252  }
1253 
1254  if (line.compare(0, 8, "#define ") == 0) {
1255  bool valid = false;
1256  for (std::string::size_type pos = 8; pos < line.size(); ++pos) {
1257  char ch = line[pos];
1258  if (ch=='_' || (ch>='a' && ch<='z') || (ch>='A' && ch<='Z') || (pos>8 && ch>='0' && ch<='9')) {
1259  valid = true;
1260  continue;
1261  }
1262  if (ch==' ' || ch=='(') {
1263  if (valid)
1264  break;
1265  }
1266  valid = false;
1267  break;
1268  }
1269  if (!valid)
1270  line.clear();
1271  else {
1272  std::string definestr = line.substr(8);
1273  const std::string::size_type spacepos = definestr.find(" ");
1274  if (spacepos != std::string::npos)
1275  definestr[spacepos] = '=';
1276  defines.insert(definestr);
1277 
1278  const std::string::size_type separatorpos = definestr.find_first_of("=(");
1279  if (separatorpos != std::string::npos && definestr[separatorpos] == '=') {
1280  const std::string varname(definestr.substr(0, separatorpos));
1281  const std::string value(definestr.substr(separatorpos + 1));
1282  alldefinesmap[varname] = value;
1283  }
1284  }
1285  }
1286 
1287  if (!line.empty() && line.compare(0, 3, "#if") != 0)
1288  includeguard = false;
1289 
1290  if (line.compare(0, 5, "#line") == 0)
1291  continue;
1292 
1293  if (line.empty() || line[0] != '#')
1294  continue;
1295 
1296  if (includeguard)
1297  continue;
1298 
1299  bool from_negation = false;
1300 
1301  std::string def = getdef(line, true);
1302  if (def.empty()) {
1303  def = getdef(line, false);
1304  // sub conditionals of ndef blocks need to be
1305  // constructed _without_ the negated define
1306  if (!def.empty())
1307  from_negation = true;
1308  }
1309  if (!def.empty()) {
1310  int par = 0;
1311  for (std::string::size_type pos = 0; pos < def.length(); ++pos) {
1312  if (def[pos] == '(')
1313  ++par;
1314  else if (def[pos] == ')') {
1315  --par;
1316  if (par < 0)
1317  break;
1318  }
1319  }
1320  if (par != 0) {
1321  std::ostringstream lineStream;
1322  lineStream << __LINE__;
1323 
1326  loc.setfile(filename);
1327  loc.line = linenr;
1328  errmsg._callStack.push_back(loc);
1329  errmsg._severity = Severity::fromString("error");
1330  errmsg.setmsg("mismatching number of '(' and ')' in this line: " + def);
1331  errmsg._id = "preprocessor" + lineStream.str();
1332  _errorLogger->reportErr(errmsg);
1333  ret.clear();
1334  return ret;
1335  }
1336 
1337  // Replace defined constants
1338  simplifyCondition(alldefinesmap, def, false);
1339 
1340  if (! deflist.empty() && line.compare(0, 6, "#elif ") == 0)
1341  deflist.pop_back();
1342 
1343  // translate A==1 condition to A=1 configuration
1344  if (def.find("==") != std::string::npos) {
1345  // Check if condition match pattern "%var% == %num%"
1346  // %var%
1347  std::string::size_type pos = 0;
1348  if (std::isalpha((unsigned char)def[pos]) || def[pos] == '_') {
1349  ++pos;
1350  while (std::isalnum((unsigned char)def[pos]) || def[pos] == '_')
1351  ++pos;
1352  }
1353 
1354  // ==
1355  if (def.compare(pos,2,"==")==0)
1356  pos += 2;
1357 
1358  // %num%
1359  if (pos<def.size() && std::isdigit(def[pos])) {
1360  if (def.compare(pos,2,"0x")==0) {
1361  pos += 2;
1362  if (pos >= def.size())
1363  pos = 0;
1364  while (pos < def.size() && std::isxdigit((unsigned char)def[pos]))
1365  ++pos;
1366  } else {
1367  while (pos < def.size() && std::isdigit((unsigned char)def[pos]))
1368  ++pos;
1369  }
1370 
1371  // Does the condition match the pattern "%var% == %num%"?
1372  if (pos == def.size()) {
1373  def.erase(def.find("=="),1);
1374  }
1375  }
1376  }
1377 
1378  deflist.push_back(def);
1379  def = "";
1380 
1381  for (std::list<std::string>::const_iterator it = deflist.begin(); it != deflist.end(); ++it) {
1382  if (*it == "0")
1383  break;
1384  if (*it == "1" || *it == "!")
1385  continue;
1386 
1387  // don't add "T;T":
1388  // treat two and more similar nested conditions as one
1389  if (def != *it) {
1390  if (! def.empty())
1391  def += ";";
1392  def += *it;
1393  }
1394 
1395  /* TODO: Fix TestPreprocessor::test7e (#2552)
1396  else
1397  {
1398  std::ostringstream lineStream;
1399  lineStream << __LINE__;
1400 
1401  ErrorLogger::ErrorMessage errmsg;
1402  ErrorLogger::ErrorMessage::FileLocation loc;
1403  loc.setfile(filename);
1404  loc.line = linenr;
1405  errmsg._callStack.push_back(loc);
1406  errmsg._severity = Severity::error;
1407  errmsg.setmsg(*it+" is already guaranteed to be defined");
1408  errmsg._id = "preprocessor" + lineStream.str();
1409  _errorLogger->reportErr(errmsg);
1410  }
1411  */
1412  }
1413  if (from_negation) {
1414  ndeflist.push_back(deflist.back());
1415  deflist.back() = "!";
1416  }
1417 
1418  if (std::find(ret.begin(), ret.end(), def) == ret.end()) {
1419  if (!includeStack.top().second) {
1420  ret.push_back(def);
1421  } else {
1423  std::list<ErrorLogger::ErrorMessage::FileLocation> locationList;
1424  const ErrorLogger::ErrorMessage errmsg(locationList, Severity::debug,
1425  "Configuration not considered: " + def +" for file:"+includeStack.top().first, "debug", false);
1426  _errorLogger->reportErr(errmsg);
1427  }
1428  }
1429  }
1430  }
1431 
1432  else if (line.compare(0, 5, "#else") == 0 && ! deflist.empty()) {
1433  if (deflist.back() == "!") {
1434  deflist.back() = ndeflist.back();
1435  ndeflist.pop_back();
1436  } else {
1437  std::string tempDef((deflist.back() == "1") ? "0" : "1");
1438  deflist.back() = tempDef;
1439  }
1440  }
1441 
1442  else if (line.compare(0, 6, "#endif") == 0 && ! deflist.empty()) {
1443  if (deflist.back() == "!")
1444  ndeflist.pop_back();
1445  deflist.pop_back();
1446  }
1447  }
1448 
1449  // Remove defined constants from ifdef configurations..
1450  std::size_t count = 0;
1451  for (std::list<std::string>::iterator it = ret.begin(); it != ret.end(); ++it) {
1452  if (_errorLogger)
1453  _errorLogger->reportProgress(filename, "Preprocessing (get configurations 2)", (100 * count++) / ret.size());
1454 
1455  std::string cfg(*it);
1456  for (std::set<std::string>::const_iterator it2 = defines.begin(); it2 != defines.end(); ++it2) {
1457  std::string::size_type pos = 0;
1458 
1459  // Get name of define
1460  std::string defineName(*it2);
1461  if (defineName.find_first_of("=(") != std::string::npos)
1462  defineName.erase(defineName.find_first_of("=("));
1463 
1464  // Remove ifdef configurations that match the defineName
1465  while ((pos = cfg.find(defineName, pos)) != std::string::npos) {
1466  const std::string::size_type pos1 = pos;
1467  ++pos;
1468  if (pos1 > 0 && cfg[pos1-1] != ';')
1469  continue;
1470  const std::string::size_type pos2 = pos1 + defineName.length();
1471  if (pos2 < cfg.length() && cfg[pos2] != ';')
1472  continue;
1473  --pos;
1474  cfg.erase(pos, defineName.length());
1475  }
1476  }
1477  if (cfg.length() != it->length()) {
1478  while (cfg.length() > 0 && cfg[0] == ';')
1479  cfg.erase(0, 1);
1480 
1481  while (cfg.length() > 0 && cfg[cfg.length()-1] == ';')
1482  cfg.erase(cfg.length() - 1);
1483 
1484  std::string::size_type pos = 0;
1485  while ((pos = cfg.find(";;", pos)) != std::string::npos)
1486  cfg.erase(pos, 1);
1487 
1488  *it = cfg;
1489  }
1490  }
1491 
1492  // convert configurations: "defined(A) && defined(B)" => "A;B"
1493  for (std::list<std::string>::iterator it = ret.begin(); it != ret.end(); ++it) {
1494  std::string s(*it);
1495 
1496  if (s.find("&&") != std::string::npos) {
1497  Tokenizer tokenizer(_settings, _errorLogger);
1498  if (!tokenizer.tokenizeCondition(s)) {
1499  std::ostringstream lineStream;
1500  lineStream << __LINE__;
1501 
1504  loc.setfile(filename);
1505  loc.line = 1;
1506  errmsg._callStack.push_back(loc);
1507  errmsg._severity = Severity::error;
1508  errmsg.setmsg("Error parsing this: " + s);
1509  errmsg._id = "preprocessor" + lineStream.str();
1510  _errorLogger->reportErr(errmsg);
1511  }
1512 
1513 
1514  const Token *tok = tokenizer.tokens();
1515  std::set<std::string> varList;
1516  while (tok) {
1517  if (Token::Match(tok, "defined ( %var% )")) {
1518  varList.insert(tok->strAt(2));
1519  tok = tok->tokAt(4);
1520  if (tok && tok->str() == "&&") {
1521  tok = tok->next();
1522  }
1523  } else if (Token::Match(tok, "%var% ;")) {
1524  varList.insert(tok->str());
1525  tok = tok->tokAt(2);
1526  } else {
1527  break;
1528  }
1529  }
1530 
1531  s = join(varList, ';');
1532 
1533  if (!s.empty())
1534  *it = s;
1535  }
1536  }
1537 
1538  // Convert configurations into a canonical form: B;C;A or C;A;B => A;B;C
1539  for (std::list<std::string>::iterator it = ret.begin(); it != ret.end(); ++it)
1540  *it = unify(*it, ';');
1541 
1542  // Remove duplicates from the ret list..
1543  ret.sort();
1544  ret.unique();
1545 
1546  // cleanup unhandled configurations..
1547  for (std::list<std::string>::iterator it = ret.begin(); it != ret.end();) {
1548  const std::string s(*it + ";");
1549 
1550  bool unhandled = false;
1551 
1552  for (std::string::size_type pos = 0; pos < s.length(); ++pos) {
1553  const unsigned char c = static_cast<unsigned char>(s[pos]);
1554 
1555  // ok with ";"
1556  if (c == ';')
1557  continue;
1558 
1559  // identifier..
1560  if (std::isalpha(c) || c == '_') {
1561  while (std::isalnum((unsigned char)s[pos]) || s[pos] == '_')
1562  ++pos;
1563  if (s[pos] == '=') {
1564  ++pos;
1565  while (std::isdigit((unsigned char)s[pos]))
1566  ++pos;
1567  if (s[pos] != ';') {
1568  unhandled = true;
1569  break;
1570  }
1571  }
1572 
1573  --pos;
1574  continue;
1575  }
1576 
1577  // not ok..
1578  else {
1579  unhandled = true;
1580  break;
1581  }
1582  }
1583 
1584  if (unhandled) {
1585  // unhandled ifdef configuration..
1587  std::list<ErrorLogger::ErrorMessage::FileLocation> locationList;
1588  const ErrorLogger::ErrorMessage errmsg(locationList, Severity::debug, "unhandled configuration: " + *it, "debug", false);
1589  _errorLogger->reportErr(errmsg);
1590  }
1591 
1592  ret.erase(it++);
1593  } else {
1594  ++it;
1595  }
1596  }
1597 
1598  return ret;
1599 }
1600 
1601 
1602 void Preprocessor::simplifyCondition(const std::map<std::string, std::string> &cfg, std::string &condition, bool match)
1603 {
1604  const Settings settings;
1605  Tokenizer tokenizer(&settings, _errorLogger);
1606  if (!tokenizer.tokenizeCondition("(" + condition + ")")) {
1607  // If tokenize returns false, then there is syntax error in the
1608  // code which we can't handle. So stop here.
1609  return;
1610  }
1611 
1612  if (Token::Match(tokenizer.tokens(), "( %var% )")) {
1613  std::map<std::string,std::string>::const_iterator var = cfg.find(tokenizer.tokens()->strAt(1));
1614  if (var != cfg.end()) {
1615  const std::string &value = (*var).second;
1616  condition = (value == "0") ? "0" : "1";
1617  } else if (match)
1618  condition = "0";
1619  return;
1620  }
1621 
1622  if (Token::Match(tokenizer.tokens(), "( ! %var% )")) {
1623  std::map<std::string,std::string>::const_iterator var = cfg.find(tokenizer.tokens()->strAt(2));
1624 
1625  if (var == cfg.end())
1626  condition = "1";
1627  else if (var->second == "0")
1628  condition = "1";
1629  else if (match)
1630  condition = "0";
1631  return;
1632  }
1633 
1634  // replace variable names with values..
1635  for (Token *tok = const_cast<Token *>(tokenizer.tokens()); tok; tok = tok->next()) {
1636  if (!tok->isName())
1637  continue;
1638 
1639  if (Token::Match(tok, "defined ( %var% )")) {
1640  if (cfg.find(tok->strAt(2)) != cfg.end())
1641  tok->str("1");
1642  else if (match)
1643  tok->str("0");
1644  else
1645  continue;
1646  tok->deleteNext(3);
1647  continue;
1648  }
1649 
1650  if (Token::Match(tok, "defined %var%")) {
1651  if (cfg.find(tok->strAt(1)) != cfg.end())
1652  tok->str("1");
1653  else if (match)
1654  tok->str("0");
1655  else
1656  continue;
1657  tok->deleteNext();
1658  continue;
1659  }
1660 
1661  const std::map<std::string, std::string>::const_iterator it = cfg.find(tok->str());
1662  if (it != cfg.end()) {
1663  if (!it->second.empty()) {
1664  // Tokenize the value
1665  Tokenizer tokenizer2(&settings, _errorLogger);
1666  tokenizer2.tokenizeCondition(it->second);
1667 
1668  // Copy the value tokens
1669  std::stack<Token *> link;
1670  for (const Token *tok2 = tokenizer2.tokens(); tok2; tok2 = tok2->next()) {
1671  tok->str(tok2->str());
1672 
1673  if (Token::Match(tok2,"[{([]"))
1674  link.push(tok);
1675  else if (!link.empty() && Token::Match(tok2,"[})]]")) {
1676  Token::createMutualLinks(link.top(), tok);
1677  link.pop();
1678  }
1679 
1680  if (tok2->next()) {
1681  tok->insertToken("");
1682  tok = tok->next();
1683  }
1684  }
1685  } else if ((!tok->previous() || Token::Match(tok->previous(), "&&|%oror%|(")) &&
1686  (!tok->next() || Token::Match(tok->next(), "&&|%oror%|)")))
1687  tok->str("1");
1688  else
1689  tok->deleteThis();
1690  }
1691  }
1692 
1693  // simplify calculations..
1695  bool modified = true;
1696  while (modified) {
1697  modified = false;
1698  modified |= tokenizer.simplifySizeof();
1699  modified |= tokenizer.simplifyCalculations();
1700  modified |= tokenizer.simplifyConstTernaryOp();
1701  modified |= tokenizer.simplifyRedundantParentheses();
1702  for (Token *tok = const_cast<Token *>(tokenizer.tokens()); tok; tok = tok->next()) {
1703  if (Token::Match(tok, "! %num%")) {
1704  tok->deleteThis();
1705  tok->str(tok->str() == "0" ? "1" : "0");
1706  modified = true;
1707  }
1708  }
1709  }
1710 
1711  for (Token *tok = const_cast<Token *>(tokenizer.tokens()); tok; tok = tok->next()) {
1712  if (Token::Match(tok, "(|%oror%|&& %num% &&|%oror%|)")) {
1713  if (tok->next()->str() != "0") {
1714  tok->next()->str("1");
1715  }
1716  }
1717  }
1718 
1719  for (Token *tok = const_cast<Token *>(tokenizer.tokens()); tok; tok = tok->next()) {
1720  while (Token::Match(tok, "(|%oror% %any% %oror% 1")) {
1721  tok->deleteNext(2);
1722  if (tok->tokAt(-3))
1723  tok = tok->tokAt(-3);
1724  }
1725  }
1726 
1727  if (Token::simpleMatch(tokenizer.tokens(), "( 1 )") ||
1728  Token::simpleMatch(tokenizer.tokens(), "( 1 ||"))
1729  condition = "1";
1730  else if (Token::simpleMatch(tokenizer.tokens(), "( 0 )"))
1731  condition = "0";
1732 }
1733 
1734 bool Preprocessor::match_cfg_def(std::map<std::string, std::string> cfg, std::string def)
1735 {
1736  /*
1737  std::cout << "cfg: \"";
1738  for (std::map<std::string, std::string>::const_iterator it = cfg.begin(); it != cfg.end(); ++it)
1739  {
1740  std::cout << it->first;
1741  if (!it->second.empty())
1742  std::cout << "=" << it->second;
1743  std::cout << ";";
1744  }
1745  std::cout << "\" ";
1746  std::cout << "def: \"" << def << "\"\n";
1747  */
1748 
1749  simplifyVarMap(cfg);
1750  simplifyCondition(cfg, def, true);
1751 
1752  if (cfg.find(def) != cfg.end())
1753  return true;
1754 
1755  if (def == "0")
1756  return false;
1757 
1758  if (def == "1")
1759  return true;
1760 
1761  return false;
1762 }
1763 
1764 std::string Preprocessor::getcode(const std::string &filedata, const std::string &cfg, const std::string &filename)
1765 {
1766  // For the error report
1767  unsigned int lineno = 0;
1768 
1769  std::ostringstream ret;
1770 
1771  bool match = true;
1772  std::list<bool> matching_ifdef;
1773  std::list<bool> matched_ifdef;
1774 
1775  // Create a map for the cfg for faster access to defines
1776  std::map<std::string, std::string> cfgmap(getcfgmap(cfg, _settings, filename));
1777 
1778  std::stack<std::string> filenames;
1779  filenames.push(filename);
1780  std::stack<unsigned int> lineNumbers;
1781  std::istringstream istr(filedata);
1782  std::string line;
1783  while (std::getline(istr, line)) {
1784  ++lineno;
1785 
1786  if (_settings && _settings->terminated())
1787  return "";
1788 
1789  if (line.compare(0, 11, "#pragma asm") == 0) {
1790  ret << "\n";
1791  bool found_end = false;
1792  while (getline(istr, line)) {
1793  if (line.compare(0, 14, "#pragma endasm") == 0) {
1794  found_end = true;
1795  break;
1796  }
1797 
1798  ret << "\n";
1799  }
1800  if (!found_end)
1801  break;
1802 
1803  if (line.find("=") != std::string::npos) {
1804  Tokenizer tokenizer(_settings, _errorLogger);
1805  line.erase(0, sizeof("#pragma endasm"));
1806  std::istringstream tempIstr(line);
1807  tokenizer.tokenize(tempIstr, "");
1808  if (Token::Match(tokenizer.tokens(), "( %var% = %any% )")) {
1809  ret << "asm(" << tokenizer.tokens()->strAt(1) << ");";
1810  }
1811  }
1812 
1813  ret << "\n";
1814 
1815  continue;
1816  }
1817 
1818  const std::string def = getdef(line, true);
1819  const std::string ndef = getdef(line, false);
1820 
1821  const bool emptymatch = matching_ifdef.empty() | matched_ifdef.empty();
1822 
1823  if (line.compare(0, 8, "#define ") == 0) {
1824  match = true;
1825 
1826  if (_settings) {
1827  typedef std::set<std::string>::const_iterator It;
1828  for (It it = _settings->userUndefs.begin(); it != _settings->userUndefs.end(); ++it) {
1829  std::string::size_type pos = line.find_first_not_of(' ',8);
1830  if (pos != std::string::npos) {
1831  std::string::size_type pos2 = line.find(*it,pos);
1832  if ((pos2 != std::string::npos) &&
1833  ((line.size() == pos2 + (*it).size()) ||
1834  (line[pos2 + (*it).size()] == ' ') ||
1835  (line[pos2 + (*it).size()] == '('))) {
1836  match = false;
1837  break;
1838  }
1839  }
1840  }
1841  }
1842 
1843  for (std::list<bool>::const_iterator it = matching_ifdef.begin(); it != matching_ifdef.end(); ++it)
1844  match &= bool(*it);
1845 
1846  if (match) {
1847  std::string::size_type pos = line.find_first_of(" (", 8);
1848  if (pos == std::string::npos)
1849  cfgmap[line.substr(8)] = "";
1850  else if (line[pos] == ' ') {
1851  std::string value(line.substr(pos + 1));
1852  if (cfgmap.find(value) != cfgmap.end())
1853  value = cfgmap[value];
1854  cfgmap[line.substr(8, pos - 8)] = value;
1855  } else
1856  cfgmap[line.substr(8, pos - 8)] = "";
1857  }
1858  }
1859 
1860  else if (line.compare(0, 7, "#undef ") == 0) {
1861  const std::string name(line.substr(7));
1862  cfgmap.erase(name);
1863  }
1864 
1865  else if (!emptymatch && line.compare(0, 7, "#elif !") == 0) {
1866  if (matched_ifdef.back()) {
1867  matching_ifdef.back() = false;
1868  } else {
1869  if (!match_cfg_def(cfgmap, ndef)) {
1870  matching_ifdef.back() = true;
1871  matched_ifdef.back() = true;
1872  }
1873  }
1874  }
1875 
1876  else if (!emptymatch && line.compare(0, 6, "#elif ") == 0) {
1877  if (matched_ifdef.back()) {
1878  matching_ifdef.back() = false;
1879  } else {
1880  if (match_cfg_def(cfgmap, def)) {
1881  matching_ifdef.back() = true;
1882  matched_ifdef.back() = true;
1883  }
1884  }
1885  }
1886 
1887  else if (line.compare(0,4,"#if ") == 0) {
1888  matching_ifdef.push_back(match_cfg_def(cfgmap, line.substr(4)));
1889  matched_ifdef.push_back(matching_ifdef.back());
1890  }
1891 
1892  else if (! def.empty()) {
1893  matching_ifdef.push_back(cfgmap.find(def) != cfgmap.end());
1894  matched_ifdef.push_back(matching_ifdef.back());
1895  }
1896 
1897  else if (! ndef.empty()) {
1898  matching_ifdef.push_back(cfgmap.find(ndef) == cfgmap.end());
1899  matched_ifdef.push_back(matching_ifdef.back());
1900  }
1901 
1902  else if (!emptymatch && line == "#else") {
1903  if (! matched_ifdef.empty())
1904  matching_ifdef.back() = ! matched_ifdef.back();
1905  }
1906 
1907  else if (line.compare(0, 6, "#endif") == 0) {
1908  if (! matched_ifdef.empty())
1909  matched_ifdef.pop_back();
1910  if (! matching_ifdef.empty())
1911  matching_ifdef.pop_back();
1912  }
1913 
1914  if (!line.empty() && line[0] == '#') {
1915  match = true;
1916  for (std::list<bool>::const_iterator it = matching_ifdef.begin(); it != matching_ifdef.end(); ++it)
1917  match &= bool(*it);
1918  }
1919 
1920  // #error => return ""
1921  if (match && line.compare(0, 6, "#error") == 0) {
1922  if (_settings && !_settings->userDefines.empty()) {
1923  Settings settings2(*_settings);
1924  Preprocessor preprocessor(&settings2, _errorLogger);
1925  preprocessor.error(filenames.top(), lineno, line);
1926  }
1927  return "";
1928  }
1929 
1930  if (!match && (line.compare(0, 8, "#define ") == 0 ||
1931  line.compare(0, 6, "#undef") == 0)) {
1932  // Remove define that is not part of this configuration
1933  line = "";
1934  } else if (line.compare(0, 7, "#file \"") == 0 ||
1935  line.compare(0, 8, "#endfile") == 0 ||
1936  line.compare(0, 8, "#define ") == 0 ||
1937  line.compare(0, 6, "#line ") == 0 ||
1938  line.compare(0, 6, "#undef") == 0) {
1939  // We must not remove #file tags or line numbers
1940  // are corrupted. File tags are removed by the tokenizer.
1941 
1942  // Keep location info updated
1943  if (line.compare(0, 7, "#file \"") == 0) {
1944  filenames.push(line.substr(7, line.size() - 8));
1945  lineNumbers.push(lineno);
1946  lineno = 0;
1947  } else if (line.compare(0, 8, "#endfile") == 0) {
1948  if (filenames.size() > 1U)
1949  filenames.pop();
1950 
1951  if (!lineNumbers.empty()) {
1952  lineno = lineNumbers.top();
1953  lineNumbers.pop();
1954  }
1955  }
1956  } else if (!match || line.compare(0, 1, "#") == 0) {
1957  // Remove #if, #else, #pragma etc, leaving only
1958  // #define, #undef, #file and #endfile. and also lines
1959  // which are not part of this configuration.
1960  line = "";
1961  }
1962 
1963  ret << line << "\n";
1964  }
1965 
1966  if (!validateCfg(ret.str(), cfg)) {
1967  return "";
1968  }
1969 
1970  return expandMacros(ret.str(), filename, cfg, _errorLogger);
1971 }
1972 
1973 void Preprocessor::error(const std::string &filename, unsigned int linenr, const std::string &msg)
1974 {
1975  std::list<ErrorLogger::ErrorMessage::FileLocation> locationList;
1976  if (!filename.empty()) {
1978  loc.line = linenr;
1979  loc.setfile(filename);
1980  locationList.push_back(loc);
1981  }
1984  msg,
1985  "preprocessorErrorDirective",
1986  false));
1987 }
1988 
1990 {
1991  std::string result;
1992  std::string::size_type i = str.find_first_of("<\"");
1993  if (i == std::string::npos) {
1994  str = "";
1995  return NoHeader;
1996  }
1997 
1998  char c = str[i];
1999  if (c == '<')
2000  c = '>';
2001 
2002  for (i = i + 1; i < str.length(); ++i) {
2003  if (str[i] == c)
2004  break;
2005 
2006  result.append(1, str[i]);
2007  }
2008 
2009  // Linux can't open include paths with \ separator, so fix them
2010  std::replace(result.begin(), result.end(), '\\', '/');
2011 
2012  str = result;
2013 
2014  return (c == '\"') ? UserHeader : SystemHeader;
2015 }
2016 
2017 /**
2018  * Try to open header
2019  * @param filename header name (in/out)
2020  * @param includePaths paths where to look for the file
2021  * @param filePath path to the header file
2022  * @param fin file input stream (in/out)
2023  * @return if file is opened then true is returned
2024  */
2025 static bool openHeader(std::string &filename, const std::list<std::string> &includePaths, const std::string &filePath, std::ifstream &fin)
2026 {
2027  fin.open((filePath + filename).c_str());
2028  if (fin.is_open()) {
2029  filename = filePath + filename;
2030  return true;
2031  }
2032 
2033  std::list<std::string> includePaths2(includePaths);
2034  includePaths2.push_front("");
2035 
2036  for (std::list<std::string>::const_iterator iter = includePaths2.begin(); iter != includePaths2.end(); ++iter) {
2037  const std::string nativePath(Path::toNativeSeparators(*iter));
2038  fin.open((nativePath + filename).c_str());
2039  if (fin.is_open()) {
2040  filename = nativePath + filename;
2041  return true;
2042  }
2043  fin.clear();
2044  }
2045 
2046  return false;
2047 }
2048 
2049 
2050 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::set<std::string> &pragmaOnce, std::list<std::string> includes)
2051 {
2052  const std::string path(filePath.substr(0, 1 + filePath.find_last_of("\\/")));
2053 
2054  // current #if indent level.
2055  std::stack<bool>::size_type indent = 0;
2056 
2057  // how deep does the #if match? this can never be bigger than "indent".
2058  std::stack<bool>::size_type indentmatch = 0;
2059 
2060  // has there been a true #if condition at the current indentmatch level?
2061  // then no more #elif or #else can be true before the #endif is seen.
2062  std::stack<bool> elseIsTrueStack;
2063 
2064  unsigned int linenr = 0;
2065 
2066  std::set<std::string> undefs = _settings ? _settings->userUndefs : std::set<std::string>();
2067 
2068  if (_errorLogger)
2069  _errorLogger->reportProgress(filePath, "Preprocessor (handleIncludes)", 0);
2070 
2071  std::ostringstream ostr;
2072  std::istringstream istr(code);
2073  std::string line;
2074  bool suppressCurrentCodePath = false;
2075  while (std::getline(istr,line)) {
2076  ++linenr;
2077 
2078  if (_settings && _settings->terminated())
2079  return "";
2080 
2081  // has there been a true #if condition at the current indentmatch level?
2082  // then no more #elif or #else can be true before the #endif is seen.
2083  while (elseIsTrueStack.size() != indentmatch + 1) {
2084  if (elseIsTrueStack.size() < indentmatch + 1) {
2085  elseIsTrueStack.push(true);
2086  } else {
2087  elseIsTrueStack.pop();
2088  }
2089  }
2090 
2091  if (elseIsTrueStack.empty()) {
2092  writeError(filePath, linenr, _errorLogger, "syntaxError", "Syntax error in preprocessor code");
2093  return "";
2094  }
2095 
2096  std::stack<bool>::reference elseIsTrue = elseIsTrueStack.top();
2097 
2098  if (line == "#pragma once") {
2099  pragmaOnce.insert(filePath);
2100  } else if (line.compare(0,7,"#ifdef ") == 0) {
2101  if (indent == indentmatch) {
2102  const std::string tag = getdef(line,true);
2103  if (defs.find(tag) != defs.end()) {
2104  elseIsTrue = false;
2105  indentmatch++;
2106  } else if (undefs.find(tag) != undefs.end()) {
2107  elseIsTrue = true;
2108  indentmatch++;
2109  suppressCurrentCodePath = true;
2110  }
2111  }
2112  ++indent;
2113 
2114  if (indent == indentmatch + 1)
2115  elseIsTrue = true;
2116  } else if (line.compare(0,8,"#ifndef ") == 0) {
2117  if (indent == indentmatch) {
2118  const std::string tag = getdef(line,false);
2119  if (defs.find(tag) == defs.end()) {
2120  elseIsTrue = false;
2121  indentmatch++;
2122  } else if (undefs.find(tag) != undefs.end()) {
2123  elseIsTrue = false;
2124  indentmatch++;
2125  suppressCurrentCodePath = false;
2126  }
2127  }
2128  ++indent;
2129 
2130  if (indent == indentmatch + 1)
2131  elseIsTrue = true;
2132 
2133  } else if (line.compare(0,4,"#if ") == 0) {
2134  if (!suppressCurrentCodePath && indent == indentmatch && match_cfg_def(defs, line.substr(4))) {
2135  elseIsTrue = false;
2136  indentmatch++;
2137  }
2138  ++indent;
2139 
2140  if (indent == indentmatch + 1)
2141  elseIsTrue = true; // this value doesn't matter when suppressCurrentCodePath is true
2142  } else if (line.compare(0,6,"#elif ") == 0 || line.compare(0,5,"#else") == 0) {
2143  if (!elseIsTrue) {
2144  if (indentmatch == indent) {
2145  indentmatch = indent - 1;
2146  }
2147  } else {
2148  if (indentmatch == indent) {
2149  indentmatch = indent - 1;
2150  } else if (indentmatch == indent - 1) {
2151  if (line.compare(0,5,"#else")==0 || match_cfg_def(defs,line.substr(6))) {
2152  indentmatch = indent;
2153  elseIsTrue = false;
2154  }
2155  }
2156  }
2157  } else if (line.compare(0, 6, "#endif") == 0) {
2158  if (indent > 0)
2159  --indent;
2160  if (indentmatch > indent || indent == 0) {
2161  indentmatch = indent;
2162  elseIsTrue = false;
2163  suppressCurrentCodePath = false;
2164  }
2165  } else if (indentmatch == indent) {
2166  if (!suppressCurrentCodePath && line.compare(0, 8, "#define ") == 0) {
2167  const unsigned int endOfDefine = 8;
2168  std::string::size_type endOfTag = line.find_first_of("( ", endOfDefine);
2169  std::string tag;
2170 
2171  // define a symbol
2172  if (endOfTag == std::string::npos) {
2173  tag = line.substr(endOfDefine);
2174  defs[tag] = "";
2175  } else {
2176  tag = line.substr(endOfDefine, endOfTag-endOfDefine);
2177 
2178  // define a function-macro
2179  if (line[endOfTag] == '(') {
2180  defs[tag] = "";
2181  }
2182  // define value
2183  else {
2184  ++endOfTag;
2185 
2186  const std::string& value = line.substr(endOfTag, line.size()-endOfTag);
2187 
2188  if (defs.find(value) != defs.end())
2189  defs[tag] = defs[value];
2190  else
2191  defs[tag] = value;
2192  }
2193  }
2194 
2195  if (undefs.find(tag) != undefs.end()) {
2196  defs.erase(tag);
2197  }
2198  }
2199 
2200  else if (!suppressCurrentCodePath && line.compare(0,7,"#undef ") == 0) {
2201  defs.erase(line.substr(7));
2202  }
2203 
2204  else if (!suppressCurrentCodePath && line.compare(0,7,"#error ") == 0) {
2205  error(filePath, linenr, line.substr(7));
2206  }
2207 
2208  else if (!suppressCurrentCodePath && line.compare(0,9,"#include ")==0) {
2209  std::string filename(line.substr(9));
2210 
2211  const HeaderTypes headerType = getHeaderFileName(filename);
2212  if (headerType == NoHeader) {
2213  ostr << std::endl;
2214  continue;
2215  }
2216 
2217  // try to open file
2218  std::string filepath;
2219  if (headerType == UserHeader)
2220  filepath = path;
2221  std::ifstream fin;
2222  if (!openHeader(filename, includePaths, filepath, fin)) {
2224  linenr,
2225  filename,
2226  headerType
2227  );
2228  ostr << std::endl;
2229  continue;
2230  }
2231 
2232  // Prevent that files are recursively included
2233  if (std::find(includes.begin(), includes.end(), filename) != includes.end()) {
2234  ostr << std::endl;
2235  continue;
2236  }
2237 
2238  includes.push_back(filename);
2239 
2240  // Don't include header if it's already included and contains #pragma once
2241  if (pragmaOnce.find(filename) != pragmaOnce.end()) {
2242  ostr << std::endl;
2243  continue;
2244  }
2245 
2246  ostr << "#file \"" << filename << "\"\n"
2247  << handleIncludes(read(fin, filename), filename, includePaths, defs, pragmaOnce, includes) << std::endl
2248  << "#endfile\n";
2249  continue;
2250  }
2251 
2252  if (!suppressCurrentCodePath)
2253  ostr << line;
2254  }
2255 
2256  // A line has been read..
2257  ostr << "\n";
2258  }
2259 
2260  return ostr.str();
2261 }
2262 
2263 
2264 void Preprocessor::handleIncludes(std::string &code, const std::string &filePath, const std::list<std::string> &includePaths)
2265 {
2266  std::list<std::string> paths;
2267  std::string path;
2268  path = filePath;
2269  path.erase(1 + path.find_last_of("\\/"));
2270  paths.push_back(path);
2271  std::string::size_type pos = 0;
2272  std::string::size_type endfilePos = 0;
2273  std::set<std::string> handledFiles;
2274  while ((pos = code.find("#include", pos)) != std::string::npos) {
2275  if (_settings && _settings->terminated())
2276  return;
2277 
2278  // Accept only includes that are at the start of a line
2279  if (pos > 0 && code[pos-1] != '\n') {
2280  pos += 8; // length of "#include"
2281  continue;
2282  }
2283 
2284  // If endfile is encountered, we have moved to a next file in our stack,
2285  // so remove last path in our list.
2286  while (!paths.empty() && (endfilePos = code.find("\n#endfile", endfilePos)) != std::string::npos && endfilePos < pos) {
2287  paths.pop_back();
2288  endfilePos += 9; // size of #endfile
2289  }
2290 
2291  endfilePos = pos;
2292  std::string::size_type end = code.find("\n", pos);
2293  std::string filename = code.substr(pos, end - pos);
2294 
2295  // Remove #include clause
2296  code.erase(pos, end - pos);
2297 
2298  HeaderTypes headerType = getHeaderFileName(filename);
2299  if (headerType == NoHeader)
2300  continue;
2301 
2302  // filename contains now a file name e.g. "menu.h"
2303  std::string processedFile;
2304  std::string filepath;
2305  if (headerType == UserHeader && !paths.empty())
2306  filepath = paths.back();
2307  std::ifstream fin;
2308  const bool fileOpened(openHeader(filename, includePaths, filepath, fin));
2309 
2310  if (fileOpened) {
2311  filename = Path::simplifyPath(filename);
2312  std::string tempFile = filename;
2313  std::transform(tempFile.begin(), tempFile.end(), tempFile.begin(), tolowerWrapper);
2314  if (handledFiles.find(tempFile) != handledFiles.end()) {
2315  // We have processed this file already once, skip
2316  // it this time to avoid eternal loop.
2317  fin.close();
2318  continue;
2319  }
2320 
2321  handledFiles.insert(tempFile);
2322  processedFile = Preprocessor::read(fin, filename);
2323  fin.close();
2324  }
2325 
2326  if (!processedFile.empty()) {
2327  // Remove space characters that are after or before new line character
2328  processedFile = "#file \"" + Path::fromNativeSeparators(filename) + "\"\n" + processedFile + "\n#endfile";
2329  code.insert(pos, processedFile);
2330 
2331  path = filename;
2332  path.erase(1 + path.find_last_of("\\/"));
2333  paths.push_back(path);
2334  } else if (!fileOpened && _settings) {
2335  std::string f = filePath;
2336 
2337  // Determine line number of include
2338  unsigned int linenr = 1;
2339  unsigned int level = 0;
2340  for (std::string::size_type p = 1; p <= pos; ++p) {
2341  if (level == 0 && code[pos-p] == '\n')
2342  ++linenr;
2343  else if (code.compare(pos-p, 9, "#endfile\n") == 0) {
2344  ++level;
2345  } else if (code.compare(pos-p, 6, "#file ") == 0) {
2346  if (level == 0) {
2347  linenr--;
2348  const std::string::size_type pos1 = pos - p + 7;
2349  const std::string::size_type pos2 = code.find_first_of("\"\n", pos1);
2350  f = code.substr(pos1, (pos2 == std::string::npos) ? pos2 : (pos2 - pos1));
2351  break;
2352  }
2353  --level;
2354  }
2355  }
2356 
2358  linenr,
2359  filename,
2360  headerType);
2361  }
2362  }
2363 }
2364 
2365 // Report that include is missing
2366 void Preprocessor::missingInclude(const std::string &filename, unsigned int linenr, const std::string &header, HeaderTypes headerType)
2367 {
2368  const std::string msgtype = (headerType==SystemHeader)?"missingIncludeSystem":"missingInclude";
2369  if (!_settings->nomsg.isSuppressed(msgtype, Path::fromNativeSeparators(filename), linenr)) {
2370  missingIncludeFlag = true;
2372 
2373  std::list<ErrorLogger::ErrorMessage::FileLocation> locationList;
2374  if (!filename.empty()) {
2376  loc.line = linenr;
2377  loc.setfile(Path::toNativeSeparators(filename));
2378  locationList.push_back(loc);
2379  }
2380  ErrorLogger::ErrorMessage errmsg(locationList, Severity::information,
2381  (headerType==SystemHeader) ?
2382  "Include file: <" + header + "> not found. Please note: Cppcheck does not need standard library headers to get proper results." :
2383  "Include file: \"" + header + "\" not found.",
2384  msgtype, false);
2385  errmsg.file0 = file0;
2386  _errorLogger->reportInfo(errmsg);
2387  }
2388  }
2389 }
2390 
2391 /**
2392  * Skip string in line. A string begins and ends with either a &quot; or a &apos;
2393  * @param line the string
2394  * @param pos in=start position of string, out=end position of string
2395  */
2396 static void skipstring(const std::string &line, std::string::size_type &pos)
2397 {
2398  const char ch = line[pos];
2399 
2400  ++pos;
2401  while (pos < line.size() && line[pos] != ch) {
2402  if (line[pos] == '\\')
2403  ++pos;
2404  ++pos;
2405  }
2406 }
2407 
2408 /**
2409  * Remove heading and trailing whitespaces from the input parameter.
2410  * @param s The string to trim.
2411  */
2412 static std::string trim(const std::string& s)
2413 {
2414  std::string::size_type beg = s.find_first_not_of(" \t");
2415  if (beg == std::string::npos)
2416  return s;
2417  std::string::size_type end = s.find_last_not_of(" \t");
2418  if (end == std::string::npos)
2419  return s.substr(beg);
2420  return s.substr(beg, end - beg + 1);
2421 }
2422 
2423 /**
2424  * @brief get parameters from code. For example 'foo(1,2)' => '1','2'
2425  * @param line in: The code
2426  * @param pos in: Position to the '('. out: Position to the ')'
2427  * @param params out: The extracted parameters
2428  * @param numberOfNewlines out: number of newlines in the macro call
2429  * @param endFound out: was the end parentheses found?
2430  */
2431 static void getparams(const std::string &line,
2432  std::string::size_type &pos,
2433  std::vector<std::string> &params,
2434  unsigned int &numberOfNewlines,
2435  bool &endFound)
2436 {
2437  params.clear();
2438  numberOfNewlines = 0;
2439  endFound = false;
2440 
2441  if (line[pos] == ' ')
2442  pos++;
2443 
2444  if (line[pos] != '(')
2445  return;
2446 
2447  // parentheses level
2448  int parlevel = 0;
2449 
2450  // current parameter data
2451  std::string par;
2452 
2453  // scan for parameters..
2454  for (; pos < line.length(); ++pos) {
2455  // increase parentheses level
2456  if (line[pos] == '(') {
2457  ++parlevel;
2458  if (parlevel == 1)
2459  continue;
2460  }
2461 
2462  // decrease parentheses level
2463  else if (line[pos] == ')') {
2464  --parlevel;
2465  if (parlevel <= 0) {
2466  endFound = true;
2467  params.push_back(trim(par));
2468  break;
2469  }
2470  }
2471 
2472  // string
2473  else if (line[pos] == '\"' || line[pos] == '\'') {
2474  const std::string::size_type p = pos;
2475  skipstring(line, pos);
2476  if (pos == line.length())
2477  break;
2478  par += line.substr(p, pos + 1 - p);
2479  continue;
2480  }
2481 
2482  // count newlines. the expanded macro must have the same number of newlines
2483  else if (line[pos] == '\n') {
2484  ++numberOfNewlines;
2485  continue;
2486  }
2487 
2488  // new parameter
2489  if (parlevel == 1 && line[pos] == ',') {
2490  params.push_back(trim(par));
2491  par = "";
2492  }
2493 
2494  // spaces are only added if needed
2495  else if (line[pos] == ' ') {
2496  // Add space only if it is needed
2497  if (par.size() && std::isalnum((unsigned char)par[par.length()-1])) {
2498  par += ' ';
2499  }
2500  }
2501 
2502  // add character to current parameter
2503  else if (parlevel >= 1 && line[pos] != Preprocessor::macroChar) {
2504  par.append(1, line[pos]);
2505  }
2506  }
2507 }
2508 
2509 /** @brief Class that the preprocessor uses when it expands macros. This class represents a preprocessor macro */
2511 private:
2513 
2514  /** tokens of this macro */
2516 
2517  /** macro parameters */
2518  std::vector<std::string> _params;
2519 
2520  /** name of macro */
2521  std::string _name;
2522 
2523  /** macro definition in plain text */
2524  const std::string _macro;
2525 
2526  /** prefix that is used by cppcheck to separate macro parameters. Always "__cppcheck__" */
2527  const std::string _prefix;
2528 
2529  /** does this macro take a variable number of parameters? */
2531 
2532  /** The macro has parentheses but no parameters.. "AAA()" */
2533  bool _nopar;
2534 
2535  /** disabled assignment operator */
2536  void operator=(const PreprocessorMacro &);
2537 
2538  /** @brief expand inner macro */
2539  std::vector<std::string> expandInnerMacros(const std::vector<std::string> &params1,
2540  const std::map<std::string, PreprocessorMacro *> &macros) const {
2541  std::string innerMacroName;
2542 
2543  // Is there an inner macro..
2544  {
2545  const Token *tok = Token::findsimplematch(tokens(), ")");
2546  if (!Token::Match(tok, ") %var% ("))
2547  return params1;
2548  innerMacroName = tok->strAt(1);
2549  tok = tok->tokAt(3);
2550  unsigned int par = 0;
2551  while (Token::Match(tok, "%var% ,|)")) {
2552  tok = tok->tokAt(2);
2553  par++;
2554  }
2555  if (tok || par != params1.size())
2556  return params1;
2557  }
2558 
2559  std::vector<std::string> params2(params1);
2560 
2561  for (unsigned int ipar = 0; ipar < params1.size(); ++ipar) {
2562  const std::string s(innerMacroName + "(");
2563  std::string param(params1[ipar]);
2564  if (param.compare(0,s.length(),s)==0 && param[param.length()-1]==')') {
2565  std::vector<std::string> innerparams;
2566  std::string::size_type pos = s.length() - 1;
2567  unsigned int num = 0;
2568  bool endFound = false;
2569  getparams(param, pos, innerparams, num, endFound);
2570  if (pos == param.length()-1 && num==0 && endFound && innerparams.size() == params1.size()) {
2571  // Is inner macro defined?
2572  std::map<std::string, PreprocessorMacro *>::const_iterator it = macros.find(innerMacroName);
2573  if (it != macros.end()) {
2574  // expand the inner macro
2575  const PreprocessorMacro *innerMacro = it->second;
2576 
2577  std::string innercode;
2578  std::map<std::string,PreprocessorMacro *> innermacros = macros;
2579  innermacros.erase(innerMacroName);
2580  innerMacro->code(innerparams, innermacros, innercode);
2581  params2[ipar] = innercode;
2582  }
2583  }
2584  }
2585  }
2586 
2587  return params2;
2588  }
2589 
2590 public:
2591  /**
2592  * @brief Constructor for PreprocessorMacro. This is the "setter"
2593  * for this class - everything is setup here.
2594  * @param macro The code after define, until end of line,
2595  * e.g. "A(x) foo(x);"
2596  */
2597  explicit PreprocessorMacro(const std::string &macro)
2598  : _macro(macro), _prefix("__cppcheck__") {
2600 
2601  // Tokenize the macro to make it easier to handle
2602  std::istringstream istr(macro);
2603  tokenizer.list.createTokens(istr);
2604 
2605  // macro name..
2606  if (tokens() && tokens()->isName())
2607  _name = tokens()->str();
2608 
2609  // initialize parameters to default values
2610  _variadic = _nopar = false;
2611 
2612  std::string::size_type pos = macro.find_first_of(" (");
2613  if (pos != std::string::npos && macro[pos] == '(') {
2614  // Extract macro parameters
2615  if (Token::Match(tokens(), "%var% ( %var%")) {
2616  for (const Token *tok = tokens()->tokAt(2); tok; tok = tok->next()) {
2617  if (tok->str() == ")")
2618  break;
2619  if (Token::simpleMatch(tok, ". . . )")) {
2620  if (tok->previous()->str() == ",")
2621  _params.push_back("__VA_ARGS__");
2622  _variadic = true;
2623  break;
2624  }
2625  if (tok->isName())
2626  _params.push_back(tok->str());
2627  }
2628  }
2629 
2630  else if (Token::Match(tokens(), "%var% ( . . . )"))
2631  _variadic = true;
2632 
2633  else if (Token::Match(tokens(), "%var% ( )"))
2634  _nopar = true;
2635  }
2636  }
2637 
2638  /** return tokens of this macro */
2639  const Token *tokens() const {
2640  return tokenizer.tokens();
2641  }
2642 
2643  /** read parameters of this macro */
2644  const std::vector<std::string> &params() const {
2645  return _params;
2646  }
2647 
2648  /** check if this is macro has a variable number of parameters */
2649  bool variadic() const {
2650  return _variadic;
2651  }
2652 
2653  /** Check if this macro has parentheses but no parameters */
2654  bool nopar() const {
2655  return _nopar;
2656  }
2657 
2658  /** name of macro */
2659  const std::string &name() const {
2660  return _name;
2661  }
2662 
2663  /**
2664  * get expanded code for this macro
2665  * @param params2 macro parameters
2666  * @param macros macro definitions (recursion)
2667  * @param macrocode output string
2668  * @return true if the expanding was successful
2669  */
2670  bool code(const std::vector<std::string> &params2, const std::map<std::string, PreprocessorMacro *> &macros, std::string &macrocode) const {
2671  if (_nopar || (_params.empty() && _variadic)) {
2672  macrocode = _macro.substr(1 + _macro.find(")"));
2673  if (macrocode.empty())
2674  return true;
2675 
2676  std::string::size_type pos = 0;
2677  // Remove leading spaces
2678  if ((pos = macrocode.find_first_not_of(" ")) > 0)
2679  macrocode.erase(0, pos);
2680  // Remove ending newline
2681  if ((pos = macrocode.find_first_of("\r\n")) != std::string::npos)
2682  macrocode.erase(pos);
2683 
2684  // Replace "__VA_ARGS__" with parameters
2685  if (!_nopar) {
2686  std::string s;
2687  for (unsigned int i = 0; i < params2.size(); ++i) {
2688  if (i > 0)
2689  s += ",";
2690  s += params2[i];
2691  }
2692 
2693  pos = 0;
2694  while ((pos = macrocode.find("__VA_ARGS__", pos)) != std::string::npos) {
2695  macrocode.erase(pos, 11);
2696  macrocode.insert(pos, s);
2697  pos += s.length();
2698  }
2699  }
2700  }
2701 
2702  else if (_params.empty()) {
2703  std::string::size_type pos = _macro.find_first_of(" \"");
2704  if (pos == std::string::npos)
2705  macrocode = "";
2706  else {
2707  if (_macro[pos] == ' ')
2708  pos++;
2709  macrocode = _macro.substr(pos);
2710  if ((pos = macrocode.find_first_of("\r\n")) != std::string::npos)
2711  macrocode.erase(pos);
2712  }
2713  }
2714 
2715  else {
2716  const std::vector<std::string> givenparams = expandInnerMacros(params2, macros);
2717 
2718  const Token *tok = tokens();
2719  while (tok && tok->str() != ")")
2720  tok = tok->next();
2721  if (tok) {
2722  bool optcomma = false;
2723  while (nullptr != (tok = tok->next())) {
2724  std::string str = tok->str();
2725  if (str == "##")
2726  continue;
2727  if (str[0] == '#' || tok->isName()) {
2728  const bool stringify(str[0] == '#');
2729  if (stringify) {
2730  str = str.erase(0, 1);
2731  }
2732  for (unsigned int i = 0; i < _params.size(); ++i) {
2733  if (str == _params[i]) {
2734  if (_variadic &&
2735  (i == _params.size() - 1 ||
2736  (givenparams.size() + 2 == _params.size() && i + 1 == _params.size() - 1))) {
2737  str = "";
2738  for (unsigned int j = (unsigned int)_params.size() - 1; j < givenparams.size(); ++j) {
2739  if (optcomma || j > _params.size() - 1)
2740  str += ",";
2741  optcomma = false;
2742  str += givenparams[j];
2743  }
2744  } else if (i >= givenparams.size()) {
2745  // Macro had more parameters than caller used.
2746  macrocode = "";
2747  return false;
2748  } else if (stringify) {
2749  const std::string &s(givenparams[i]);
2750  std::ostringstream ostr;
2751  ostr << "\"";
2752  for (std::string::size_type j = 0; j < s.size(); ++j) {
2753  if (s[j] == '\\' || s[j] == '\"')
2754  ostr << '\\';
2755  ostr << s[j];
2756  }
2757  str = ostr.str() + "\"";
2758  } else
2759  str = givenparams[i];
2760 
2761  break;
2762  }
2763  }
2764 
2765  // expand nopar macro
2766  if (tok->strAt(-1) != "##") {
2767  const std::map<std::string, PreprocessorMacro *>::const_iterator it = macros.find(str);
2768  if (it != macros.end() && it->second->_macro.find("(") == std::string::npos) {
2769  str = it->second->_macro;
2770  if (str.find(" ") != std::string::npos)
2771  str.erase(0, str.find(" "));
2772  else
2773  str = "";
2774  }
2775  }
2776  }
2777  if (_variadic && tok->str() == "," && tok->next() && tok->next()->str() == "##") {
2778  optcomma = true;
2779  continue;
2780  }
2781  optcomma = false;
2782  macrocode += str;
2783  if (Token::Match(tok, "%var% %var%") ||
2784  Token::Match(tok, "%var% %num%") ||
2785  Token::Match(tok, "%num% %var%") ||
2786  Token::simpleMatch(tok, "> >"))
2787  macrocode += " ";
2788  }
2789  }
2790  }
2791 
2792  return true;
2793  }
2794 };
2795 
2796 /**
2797  * Get data from a input string. This is an extended version of std::getline.
2798  * The std::getline only get a single line at a time. It can therefore happen that it
2799  * contains a partial statement. This function ensures that the returned data
2800  * doesn't end in the middle of a statement. The "getlines" name indicate that
2801  * this function will return multiple lines if needed.
2802  * @param istr input stream
2803  * @param line output data
2804  * @return success
2805  */
2806 static bool getlines(std::istream &istr, std::string &line)
2807 {
2808  if (!istr.good())
2809  return false;
2810  line = "";
2811  int parlevel = 0;
2812  for (char ch = (char)istr.get(); istr.good(); ch = (char)istr.get()) {
2813  if (ch == '\'' || ch == '\"') {
2814  line += ch;
2815  char c = 0;
2816  while (istr.good() && c != ch) {
2817  if (c == '\\') {
2818  c = (char)istr.get();
2819  if (!istr.good())
2820  return true;
2821  line += c;
2822  }
2823 
2824  c = (char)istr.get();
2825  if (!istr.good())
2826  return true;
2827  if (c == '\n' && line.compare(0, 1, "#") == 0)
2828  return true;
2829  line += c;
2830  }
2831  continue;
2832  }
2833  if (ch == '(')
2834  ++parlevel;
2835  else if (ch == ')')
2836  --parlevel;
2837  else if (ch == '\n') {
2838  if (line.compare(0, 1, "#") == 0)
2839  return true;
2840 
2841  if (istr.peek() == '#') {
2842  line += ch;
2843  return true;
2844  }
2845  } else if (line.compare(0, 1, "#") != 0 && parlevel <= 0 && ch == ';') {
2846  line += ";";
2847  return true;
2848  }
2849 
2850  line += ch;
2851  }
2852  return true;
2853 }
2854 
2855 bool Preprocessor::validateCfg(const std::string &code, const std::string &cfg)
2856 {
2857  // fill up "macros" with empty configuration macros
2858  std::set<std::string> macros;
2859  for (std::string::size_type pos = 0; pos < cfg.size();) {
2860  const std::string::size_type pos2 = cfg.find_first_of(";=", pos);
2861  if (pos2 == std::string::npos) {
2862  macros.insert(cfg.substr(pos));
2863  break;
2864  }
2865  if (cfg[pos2] == ';')
2866  macros.insert(cfg.substr(pos, pos2-pos));
2867  pos = cfg.find(";", pos2);
2868  if (pos != std::string::npos)
2869  ++pos;
2870  }
2871 
2872  // check if any empty macros are used in code
2873  for (std::set<std::string>::const_iterator it = macros.begin(); it != macros.end(); ++it) {
2874  const std::string &macro = *it;
2875  std::string::size_type pos = 0;
2876  while ((pos = code.find_first_of(std::string("#\"'")+macro[0], pos)) != std::string::npos) {
2877  const std::string::size_type pos1 = pos;
2878  const std::string::size_type pos2 = pos + macro.size();
2879  pos++;
2880 
2881  // skip string..
2882  if (code[pos1] == '\"' || code[pos1] == '\'') {
2883  while (pos < code.size() && code[pos] != code[pos1]) {
2884  if (code[pos] == '\\')
2885  ++pos;
2886  ++pos;
2887  }
2888  ++pos;
2889  }
2890 
2891  // skip preprocessor statement..
2892  else if (code[pos1] == '#') {
2893  if (pos1 == 0 || code[pos1-1] == '\n')
2894  pos = code.find("\n",pos);
2895  }
2896 
2897  // is macro used in code?
2898  else if (code.compare(pos1,macro.size(),macro) == 0) {
2899  if (pos1 > 0 && (std::isalnum((unsigned char)code[pos1-1U]) || code[pos1-1U] == '_'))
2900  continue;
2901  if (pos2 < code.size() && (std::isalnum((unsigned char)code[pos2]) || code[pos2] == '_'))
2902  continue;
2903  // macro is used in code, return false
2904  if (_settings->isEnabled("information"))
2905  validateCfgError(cfg, macro);
2906  return false;
2907  }
2908  }
2909  }
2910 
2911  return true;
2912 }
2913 
2914 void Preprocessor::validateCfgError(const std::string &cfg, const std::string &macro)
2915 {
2916  const std::string id = "ConfigurationNotChecked";
2917  std::list<ErrorLogger::ErrorMessage::FileLocation> locationList;
2919  loc.line = 1;
2920  loc.setfile(file0);
2921  locationList.push_back(loc);
2922  ErrorLogger::ErrorMessage errmsg(locationList, Severity::information, "Skipping configuration '" + cfg + "' since the value of '" + macro + "' is unknown. Use -D if you want to check it. You can use -U to skip it explicitly.", id, false);
2923  _errorLogger->reportInfo(errmsg);
2924 }
2925 
2926 std::string Preprocessor::expandMacros(const std::string &code, std::string filename, const std::string &cfg, ErrorLogger *errorLogger)
2927 {
2928  // Search for macros and expand them..
2929  // --------------------------------------------
2930 
2931  // Available macros (key=macroname, value=macro).
2932  std::map<std::string, PreprocessorMacro *> macros;
2933 
2934  {
2935  // fill up "macros" with user defined macros
2936  const std::map<std::string,std::string> cfgmap(getcfgmap(cfg,nullptr,""));
2937  std::map<std::string, std::string>::const_iterator it;
2938  for (it = cfgmap.begin(); it != cfgmap.end(); ++it) {
2939  std::string s = it->first;
2940  if (!it->second.empty())
2941  s += " " + it->second;
2942  PreprocessorMacro *macro = new PreprocessorMacro(s);
2943  macros[it->first] = macro;
2944  }
2945  }
2946 
2947  // Current line number
2948  unsigned int linenr = 1;
2949 
2950  // linenr, filename
2951  std::stack< std::pair<unsigned int, std::string> > fileinfo;
2952 
2953  // output stream
2954  std::ostringstream ostr;
2955 
2956  // read code..
2957  std::istringstream istr(code);
2958  std::string line;
2959  while (getlines(istr, line)) {
2960  // defining a macro..
2961  if (line.compare(0, 8, "#define ") == 0) {
2962  PreprocessorMacro *macro = new PreprocessorMacro(line.substr(8));
2963  if (macro->name().empty() || macro->name() == "NULL") {
2964  delete macro;
2965  } else if (macro->name() == "BOOST_FOREACH") {
2966  // BOOST_FOREACH is currently too complex to parse, so skip it.
2967  delete macro;
2968  } else {
2969  std::map<std::string, PreprocessorMacro *>::iterator it;
2970  it = macros.find(macro->name());
2971  if (it != macros.end())
2972  delete it->second;
2973  macros[macro->name()] = macro;
2974  }
2975  line = "\n";
2976  }
2977 
2978  // undefining a macro..
2979  else if (line.compare(0, 7, "#undef ") == 0) {
2980  std::map<std::string, PreprocessorMacro *>::iterator it;
2981  it = macros.find(line.substr(7));
2982  if (it != macros.end()) {
2983  delete it->second;
2984  macros.erase(it);
2985  }
2986  line = "\n";
2987  }
2988 
2989  // entering a file, update position..
2990  else if (line.compare(0, 7, "#file \"") == 0) {
2991  fileinfo.push(std::pair<unsigned int, std::string>(linenr, filename));
2992  filename = line.substr(7, line.length() - 8);
2993  linenr = 0;
2994  line += "\n";
2995  }
2996 
2997  // leaving a file, update position..
2998  else if (line == "#endfile") {
2999  if (!fileinfo.empty()) {
3000  linenr = fileinfo.top().first;
3001  filename = fileinfo.top().second;
3002  fileinfo.pop();
3003  }
3004  line += "\n";
3005  }
3006 
3007  // all other preprocessor directives are just replaced with a newline
3008  else if (line.compare(0, 1, "#") == 0) {
3009  line += "\n";
3010  }
3011 
3012  // expand macros..
3013  else {
3014  // Limit for each macro.
3015  // The limit specify a position in the "line" variable.
3016  // For a "recursive macro" where the expanded text contains
3017  // the macro again, the macro should not be expanded again.
3018  // The limits are used to prevent recursive expanding.
3019  // * When a macro is expanded its limit position is set to
3020  // the last expanded character.
3021  // * macros are only allowed to be expanded when the
3022  // the position is beyond the limit.
3023  // * The limit is relative to the end of the "line"
3024  // variable. Inserting and deleting text before the limit
3025  // without updating the limit is safe.
3026  // * when pos goes beyond a limit the limit needs to be
3027  // deleted because it is unsafe to insert/delete text
3028  // after the limit otherwise
3029  std::map<const PreprocessorMacro *, std::size_t> limits;
3030 
3031  // pos is the current position in line
3032  std::string::size_type pos = 0;
3033 
3034  // scan line to see if there are any macros to expand..
3035  unsigned int tmpLinenr = 0;
3036  while (pos < line.size()) {
3037  if (line[pos] == '\n')
3038  ++tmpLinenr;
3039 
3040  // skip strings..
3041  if (line[pos] == '\"' || line[pos] == '\'') {
3042  const char ch = line[pos];
3043 
3044  skipstring(line, pos);
3045  ++pos;
3046 
3047  if (pos >= line.size()) {
3048  writeError(filename,
3049  linenr + tmpLinenr,
3050  errorLogger,
3051  "noQuoteCharPair",
3052  std::string("No pair for character (") + ch + "). Can't process file. File is either invalid or unicode, which is currently not supported.");
3053 
3054  std::map<std::string, PreprocessorMacro *>::iterator it;
3055  for (it = macros.begin(); it != macros.end(); ++it)
3056  delete it->second;
3057  macros.clear();
3058  return "";
3059  }
3060 
3061  continue;
3062  }
3063 
3064  if (!std::isalpha((unsigned char)line[pos]) && line[pos] != '_')
3065  ++pos;
3066 
3067  // found an identifier..
3068  // the "while" is used in case the expanded macro will immediately call another macro
3069  while (pos < line.length() && (std::isalpha((unsigned char)line[pos]) || line[pos] == '_')) {
3070  // pos1 = start position of macro
3071  const std::string::size_type pos1 = pos++;
3072 
3073  // find the end of the identifier
3074  while (pos < line.size() && (std::isalnum((unsigned char)line[pos]) || line[pos] == '_'))
3075  ++pos;
3076 
3077  // get identifier
3078  const std::string id = line.substr(pos1, pos - pos1);
3079 
3080  // is there a macro with this name?
3081  std::map<std::string, PreprocessorMacro *>::const_iterator it;
3082  it = macros.find(id);
3083  if (it == macros.end())
3084  break; // no macro with this name exist
3085 
3086  const PreprocessorMacro * const macro = it->second;
3087 
3088  // check that pos is within allowed limits for this
3089  // macro
3090  {
3091  const std::map<const PreprocessorMacro *, std::size_t>::const_iterator it2 = limits.find(macro);
3092  if (it2 != limits.end() && pos <= line.length() - it2->second)
3093  break;
3094  }
3095 
3096  // get parameters from line..
3097  std::vector<std::string> params;
3098  std::string::size_type pos2 = pos;
3099  if (macro->params().size() && pos2 >= line.length())
3100  break;
3101 
3102  // number of newlines within macro use
3103  unsigned int numberOfNewlines = 0;
3104 
3105  // if the macro has parentheses, get parameters
3106  if (macro->variadic() || macro->nopar() || macro->params().size()) {
3107  // is the end parentheses found?
3108  bool endFound = false;
3109 
3110  getparams(line,pos2,params,numberOfNewlines,endFound);
3111 
3112  // something went wrong so bail out
3113  if (!endFound)
3114  break;
3115  }
3116 
3117  // Just an empty parameter => clear
3118  if (params.size() == 1 && params[0] == "")
3119  params.clear();
3120 
3121  // Check that it's the same number of parameters..
3122  if (!macro->variadic() && params.size() != macro->params().size())
3123  break;
3124 
3125  // Create macro code..
3126  std::string tempMacro;
3127  if (!macro->code(params, macros, tempMacro)) {
3128  // Syntax error in code
3129  writeError(filename,
3130  linenr + tmpLinenr,
3131  errorLogger,
3132  "syntaxError",
3133  std::string("Syntax error. Not enough parameters for macro '") + macro->name() + "'.");
3134 
3135  std::map<std::string, PreprocessorMacro *>::iterator iter;
3136  for (iter = macros.begin(); iter != macros.end(); ++iter)
3137  delete iter->second;
3138  macros.clear();
3139  return "";
3140  }
3141 
3142  // make sure number of newlines remain the same..
3143  std::string macrocode(std::string(numberOfNewlines, '\n') + tempMacro);
3144 
3145  // Insert macro code..
3146  if (macro->variadic() || macro->nopar() || !macro->params().empty())
3147  ++pos2;
3148 
3149  // Remove old limits
3150  for (std::map<const PreprocessorMacro *, std::size_t>::iterator iter = limits.begin();
3151  iter != limits.end();) {
3152  if ((line.length() - pos1) < iter->second) {
3153  // We have gone past this limit, so just delete it
3154  limits.erase(iter++);
3155  } else {
3156  ++iter;
3157  }
3158  }
3159 
3160  // don't allow this macro to be expanded again before pos2
3161  limits[macro] = line.length() - pos2;
3162 
3163  // erase macro
3164  line.erase(pos1, pos2 - pos1);
3165 
3166  // Don't glue this macro into variable or number after it
3167  if (!line.empty() && (std::isalnum((unsigned char)line[pos1]) || line[pos1] == '_'))
3168  macrocode.append(1,' ');
3169 
3170  // insert macrochar before each symbol/nr/operator
3171  bool str = false;
3172  bool chr = false;
3173  for (std::size_t i = 0U; i < macrocode.size(); ++i) {
3174  if (macrocode[i] == '\\') {
3175  i++;
3176  continue;
3177  } else if (macrocode[i] == '\"')
3178  str = !str;
3179  else if (macrocode[i] == '\'')
3180  chr = !chr;
3181  else if (str || chr)
3182  continue;
3183  else if (macrocode[i] == '.') { // 5. / .5
3184  if ((i > 0U && std::isdigit((unsigned char)macrocode[i-1])) ||
3185  (i+1 < macrocode.size() && std::isdigit((unsigned char)macrocode[i+1]))) {
3186  if (i > 0U && !std::isdigit((unsigned char)macrocode[i-1])) {
3187  macrocode.insert(i, 1U, macroChar);
3188  i++;
3189  }
3190  i++;
3191  if (i<macrocode.size() && std::isdigit((unsigned char)macrocode[i]))
3192  i++;
3193  if (i+1U < macrocode.size() &&
3194  (macrocode[i] == 'e' || macrocode[i] == 'E') &&
3195  (macrocode[i+1] == '+' || macrocode[i+1] == '-')) {
3196  i+=2;
3197  }
3198  }
3199  } else if (std::isalnum((unsigned char)macrocode[i]) || macrocode[i] == '_') {
3200  if ((i > 0U) &&
3201  (!std::isalnum((unsigned char)macrocode[i-1])) &&
3202  (macrocode[i-1] != '_') &&
3203  (macrocode[i-1] != macroChar)) {
3204  macrocode.insert(i, 1U, macroChar);
3205  }
3206 
3207  // 1e-7 / 1e+7
3208  if (i+3U < macrocode.size() &&
3209  (std::isdigit((unsigned char)macrocode[i]) || macrocode[i]=='.') &&
3210  (macrocode[i+1] == 'e' || macrocode[i+1] == 'E') &&
3211  (macrocode[i+2] == '-' || macrocode[i+2] == '+') &&
3212  std::isdigit((unsigned char)macrocode[i+3])) {
3213  i += 3U;
3214  }
3215 
3216  // 1.f / 1.e7
3217  if (i+2U < macrocode.size() &&
3218  std::isdigit((unsigned char)macrocode[i]) &&
3219  macrocode[i+1] == '.' &&
3220  std::isalpha((unsigned char)macrocode[i+2])) {
3221  i += 2U;
3222  if (i+2U < macrocode.size() &&
3223  (macrocode[i+0] == 'e' || macrocode[i+0] == 'E') &&
3224  (macrocode[i+1] == '-' || macrocode[i+1] == '+') &&
3225  std::isdigit((unsigned char)macrocode[i+2])) {
3226  i += 2U;
3227  }
3228  }
3229  }
3230  }
3231  line.insert(pos1, macroChar + macrocode);
3232 
3233  // position = start position.
3234  pos = pos1;
3235  }
3236  }
3237  }
3238 
3239  // the line has been processed in various ways. Now add it to the output stream
3240  ostr << line;
3241 
3242  // update linenr
3243  for (std::string::size_type p = 0; p < line.length(); ++p) {
3244  if (line[p] == '\n')
3245  ++linenr;
3246  }
3247  }
3248 
3249  for (std::map<std::string, PreprocessorMacro *>::iterator it = macros.begin(); it != macros.end(); ++it)
3250  delete it->second;
3251  macros.clear();
3252 
3253  return ostr.str();
3254 }
3255 
3256 
3257 void Preprocessor::getErrorMessages(ErrorLogger *errorLogger, const Settings *settings)
3258 {
3259  Settings settings2(*settings);
3260  Preprocessor preprocessor(&settings2, errorLogger);
3261  settings2.checkConfiguration=true;
3262  preprocessor.missingInclude("", 1, "", UserHeader);
3263  preprocessor.missingInclude("", 1, "", SystemHeader);
3264  preprocessor.validateCfgError("X", "X");
3265  preprocessor.error("", 1, "#error message"); // #error ..
3266 }