Revert "bump simplecpp"

This reverts commit bba31be87a.
This commit is contained in:
Daniel Marjamäki 2022-03-21 19:11:26 +01:00
parent bba31be87a
commit b6fa9bb5aa
2 changed files with 169 additions and 362 deletions

View File

@ -1,6 +1,6 @@
/* /*
* simplecpp - A simple and high-fidelity C/C++ preprocessor library * simplecpp - A simple and high-fidelity C/C++ preprocessor library
* Copyright (C) 2016-2022 Daniel Marjamäki. * Copyright (C) 2016 Daniel Marjamäki.
* *
* This library is free software: you can redistribute it and/or * This library is free software: you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public * modify it under the terms of the GNU Lesser General Public
@ -24,18 +24,16 @@
#include <algorithm> #include <algorithm>
#include <climits> #include <climits>
#include <cstdlib>
#include <cstring> #include <cstring>
#include <ctime>
#include <exception> #include <exception>
#include <fstream> #include <fstream> // IWYU pragma: keep
#include <iostream> #include <iostream>
#include <limits> #include <limits>
#include <sstream> #include <sstream> // IWYU pragma: keep
#include <stack> #include <stack>
#include <stdexcept> #include <stdexcept>
#if __cplusplus >= 201103L #include <type_traits>
#include <unordered_map>
#endif
#include <utility> #include <utility>
#ifdef SIMPLECPP_WINDOWS #ifdef SIMPLECPP_WINDOWS
@ -44,10 +42,6 @@
#undef TRUE #undef TRUE
#endif #endif
#if (__cplusplus < 201103L) && !defined(__APPLE__)
#define nullptr NULL
#endif
static bool isHex(const std::string &s) static bool isHex(const std::string &s)
{ {
return s.size()>2 && (s.compare(0,2,"0x")==0 || s.compare(0,2,"0X")==0); return s.size()>2 && (s.compare(0,2,"0x")==0 || s.compare(0,2,"0X")==0);
@ -58,17 +52,6 @@ static bool isOct(const std::string &s)
return s.size()>1 && (s[0]=='0') && (s[1] >= '0') && (s[1] < '8'); return s.size()>1 && (s[0]=='0') && (s[1] >= '0') && (s[1] < '8');
} }
static bool isStringLiteral(const std::string &s)
{
return s.size() > 1 && (s[0]=='\"') && (*s.rbegin()=='\"');
}
static bool isCharLiteral(const std::string &s)
{
// char literal patterns can include 'a', '\t', '\000', '\xff', 'abcd', and maybe ''
// This only checks for the surrounding '' but doesn't parse the content.
return s.size() > 1 && (s[0]=='\'') && (*s.rbegin()=='\'');
}
static const simplecpp::TokenString DEFINE("define"); static const simplecpp::TokenString DEFINE("define");
static const simplecpp::TokenString UNDEF("undef"); static const simplecpp::TokenString UNDEF("undef");
@ -169,7 +152,7 @@ const std::string simplecpp::Location::emptyFileName;
void simplecpp::Location::adjust(const std::string &str) void simplecpp::Location::adjust(const std::string &str)
{ {
if (strpbrk(str.c_str(), "\r\n") == nullptr) { if (str.find_first_of("\r\n") == std::string::npos) {
col += str.size(); col += str.size();
return; return;
} }
@ -187,17 +170,17 @@ void simplecpp::Location::adjust(const std::string &str)
bool simplecpp::Token::isOneOf(const char ops[]) const bool simplecpp::Token::isOneOf(const char ops[]) const
{ {
return (op != '\0') && (std::strchr(ops, op) != nullptr); return (op != '\0') && (std::strchr(ops, op) != NULL);
} }
bool simplecpp::Token::startsWithOneOf(const char c[]) const bool simplecpp::Token::startsWithOneOf(const char c[]) const
{ {
return std::strchr(c, string[0]) != nullptr; return std::strchr(c, string[0]) != NULL;
} }
bool simplecpp::Token::endsWithOneOf(const char c[]) const bool simplecpp::Token::endsWithOneOf(const char c[]) const
{ {
return std::strchr(c, string[string.size() - 1U]) != nullptr; return std::strchr(c, string[string.size() - 1U]) != NULL;
} }
void simplecpp::Token::printAll() const void simplecpp::Token::printAll() const
@ -225,21 +208,21 @@ void simplecpp::Token::printOut() const
std::cout << std::endl; std::cout << std::endl;
} }
simplecpp::TokenList::TokenList(std::vector<std::string> &filenames) : frontToken(nullptr), backToken(nullptr), files(filenames) {} simplecpp::TokenList::TokenList(std::vector<std::string> &filenames) : frontToken(NULL), backToken(NULL), files(filenames) {}
simplecpp::TokenList::TokenList(std::istream &istr, std::vector<std::string> &filenames, const std::string &filename, OutputList *outputList) simplecpp::TokenList::TokenList(std::istream &istr, std::vector<std::string> &filenames, const std::string &filename, OutputList *outputList)
: frontToken(nullptr), backToken(nullptr), files(filenames) : frontToken(NULL), backToken(NULL), files(filenames)
{ {
readfile(istr,filename,outputList); readfile(istr,filename,outputList);
} }
simplecpp::TokenList::TokenList(const TokenList &other) : frontToken(nullptr), backToken(nullptr), files(other.files) simplecpp::TokenList::TokenList(const TokenList &other) : frontToken(NULL), backToken(NULL), files(other.files)
{ {
*this = other; *this = other;
} }
#if __cplusplus >= 201103L #if __cplusplus >= 201103L
simplecpp::TokenList::TokenList(TokenList &&other) : TokenList(other) simplecpp::TokenList::TokenList(TokenList &&other) : frontToken(NULL), backToken(NULL), files(other.files)
{ {
*this = std::move(other); *this = std::move(other);
} }
@ -254,7 +237,6 @@ simplecpp::TokenList &simplecpp::TokenList::operator=(const TokenList &other)
{ {
if (this != &other) { if (this != &other) {
clear(); clear();
files = other.files;
for (const Token *tok = other.cfront(); tok; tok = tok->next) for (const Token *tok = other.cfront(); tok; tok = tok->next)
push_back(new Token(*tok)); push_back(new Token(*tok));
sizeOfType = other.sizeOfType; sizeOfType = other.sizeOfType;
@ -267,11 +249,10 @@ simplecpp::TokenList &simplecpp::TokenList::operator=(TokenList &&other)
{ {
if (this != &other) { if (this != &other) {
clear(); clear();
frontToken = other.frontToken;
other.frontToken = nullptr;
backToken = other.backToken; backToken = other.backToken;
other.backToken = nullptr; other.backToken = NULL;
files = other.files; frontToken = other.frontToken;
other.frontToken = NULL;
sizeOfType = std::move(other.sizeOfType); sizeOfType = std::move(other.sizeOfType);
} }
return *this; return *this;
@ -280,7 +261,7 @@ simplecpp::TokenList &simplecpp::TokenList::operator=(TokenList &&other)
void simplecpp::TokenList::clear() void simplecpp::TokenList::clear()
{ {
backToken = nullptr; backToken = NULL;
while (frontToken) { while (frontToken) {
Token *next = frontToken->next; Token *next = frontToken->next;
delete frontToken; delete frontToken;
@ -332,20 +313,20 @@ std::string simplecpp::TokenList::stringify() const
static unsigned char readChar(std::istream &istr, unsigned int bom) static unsigned char readChar(std::istream &istr, unsigned int bom)
{ {
unsigned char ch = static_cast<unsigned char>(istr.get()); unsigned char ch = (unsigned char)istr.get();
// For UTF-16 encoded files the BOM is 0xfeff/0xfffe. If the // For UTF-16 encoded files the BOM is 0xfeff/0xfffe. If the
// character is non-ASCII character then replace it with 0xff // character is non-ASCII character then replace it with 0xff
if (bom == 0xfeff || bom == 0xfffe) { if (bom == 0xfeff || bom == 0xfffe) {
const unsigned char ch2 = static_cast<unsigned char>(istr.get()); const unsigned char ch2 = (unsigned char)istr.get();
const int ch16 = (bom == 0xfeff) ? (ch<<8 | ch2) : (ch2<<8 | ch); const int ch16 = (bom == 0xfeff) ? (ch<<8 | ch2) : (ch2<<8 | ch);
ch = static_cast<unsigned char>(((ch16 >= 0x80) ? 0xff : ch16)); ch = (unsigned char)((ch16 >= 0x80) ? 0xff : ch16);
} }
// Handling of newlines.. // Handling of newlines..
if (ch == '\r') { if (ch == '\r') {
ch = '\n'; ch = '\n';
if (bom == 0 && static_cast<char>(istr.peek()) == '\n') if (bom == 0 && (char)istr.peek() == '\n')
(void)istr.get(); (void)istr.get();
else if (bom == 0xfeff || bom == 0xfffe) { else if (bom == 0xfeff || bom == 0xfffe) {
int c1 = istr.get(); int c1 = istr.get();
@ -363,16 +344,16 @@ static unsigned char readChar(std::istream &istr, unsigned int bom)
static unsigned char peekChar(std::istream &istr, unsigned int bom) static unsigned char peekChar(std::istream &istr, unsigned int bom)
{ {
unsigned char ch = static_cast<unsigned char>(istr.peek()); unsigned char ch = (unsigned char)istr.peek();
// For UTF-16 encoded files the BOM is 0xfeff/0xfffe. If the // For UTF-16 encoded files the BOM is 0xfeff/0xfffe. If the
// character is non-ASCII character then replace it with 0xff // character is non-ASCII character then replace it with 0xff
if (bom == 0xfeff || bom == 0xfffe) { if (bom == 0xfeff || bom == 0xfffe) {
(void)istr.get(); (void)istr.get();
const unsigned char ch2 = static_cast<unsigned char>(istr.peek()); const unsigned char ch2 = (unsigned char)istr.peek();
istr.unget(); istr.unget();
const int ch16 = (bom == 0xfeff) ? (ch<<8 | ch2) : (ch2<<8 | ch); const int ch16 = (bom == 0xfeff) ? (ch<<8 | ch2) : (ch2<<8 | ch);
ch = static_cast<unsigned char>(((ch16 >= 0x80) ? 0xff : ch16)); ch = (unsigned char)((ch16 >= 0x80) ? 0xff : ch16);
} }
// Handling of newlines.. // Handling of newlines..
@ -395,9 +376,9 @@ static unsigned short getAndSkipBOM(std::istream &istr)
// The UTF-16 BOM is 0xfffe or 0xfeff. // The UTF-16 BOM is 0xfffe or 0xfeff.
if (ch1 >= 0xfe) { if (ch1 >= 0xfe) {
unsigned short bom = (static_cast<unsigned char>(istr.get()) << 8); unsigned short bom = ((unsigned char)istr.get() << 8);
if (istr.peek() >= 0xfe) if (istr.peek() >= 0xfe)
return bom | static_cast<unsigned char>(istr.get()); return bom | (unsigned char)istr.get();
istr.unget(); istr.unget();
return 0; return 0;
} }
@ -469,15 +450,13 @@ void simplecpp::TokenList::lineDirective(unsigned int fileIndex, unsigned int li
} }
} }
static const std::string COMMENT_END("*/");
void simplecpp::TokenList::readfile(std::istream &istr, const std::string &filename, OutputList *outputList) void simplecpp::TokenList::readfile(std::istream &istr, const std::string &filename, OutputList *outputList)
{ {
std::stack<simplecpp::Location> loc; std::stack<simplecpp::Location> loc;
unsigned int multiline = 0U; unsigned int multiline = 0U;
const Token *oldLastToken = nullptr; const Token *oldLastToken = NULL;
const unsigned short bom = getAndSkipBOM(istr); const unsigned short bom = getAndSkipBOM(istr);
@ -498,7 +477,7 @@ void simplecpp::TokenList::readfile(std::istream &istr, const std::string &filen
err.type = simplecpp::Output::UNHANDLED_CHAR_ERROR; err.type = simplecpp::Output::UNHANDLED_CHAR_ERROR;
err.location = location; err.location = location;
std::ostringstream s; std::ostringstream s;
s << static_cast<int>(ch); s << (int)ch;
err.msg = "The code contains unhandled character(s) (character code=" + s.str() + "). Neither unicode nor extended ascii is supported."; err.msg = "The code contains unhandled character(s) (character code=" + s.str() + "). Neither unicode nor extended ascii is supported.";
outputList->push_back(err); outputList->push_back(err);
} }
@ -521,8 +500,6 @@ void simplecpp::TokenList::readfile(std::istream &istr, const std::string &filen
if (oldLastToken != cback()) { if (oldLastToken != cback()) {
oldLastToken = cback(); oldLastToken = cback();
if (!isLastLinePreprocessor())
continue;
const std::string lastline(lastLine()); const std::string lastline(lastLine());
if (lastline == "# file %str%") { if (lastline == "# file %str%") {
const Token *strtok = cback(); const Token *strtok = cback();
@ -613,7 +590,7 @@ void simplecpp::TokenList::readfile(std::istream &istr, const std::string &filen
ch = readChar(istr,bom); ch = readChar(istr,bom);
while (istr.good()) { while (istr.good()) {
currentToken += ch; currentToken += ch;
if (currentToken.size() >= 4U && endsWith(currentToken, COMMENT_END)) if (currentToken.size() >= 4U && endsWith(currentToken, "*/"))
break; break;
ch = readChar(istr,bom); ch = readChar(istr,bom);
} }
@ -1217,42 +1194,19 @@ std::string simplecpp::TokenList::lastLine(int maxsize) const
{ {
std::string ret; std::string ret;
int count = 0; int count = 0;
for (const Token *tok = cback(); ; tok = tok->previous) { for (const Token *tok = cback(); sameline(tok,cback()); tok = tok->previous) {
if (!sameline(tok, cback())) {
break;
}
if (tok->comment) if (tok->comment)
continue; continue;
if (++count > maxsize)
return "";
if (!ret.empty()) if (!ret.empty())
ret.insert(0, 1, ' '); ret.insert(0, 1, ' ');
if (tok->str()[0] == '\"') ret.insert(0, tok->str()[0] == '\"' ? std::string("%str%")
ret.insert(0, "%str%"); : tok->number ? std::string("%num%") : tok->str());
else if (tok->number) if (++count > maxsize)
ret.insert(0, "%num%"); return "";
else
ret.insert(0, tok->str());
} }
return ret; return ret;
} }
bool simplecpp::TokenList::isLastLinePreprocessor(int maxsize) const
{
const Token* prevTok = nullptr;
int count = 0;
for (const Token *tok = cback(); ; tok = tok->previous) {
if (!sameline(tok, cback()))
break;
if (tok->comment)
continue;
if (++count > maxsize)
return false;
prevTok = tok;
}
return prevTok && prevTok->str()[0] == '#';
}
unsigned int simplecpp::TokenList::fileIndex(const std::string &filename) unsigned int simplecpp::TokenList::fileIndex(const std::string &filename)
{ {
for (unsigned int i = 0; i < files.size(); ++i) { for (unsigned int i = 0; i < files.size(); ++i) {
@ -1265,18 +1219,11 @@ unsigned int simplecpp::TokenList::fileIndex(const std::string &filename)
namespace simplecpp { namespace simplecpp {
class Macro;
#if __cplusplus >= 201103L
using MacroMap = std::unordered_map<TokenString,Macro>;
#else
typedef std::map<TokenString,Macro> MacroMap;
#endif
class Macro { class Macro {
public: public:
explicit Macro(std::vector<std::string> &f) : nameTokDef(nullptr), variadic(false), valueToken(nullptr), endToken(nullptr), files(f), tokenListDefine(f), valueDefinedInCode_(false) {} explicit Macro(std::vector<std::string> &f) : nameTokDef(NULL), variadic(false), valueToken(NULL), endToken(NULL), files(f), tokenListDefine(f), valueDefinedInCode_(false) {}
Macro(const Token *tok, std::vector<std::string> &f) : nameTokDef(nullptr), files(f), tokenListDefine(f), valueDefinedInCode_(true) { Macro(const Token *tok, std::vector<std::string> &f) : nameTokDef(NULL), files(f), tokenListDefine(f), valueDefinedInCode_(true) {
if (sameline(tok->previous, tok)) if (sameline(tok->previous, tok))
throw std::runtime_error("bad macro syntax"); throw std::runtime_error("bad macro syntax");
if (tok->op != '#') if (tok->op != '#')
@ -1292,7 +1239,7 @@ namespace simplecpp {
throw std::runtime_error("bad macro syntax"); throw std::runtime_error("bad macro syntax");
} }
Macro(const std::string &name, const std::string &value, std::vector<std::string> &f) : nameTokDef(nullptr), files(f), tokenListDefine(f), valueDefinedInCode_(false) { Macro(const std::string &name, const std::string &value, std::vector<std::string> &f) : nameTokDef(NULL), files(f), tokenListDefine(f), valueDefinedInCode_(false) {
const std::string def(name + ' ' + value); const std::string def(name + ' ' + value);
std::istringstream istr(def); std::istringstream istr(def);
tokenListDefine.readfile(istr); tokenListDefine.readfile(istr);
@ -1300,22 +1247,20 @@ namespace simplecpp {
throw std::runtime_error("bad macro syntax. macroname=" + name + " value=" + value); throw std::runtime_error("bad macro syntax. macroname=" + name + " value=" + value);
} }
Macro(const Macro &other) : nameTokDef(nullptr), files(other.files), tokenListDefine(other.files), valueDefinedInCode_(other.valueDefinedInCode_) { Macro(const Macro &macro) : nameTokDef(NULL), files(macro.files), tokenListDefine(macro.files), valueDefinedInCode_(macro.valueDefinedInCode_) {
*this = other; *this = macro;
} }
Macro &operator=(const Macro &other) { void operator=(const Macro &macro) {
if (this != &other) { if (this != &macro) {
files = other.files; valueDefinedInCode_ = macro.valueDefinedInCode_;
valueDefinedInCode_ = other.valueDefinedInCode_; if (macro.tokenListDefine.empty())
if (other.tokenListDefine.empty()) parseDefine(macro.nameTokDef);
parseDefine(other.nameTokDef);
else { else {
tokenListDefine = other.tokenListDefine; tokenListDefine = macro.tokenListDefine;
parseDefine(tokenListDefine.cfront()); parseDefine(tokenListDefine.cfront());
} }
} }
return *this;
} }
bool valueDefinedInCode() const { bool valueDefinedInCode() const {
@ -1333,7 +1278,7 @@ namespace simplecpp {
*/ */
const Token * expand(TokenList * const output, const Token * expand(TokenList * const output,
const Token * rawtok, const Token * rawtok,
const MacroMap &macros, const std::map<TokenString,Macro> &macros,
std::vector<std::string> &inputFiles) const { std::vector<std::string> &inputFiles) const {
std::set<TokenString> expandedmacros; std::set<TokenString> expandedmacros;
@ -1387,7 +1332,7 @@ namespace simplecpp {
break; break;
if (output2.cfront() != output2.cback() && macro2tok->str() == this->name()) if (output2.cfront() != output2.cback() && macro2tok->str() == this->name())
break; break;
const MacroMap::const_iterator macro = macros.find(macro2tok->str()); const std::map<TokenString,Macro>::const_iterator macro = macros.find(macro2tok->str());
if (macro == macros.end() || !macro->second.functionLike()) if (macro == macros.end() || !macro->second.functionLike())
break; break;
TokenList rawtokens2(inputFiles); TokenList rawtokens2(inputFiles);
@ -1412,7 +1357,7 @@ namespace simplecpp {
} }
if (!rawtok2 || par != 1U) if (!rawtok2 || par != 1U)
break; break;
if (macro->second.expand(&output2, rawtok->location, rawtokens2.cfront(), macros, expandedmacros) != nullptr) if (macro->second.expand(&output2, rawtok->location, rawtokens2.cfront(), macros, expandedmacros) != NULL)
break; break;
rawtok = rawtok2->next; rawtok = rawtok2->next;
} }
@ -1446,8 +1391,8 @@ namespace simplecpp {
/** base class for errors */ /** base class for errors */
struct Error { struct Error {
Error(const Location &loc, const std::string &s) : location(loc), what(s) {} Error(const Location &loc, const std::string &s) : location(loc), what(s) {}
const Location location; Location location;
const std::string what; std::string what;
}; };
/** Struct that is thrown when macro is expanded with wrong number of parameters */ /** Struct that is thrown when macro is expanded with wrong number of parameters */
@ -1457,28 +1402,11 @@ namespace simplecpp {
/** Struct that is thrown when there is invalid ## usage */ /** Struct that is thrown when there is invalid ## usage */
struct invalidHashHash : public Error { struct invalidHashHash : public Error {
static inline std::string format(const std::string &macroName, const std::string &message) { invalidHashHash(const Location &loc, const std::string &macroName) : Error(loc, "Invalid ## usage when expanding \'" + macroName + "\'.") {}
return "Invalid ## usage when expanding \'" + macroName + "\': " + message;
}
invalidHashHash(const Location &loc, const std::string &macroName, const std::string &message)
: Error(loc, format(macroName, message)) { }
static inline invalidHashHash unexpectedToken(const Location &loc, const std::string &macroName, const Token *tokenA) {
return invalidHashHash(loc, macroName, "Unexpected token '"+ tokenA->str()+"'");
}
static inline invalidHashHash cannotCombine(const Location &loc, const std::string &macroName, const Token *tokenA, const Token *tokenB) {
return invalidHashHash(loc, macroName, "Pasting '"+ tokenA->str()+ "' and '"+ tokenB->str() + "' yields an invalid token.");
}
static inline invalidHashHash unexpectedNewline(const Location &loc, const std::string &macroName) {
return invalidHashHash(loc, macroName, "Unexpected newline");
}
}; };
private: private:
/** Create new token where Token::macro is set for replaced tokens */ /** Create new token where Token::macro is set for replaced tokens */
Token *newMacroToken(const TokenString &str, const Location &loc, bool replaced, const Token *expandedFromToken=nullptr) const { Token *newMacroToken(const TokenString &str, const Location &loc, bool replaced, const Token *expandedFromToken=NULL) const {
Token *tok = new Token(str,loc); Token *tok = new Token(str,loc);
if (replaced) if (replaced)
tok->macro = nameTokDef->str(); tok->macro = nameTokDef->str();
@ -1491,7 +1419,7 @@ namespace simplecpp {
nameTokDef = nametoken; nameTokDef = nametoken;
variadic = false; variadic = false;
if (!nameTokDef) { if (!nameTokDef) {
valueToken = endToken = nullptr; valueToken = endToken = NULL;
args.clear(); args.clear();
return false; return false;
} }
@ -1515,17 +1443,17 @@ namespace simplecpp {
} }
if (!sameline(nametoken, argtok)) { if (!sameline(nametoken, argtok)) {
endToken = argtok ? argtok->previous : argtok; endToken = argtok ? argtok->previous : argtok;
valueToken = nullptr; valueToken = NULL;
return false; return false;
} }
valueToken = argtok ? argtok->next : nullptr; valueToken = argtok ? argtok->next : NULL;
} else { } else {
args.clear(); args.clear();
valueToken = nameTokDef->next; valueToken = nameTokDef->next;
} }
if (!sameline(valueToken, nameTokDef)) if (!sameline(valueToken, nameTokDef))
valueToken = nullptr; valueToken = NULL;
endToken = valueToken; endToken = valueToken;
while (sameline(endToken, nameTokDef)) while (sameline(endToken, nameTokDef))
endToken = endToken->next; endToken = endToken->next;
@ -1549,7 +1477,7 @@ namespace simplecpp {
std::vector<const Token *> parametertokens; std::vector<const Token *> parametertokens;
parametertokens.push_back(nameTokInst->next); parametertokens.push_back(nameTokInst->next);
unsigned int par = 0U; unsigned int par = 0U;
for (const Token *tok = nameTokInst->next->next; calledInDefine ? sameline(tok, nameTokInst) : (tok != nullptr); tok = tok->next) { for (const Token *tok = nameTokInst->next->next; calledInDefine ? sameline(tok, nameTokInst) : (tok != NULL); tok = tok->next) {
if (tok->op == '(') if (tok->op == '(')
++par; ++par;
else if (tok->op == ')') { else if (tok->op == ')') {
@ -1567,11 +1495,11 @@ namespace simplecpp {
const Token *appendTokens(TokenList *tokens, const Token *appendTokens(TokenList *tokens,
const Location &rawloc, const Location &rawloc,
const Token * const lpar, const Token * const lpar,
const MacroMap &macros, const std::map<TokenString,Macro> &macros,
const std::set<TokenString> &expandedmacros, const std::set<TokenString> &expandedmacros,
const std::vector<const Token*> &parametertokens) const { const std::vector<const Token*> &parametertokens) const {
if (!lpar || lpar->op != '(') if (!lpar || lpar->op != '(')
return nullptr; return NULL;
unsigned int par = 0; unsigned int par = 0;
const Token *tok = lpar; const Token *tok = lpar;
while (sameline(lpar, tok)) { while (sameline(lpar, tok)) {
@ -1583,7 +1511,7 @@ namespace simplecpp {
} else { } else {
if (!expandArg(tokens, tok, rawloc, macros, expandedmacros, parametertokens)) { if (!expandArg(tokens, tok, rawloc, macros, expandedmacros, parametertokens)) {
bool expanded = false; bool expanded = false;
const MacroMap::const_iterator it = macros.find(tok->str()); const std::map<TokenString, Macro>::const_iterator it = macros.find(tok->str());
if (it != macros.end() && expandedmacros.find(tok->str()) == expandedmacros.end()) { if (it != macros.end() && expandedmacros.find(tok->str()) == expandedmacros.end()) {
const Macro &m = it->second; const Macro &m = it->second;
if (!m.functionLike()) { if (!m.functionLike()) {
@ -1610,10 +1538,10 @@ namespace simplecpp {
} }
for (Token *tok2 = tokens->front(); tok2; tok2 = tok2->next) for (Token *tok2 = tokens->front(); tok2; tok2 = tok2->next)
tok2->location = lpar->location; tok2->location = lpar->location;
return sameline(lpar,tok) ? tok : nullptr; return sameline(lpar,tok) ? tok : NULL;
} }
const Token * expand(TokenList * const output, const Location &loc, const Token * const nameTokInst, const MacroMap &macros, std::set<TokenString> expandedmacros, bool first=false) const { const Token * expand(TokenList * const output, const Location &loc, const Token * const nameTokInst, const std::map<TokenString,Macro> &macros, std::set<TokenString> expandedmacros, bool first=false) const {
if (!first) if (!first)
expandedmacros.insert(nameTokInst->str()); expandedmacros.insert(nameTokInst->str());
@ -1668,7 +1596,7 @@ namespace simplecpp {
} }
} }
const MacroMap::const_iterator m = macros.find("__COUNTER__"); const std::map<TokenString,Macro>::const_iterator m = macros.find("__COUNTER__");
if (!counter || m == macros.end()) if (!counter || m == macros.end())
parametertokens2.swap(parametertokens1); parametertokens2.swap(parametertokens1);
@ -1698,7 +1626,7 @@ namespace simplecpp {
// A##B => AB // A##B => AB
if (sameline(tok, tok->next) && tok->next && tok->next->op == '#' && tok->next->next && tok->next->next->op == '#') { if (sameline(tok, tok->next) && tok->next && tok->next->op == '#' && tok->next->next && tok->next->next->op == '#') {
if (!sameline(tok, tok->next->next->next)) if (!sameline(tok, tok->next->next->next))
throw invalidHashHash::unexpectedNewline(tok->location, name()); throw invalidHashHash(tok->location, name());
TokenList new_output(files); TokenList new_output(files);
if (!expandArg(&new_output, tok, parametertokens2)) if (!expandArg(&new_output, tok, parametertokens2))
output->push_back(newMacroToken(tok->str(), loc, isReplaced(expandedmacros), tok)); output->push_back(newMacroToken(tok->str(), loc, isReplaced(expandedmacros), tok));
@ -1759,7 +1687,7 @@ namespace simplecpp {
return functionLike() ? parametertokens2.back()->next : nameTokInst->next; return functionLike() ? parametertokens2.back()->next : nameTokInst->next;
} }
const Token *recursiveExpandToken(TokenList *output, TokenList &temp, const Location &loc, const Token *tok, const MacroMap &macros, const std::set<TokenString> &expandedmacros, const std::vector<const Token*> &parametertokens) const { const Token *recursiveExpandToken(TokenList *output, TokenList &temp, const Location &loc, const Token *tok, const std::map<TokenString,Macro> &macros, const std::set<TokenString> &expandedmacros, const std::vector<const Token*> &parametertokens) const {
if (!(temp.cback() && temp.cback()->name && tok->next && tok->next->op == '(')) { if (!(temp.cback() && temp.cback()->name && tok->next && tok->next->op == '(')) {
output->takeTokens(temp); output->takeTokens(temp);
return tok->next; return tok->next;
@ -1770,7 +1698,7 @@ namespace simplecpp {
return tok->next; return tok->next;
} }
const MacroMap::const_iterator it = macros.find(temp.cback()->str()); const std::map<TokenString, Macro>::const_iterator it = macros.find(temp.cback()->str());
if (it == macros.end() || expandedmacros.find(temp.cback()->str()) != expandedmacros.end()) { if (it == macros.end() || expandedmacros.find(temp.cback()->str()) != expandedmacros.end()) {
output->takeTokens(temp); output->takeTokens(temp);
return tok->next; return tok->next;
@ -1794,7 +1722,7 @@ namespace simplecpp {
return tok2->next; return tok2->next;
} }
const Token *expandToken(TokenList *output, const Location &loc, const Token *tok, const MacroMap &macros, const std::set<TokenString> &expandedmacros, const std::vector<const Token*> &parametertokens) const { const Token *expandToken(TokenList *output, const Location &loc, const Token *tok, const std::map<TokenString,Macro> &macros, const std::set<TokenString> &expandedmacros, const std::vector<const Token*> &parametertokens) const {
// Not name.. // Not name..
if (!tok->name) { if (!tok->name) {
output->push_back(newMacroToken(tok->str(), loc, true, tok)); output->push_back(newMacroToken(tok->str(), loc, true, tok));
@ -1809,7 +1737,7 @@ namespace simplecpp {
} }
// Macro.. // Macro..
const MacroMap::const_iterator it = macros.find(tok->str()); const std::map<TokenString, Macro>::const_iterator it = macros.find(tok->str());
if (it != macros.end() && expandedmacros.find(tok->str()) == expandedmacros.end()) { if (it != macros.end() && expandedmacros.find(tok->str()) == expandedmacros.end()) {
std::set<std::string> expandedmacros2(expandedmacros); std::set<std::string> expandedmacros2(expandedmacros);
expandedmacros2.insert(tok->str()); expandedmacros2.insert(tok->str());
@ -1838,10 +1766,10 @@ namespace simplecpp {
else if (tok->str() == DEFINED) { else if (tok->str() == DEFINED) {
const Token *tok2 = tok->next; const Token *tok2 = tok->next;
const Token *tok3 = tok2 ? tok2->next : nullptr; const Token *tok3 = tok2 ? tok2->next : NULL;
const Token *tok4 = tok3 ? tok3->next : nullptr; const Token *tok4 = tok3 ? tok3->next : NULL;
const Token *defToken = nullptr; const Token *defToken = NULL;
const Token *lastToken = nullptr; const Token *lastToken = NULL;
if (sameline(tok, tok4) && tok2->op == '(' && tok3->name && tok4->op == ')') { if (sameline(tok, tok4) && tok2->op == '(' && tok3->name && tok4->op == ')') {
defToken = tok3; defToken = tok3;
lastToken = tok4; lastToken = tok4;
@ -1888,7 +1816,7 @@ namespace simplecpp {
return true; return true;
} }
bool expandArg(TokenList *output, const Token *tok, const Location &loc, const MacroMap &macros, const std::set<TokenString> &expandedmacros, const std::vector<const Token*> &parametertokens) const { bool expandArg(TokenList *output, const Token *tok, const Location &loc, const std::map<TokenString, Macro> &macros, const std::set<TokenString> &expandedmacros, const std::vector<const Token*> &parametertokens) const {
if (!tok->name) if (!tok->name)
return false; return false;
const unsigned int argnr = getArgNum(tok->str()); const unsigned int argnr = getArgNum(tok->str());
@ -1897,7 +1825,7 @@ namespace simplecpp {
if (variadic && argnr + 1U >= parametertokens.size()) // empty variadic parameter if (variadic && argnr + 1U >= parametertokens.size()) // empty variadic parameter
return true; return true;
for (const Token *partok = parametertokens[argnr]->next; partok != parametertokens[argnr + 1U];) { for (const Token *partok = parametertokens[argnr]->next; partok != parametertokens[argnr + 1U];) {
const MacroMap::const_iterator it = macros.find(partok->str()); const std::map<TokenString, Macro>::const_iterator it = macros.find(partok->str());
if (it != macros.end() && !partok->isExpandedFrom(&it->second) && (partok->str() == name() || expandedmacros.find(partok->str()) == expandedmacros.end())) if (it != macros.end() && !partok->isExpandedFrom(&it->second) && (partok->str() == name() || expandedmacros.find(partok->str()) == expandedmacros.end()))
partok = it->second.expand(output, loc, partok, macros, expandedmacros); partok = it->second.expand(output, loc, partok, macros, expandedmacros);
else { else {
@ -1919,7 +1847,7 @@ namespace simplecpp {
* @param parametertokens parameters given when expanding this macro * @param parametertokens parameters given when expanding this macro
* @return token after the X * @return token after the X
*/ */
const Token *expandHash(TokenList *output, const Location &loc, const Token *tok, const MacroMap &macros, const std::set<TokenString> &expandedmacros, const std::vector<const Token*> &parametertokens) const { const Token *expandHash(TokenList *output, const Location &loc, const Token *tok, const std::map<TokenString, Macro> &macros, const std::set<TokenString> &expandedmacros, const std::vector<const Token*> &parametertokens) const {
TokenList tokenListHash(files); TokenList tokenListHash(files);
tok = expandToken(&tokenListHash, loc, tok->next, macros, expandedmacros, parametertokens); tok = expandToken(&tokenListHash, loc, tok->next, macros, expandedmacros, parametertokens);
std::ostringstream ostr; std::ostringstream ostr;
@ -1942,93 +1870,74 @@ namespace simplecpp {
* @param parametertokens parameters given when expanding this macro * @param parametertokens parameters given when expanding this macro
* @return token after B * @return token after B
*/ */
const Token *expandHashHash(TokenList *output, const Location &loc, const Token *tok, const MacroMap &macros, const std::set<TokenString> &expandedmacros, const std::vector<const Token*> &parametertokens) const { const Token *expandHashHash(TokenList *output, const Location &loc, const Token *tok, const std::map<TokenString, Macro> &macros, const std::set<TokenString> &expandedmacros, const std::vector<const Token*> &parametertokens) const {
Token *A = output->back(); Token *A = output->back();
if (!A) if (!A)
throw invalidHashHash(tok->location, name(), "Missing first argument"); throw invalidHashHash(tok->location, name());
if (!sameline(tok, tok->next) || !sameline(tok, tok->next->next)) if (!sameline(tok, tok->next) || !sameline(tok, tok->next->next))
throw invalidHashHash::unexpectedNewline(tok->location, name()); throw invalidHashHash(tok->location, name());
bool canBeConcatenatedWithEqual = A->isOneOf("+-*/%&|^") || A->str() == "<<" || A->str() == ">>"; bool canBeConcatenatedWithEqual = A->isOneOf("+-*/%&|^") || A->str() == "<<" || A->str() == ">>";
bool canBeConcatenatedStringOrChar = isStringLiteral(A->str()) || isCharLiteral(A->str()); if (!A->name && !A->number && A->op != ',' && !A->str().empty() && !canBeConcatenatedWithEqual)
if (!A->name && !A->number && A->op != ',' && !A->str().empty() && !canBeConcatenatedWithEqual && !canBeConcatenatedStringOrChar) throw invalidHashHash(tok->location, name());
throw invalidHashHash::unexpectedToken(tok->location, name(), A);
Token *B = tok->next->next; Token *B = tok->next->next;
if (!B->name && !B->number && B->op && !B->isOneOf("#=")) if (!B->name && !B->number && B->op && !B->isOneOf("#="))
throw invalidHashHash::unexpectedToken(tok->location, name(), B); throw invalidHashHash(tok->location, name());
if ((canBeConcatenatedWithEqual && B->op != '=') || if ((canBeConcatenatedWithEqual && B->op != '=') ||
(!canBeConcatenatedWithEqual && B->op == '=')) (!canBeConcatenatedWithEqual && B->op == '='))
throw invalidHashHash::cannotCombine(tok->location, name(), A, B); throw invalidHashHash(tok->location, name());
// Superficial check; more in-depth would in theory be possible _after_ expandArg std::string strAB;
if (canBeConcatenatedStringOrChar && (B->number || !B->name))
throw invalidHashHash::cannotCombine(tok->location, name(), A, B); const bool varargs = variadic && args.size() >= 1U && B->str() == args[args.size()-1U];
TokenList tokensB(files); TokenList tokensB(files);
const Token *nextTok = B->next; if (expandArg(&tokensB, B, parametertokens)) {
if (tokensB.empty())
if (canBeConcatenatedStringOrChar) { strAB = A->str();
// It seems clearer to handle this case separately even though the code is similar-ish, but we don't want to merge here. else if (varargs && A->op == ',') {
// TODO The question is whether the ## or varargs may still apply, and how to provoke? strAB = ",";
if (expandArg(&tokensB, B, parametertokens)) {
for (Token *b = tokensB.front(); b; b = b->next)
b->location = loc;
} else { } else {
tokensB.push_back(new Token(*B)); strAB = A->str() + tokensB.cfront()->str();
tokensB.back()->location = loc; tokensB.deleteToken(tokensB.front());
} }
output->takeTokens(tokensB);
} else { } else {
std::string strAB; strAB = A->str() + B->str();
}
const bool varargs = variadic && args.size() >= 1U && B->str() == args[args.size()-1U]; const Token *nextTok = B->next;
if (varargs && tokensB.empty() && tok->previous->str() == ",")
if (expandArg(&tokensB, B, parametertokens)) { output->deleteToken(A);
if (tokensB.empty()) else if (strAB != "," && macros.find(strAB) == macros.end()) {
strAB = A->str(); A->setstr(strAB);
else if (varargs && A->op == ',') { for (Token *b = tokensB.front(); b; b = b->next)
strAB = ","; b->location = loc;
} else { output->takeTokens(tokensB);
strAB = A->str() + tokensB.cfront()->str(); } else if (nextTok->op == '#' && nextTok->next->op == '#') {
tokensB.deleteToken(tokensB.front()); TokenList output2(files);
output2.push_back(new Token(strAB, tok->location));
nextTok = expandHashHash(&output2, loc, nextTok, macros, expandedmacros, parametertokens);
output->deleteToken(A);
output->takeTokens(output2);
} else {
output->deleteToken(A);
TokenList tokens(files);
tokens.push_back(new Token(strAB, tok->location));
// for function like macros, push the (...)
if (tokensB.empty() && sameline(B,B->next) && B->next->op=='(') {
const std::map<TokenString,Macro>::const_iterator it = macros.find(strAB);
if (it != macros.end() && expandedmacros.find(strAB) == expandedmacros.end() && it->second.functionLike()) {
const Token *tok2 = appendTokens(&tokens, loc, B->next, macros, expandedmacros, parametertokens);
if (tok2)
nextTok = tok2->next;
} }
} else {
strAB = A->str() + B->str();
}
if (varargs && tokensB.empty() && tok->previous->str() == ",")
output->deleteToken(A);
else if (strAB != "," && macros.find(strAB) == macros.end()) {
A->setstr(strAB);
for (Token *b = tokensB.front(); b; b = b->next)
b->location = loc;
output->takeTokens(tokensB);
} else if (nextTok->op == '#' && nextTok->next->op == '#') {
TokenList output2(files);
output2.push_back(new Token(strAB, tok->location));
nextTok = expandHashHash(&output2, loc, nextTok, macros, expandedmacros, parametertokens);
output->deleteToken(A);
output->takeTokens(output2);
} else {
output->deleteToken(A);
TokenList tokens(files);
tokens.push_back(new Token(strAB, tok->location));
// for function like macros, push the (...)
if (tokensB.empty() && sameline(B,B->next) && B->next->op=='(') {
const MacroMap::const_iterator it = macros.find(strAB);
if (it != macros.end() && expandedmacros.find(strAB) == expandedmacros.end() && it->second.functionLike()) {
const Token *tok2 = appendTokens(&tokens, loc, B->next, macros, expandedmacros, parametertokens);
if (tok2)
nextTok = tok2->next;
}
}
expandToken(output, loc, tokens.cfront(), macros, expandedmacros, parametertokens);
for (Token *b = tokensB.front(); b; b = b->next)
b->location = loc;
output->takeTokens(tokensB);
} }
expandToken(output, loc, tokens.cfront(), macros, expandedmacros, parametertokens);
for (Token *b = tokensB.front(); b; b = b->next)
b->location = loc;
output->takeTokens(tokensB);
} }
return nextTok; return nextTok;
@ -2311,19 +2220,14 @@ namespace simplecpp {
continue; continue;
} }
// get previous subpath // get previous subpath
std::string::size_type pos1 = path.rfind('/', pos - 1U); const std::string::size_type pos1 = path.rfind('/', pos - 1U) + 1U;
if (pos1 == std::string::npos) { const std::string previousSubPath = path.substr(pos1, pos-pos1);
pos1 = 0;
} else {
pos1 += 1U;
}
const std::string previousSubPath = path.substr(pos1, pos - pos1);
if (previousSubPath == "..") { if (previousSubPath == "..") {
// don't simplify // don't simplify
++pos; ++pos;
} else { } else {
// remove previous subpath and ".." // remove previous subpath and ".."
path.erase(pos1, pos - pos1 + 4); path.erase(pos1,pos-pos1+4);
if (path.empty()) if (path.empty())
path = "."; path = ".";
// update pos // update pos
@ -2719,7 +2623,7 @@ static NonExistingFilesCache nonExistingFilesCache;
#endif #endif
static std::string openHeader(std::ifstream &f, const std::string &path) static std::string _openHeader(std::ifstream &f, const std::string &path)
{ {
#ifdef SIMPLECPP_WINDOWS #ifdef SIMPLECPP_WINDOWS
std::string simplePath = simplecpp::simplifyPath(path); std::string simplePath = simplecpp::simplifyPath(path);
@ -2748,7 +2652,7 @@ static std::string getRelativeFileName(const std::string &sourcefile, const std:
static std::string openHeaderRelative(std::ifstream &f, const std::string &sourcefile, const std::string &header) static std::string openHeaderRelative(std::ifstream &f, const std::string &sourcefile, const std::string &header)
{ {
return openHeader(f, getRelativeFileName(sourcefile, header)); return _openHeader(f, getRelativeFileName(sourcefile, header));
} }
static std::string getIncludePathFileName(const std::string &includePath, const std::string &header) static std::string getIncludePathFileName(const std::string &includePath, const std::string &header)
@ -2762,7 +2666,7 @@ static std::string getIncludePathFileName(const std::string &includePath, const
static std::string openHeaderIncludePath(std::ifstream &f, const simplecpp::DUI &dui, const std::string &header) static std::string openHeaderIncludePath(std::ifstream &f, const simplecpp::DUI &dui, const std::string &header)
{ {
for (std::list<std::string>::const_iterator it = dui.includePaths.begin(); it != dui.includePaths.end(); ++it) { for (std::list<std::string>::const_iterator it = dui.includePaths.begin(); it != dui.includePaths.end(); ++it) {
std::string simplePath = openHeader(f, getIncludePathFileName(*it, header)); std::string simplePath = _openHeader(f, getIncludePathFileName(*it, header));
if (!simplePath.empty()) if (!simplePath.empty())
return simplePath; return simplePath;
} }
@ -2772,7 +2676,7 @@ static std::string openHeaderIncludePath(std::ifstream &f, const simplecpp::DUI
static std::string openHeader(std::ifstream &f, const simplecpp::DUI &dui, const std::string &sourcefile, const std::string &header, bool systemheader) static std::string openHeader(std::ifstream &f, const simplecpp::DUI &dui, const std::string &sourcefile, const std::string &header, bool systemheader)
{ {
if (isAbsolutePath(header)) if (isAbsolutePath(header))
return openHeader(f, header); return _openHeader(f, header);
std::string ret; std::string ret;
@ -2850,8 +2754,8 @@ std::map<std::string, simplecpp::TokenList*> simplecpp::load(const simplecpp::To
filelist.push_back(tokenlist->front()); filelist.push_back(tokenlist->front());
} }
for (const Token *rawtok = rawtokens.cfront(); rawtok || !filelist.empty(); rawtok = rawtok ? rawtok->next : nullptr) { for (const Token *rawtok = rawtokens.cfront(); rawtok || !filelist.empty(); rawtok = rawtok ? rawtok->next : NULL) {
if (rawtok == nullptr) { if (rawtok == NULL) {
rawtok = filelist.back(); rawtok = filelist.back();
filelist.pop_back(); filelist.pop_back();
} }
@ -2888,10 +2792,10 @@ std::map<std::string, simplecpp::TokenList*> simplecpp::load(const simplecpp::To
return ret; return ret;
} }
static bool preprocessToken(simplecpp::TokenList &output, const simplecpp::Token **tok1, simplecpp::MacroMap &macros, std::vector<std::string> &files, simplecpp::OutputList *outputList) static bool preprocessToken(simplecpp::TokenList &output, const simplecpp::Token **tok1, std::map<std::string, simplecpp::Macro> &macros, std::vector<std::string> &files, simplecpp::OutputList *outputList)
{ {
const simplecpp::Token *tok = *tok1; const simplecpp::Token *tok = *tok1;
const simplecpp::MacroMap::const_iterator it = macros.find(tok->str()); const std::map<std::string,simplecpp::Macro>::const_iterator it = macros.find(tok->str());
if (it != macros.end()) { if (it != macros.end()) {
simplecpp::TokenList value(files); simplecpp::TokenList value(files);
try { try {
@ -2915,28 +2819,6 @@ static bool preprocessToken(simplecpp::TokenList &output, const simplecpp::Token
return true; return true;
} }
static void getLocaltime(struct tm &ltime) {
time_t t;
time(&t);
#ifndef _WIN32
localtime_r(&t, &ltime);
#else
localtime_s(&ltime, &t);
#endif
}
static std::string getDateDefine(struct tm *timep) {
char buf[] = "??? ?? ????";
strftime(buf, sizeof(buf), "%b %d %Y", timep);
return std::string("\"").append(buf).append("\"");
}
static std::string getTimeDefine(struct tm *timep) {
char buf[] = "??:??:??";
strftime(buf, sizeof(buf), "%T", timep);
return std::string("\"").append(buf).append("\"");
}
void simplecpp::preprocess(simplecpp::TokenList &output, const simplecpp::TokenList &rawtokens, std::vector<std::string> &files, std::map<std::string, simplecpp::TokenList *> &filedata, const simplecpp::DUI &dui, simplecpp::OutputList *outputList, std::list<simplecpp::MacroUsage> *macroUsage, std::list<simplecpp::IfCond> *ifCond) void simplecpp::preprocess(simplecpp::TokenList &output, const simplecpp::TokenList &rawtokens, std::vector<std::string> &files, std::map<std::string, simplecpp::TokenList *> &filedata, const simplecpp::DUI &dui, simplecpp::OutputList *outputList, std::list<simplecpp::MacroUsage> *macroUsage, std::list<simplecpp::IfCond> *ifCond)
{ {
std::map<std::string, std::size_t> sizeOfType(rawtokens.sizeOfType); std::map<std::string, std::size_t> sizeOfType(rawtokens.sizeOfType);
@ -2962,7 +2844,7 @@ void simplecpp::preprocess(simplecpp::TokenList &output, const simplecpp::TokenL
sizeOfType.insert(std::make_pair("long double *", sizeof(long double *))); sizeOfType.insert(std::make_pair("long double *", sizeof(long double *)));
const bool hasInclude = (dui.std.size() == 5 && dui.std.compare(0,3,"c++") == 0 && dui.std >= "c++17"); const bool hasInclude = (dui.std.size() == 5 && dui.std.compare(0,3,"c++") == 0 && dui.std >= "c++17");
MacroMap macros; std::map<TokenString, Macro> macros;
for (std::list<std::string>::const_iterator it = dui.defines.begin(); it != dui.defines.end(); ++it) { for (std::list<std::string>::const_iterator it = dui.defines.begin(); it != dui.defines.end(); ++it) {
const std::string &macrostr = *it; const std::string &macrostr = *it;
const std::string::size_type eq = macrostr.find('='); const std::string::size_type eq = macrostr.find('=');
@ -2979,21 +2861,15 @@ void simplecpp::preprocess(simplecpp::TokenList &output, const simplecpp::TokenL
macros.insert(std::make_pair("__FILE__", Macro("__FILE__", "__FILE__", files))); macros.insert(std::make_pair("__FILE__", Macro("__FILE__", "__FILE__", files)));
macros.insert(std::make_pair("__LINE__", Macro("__LINE__", "__LINE__", files))); macros.insert(std::make_pair("__LINE__", Macro("__LINE__", "__LINE__", files)));
macros.insert(std::make_pair("__COUNTER__", Macro("__COUNTER__", "__COUNTER__", files))); macros.insert(std::make_pair("__COUNTER__", Macro("__COUNTER__", "__COUNTER__", files)));
struct tm ltime = {};
getLocaltime(ltime);
macros.insert(std::make_pair("__DATE__", Macro("__DATE__", getDateDefine(&ltime), files)));
macros.insert(std::make_pair("__TIME__", Macro("__TIME__", getTimeDefine(&ltime), files)));
if (!dui.std.empty()) { if (dui.std == "c++11")
std::string std_def = simplecpp::getCStdString(dui.std); macros.insert(std::make_pair("__cplusplus", Macro("__cplusplus", "201103L", files)));
if (!std_def.empty()) { else if (dui.std == "c++14")
macros.insert(std::make_pair("__STDC_VERSION__", Macro("__STDC_VERSION__", std_def, files))); macros.insert(std::make_pair("__cplusplus", Macro("__cplusplus", "201402L", files)));
} else { else if (dui.std == "c++17")
std_def = simplecpp::getCppStdString(dui.std); macros.insert(std::make_pair("__cplusplus", Macro("__cplusplus", "201703L", files)));
if (!std_def.empty()) else if (dui.std == "c++20")
macros.insert(std::make_pair("__cplusplus", Macro("__cplusplus", std_def, files))); macros.insert(std::make_pair("__cplusplus", Macro("__cplusplus", "202002L", files)));
}
}
// TRUE => code in current #if block should be kept // TRUE => code in current #if block should be kept
// ELSE_IS_TRUE => code in current #if block should be dropped. the code in the #else should be kept. // ELSE_IS_TRUE => code in current #if block should be dropped. the code in the #else should be kept.
@ -3013,10 +2889,8 @@ void simplecpp::preprocess(simplecpp::TokenList &output, const simplecpp::TokenL
includetokenstack.push(f->second->cfront()); includetokenstack.push(f->second->cfront());
} }
std::map<std::string, std::list<Location> > maybeUsedMacros; for (const Token *rawtok = NULL; rawtok || !includetokenstack.empty();) {
if (rawtok == NULL) {
for (const Token *rawtok = nullptr; rawtok || !includetokenstack.empty();) {
if (rawtok == nullptr) {
rawtok = includetokenstack.top(); rawtok = includetokenstack.top();
includetokenstack.pop(); includetokenstack.pop();
continue; continue;
@ -3070,7 +2944,7 @@ void simplecpp::preprocess(simplecpp::TokenList &output, const simplecpp::TokenL
try { try {
const Macro &macro = Macro(rawtok->previous, files); const Macro &macro = Macro(rawtok->previous, files);
if (dui.undefined.find(macro.name()) == dui.undefined.end()) { if (dui.undefined.find(macro.name()) == dui.undefined.end()) {
MacroMap::iterator it = macros.find(macro.name()); std::map<TokenString, Macro>::iterator it = macros.find(macro.name());
if (it == macros.end()) if (it == macros.end())
macros.insert(std::pair<TokenString, Macro>(macro.name(), macro)); macros.insert(std::pair<TokenString, Macro>(macro.name(), macro));
else else
@ -3161,7 +3035,7 @@ void simplecpp::preprocess(simplecpp::TokenList &output, const simplecpp::TokenL
} else if (pragmaOnce.find(header2) == pragmaOnce.end()) { } else if (pragmaOnce.find(header2) == pragmaOnce.end()) {
includetokenstack.push(gotoNextLine(rawtok)); includetokenstack.push(gotoNextLine(rawtok));
const TokenList *includetokens = filedata.find(header2)->second; const TokenList *includetokens = filedata.find(header2)->second;
rawtok = includetokens ? includetokens->cfront() : nullptr; rawtok = includetokens ? includetokens->cfront() : NULL;
continue; continue;
} }
} else if (rawtok->str() == IF || rawtok->str() == IFDEF || rawtok->str() == IFNDEF || rawtok->str() == ELIF) { } else if (rawtok->str() == IF || rawtok->str() == IFDEF || rawtok->str() == IFNDEF || rawtok->str() == ELIF) {
@ -3180,13 +3054,11 @@ void simplecpp::preprocess(simplecpp::TokenList &output, const simplecpp::TokenL
bool conditionIsTrue; bool conditionIsTrue;
if (ifstates.top() == ALWAYS_FALSE || (ifstates.top() == ELSE_IS_TRUE && rawtok->str() != ELIF)) if (ifstates.top() == ALWAYS_FALSE || (ifstates.top() == ELSE_IS_TRUE && rawtok->str() != ELIF))
conditionIsTrue = false; conditionIsTrue = false;
else if (rawtok->str() == IFDEF) { else if (rawtok->str() == IFDEF)
conditionIsTrue = (macros.find(rawtok->next->str()) != macros.end() || (hasInclude && rawtok->next->str() == HAS_INCLUDE)); conditionIsTrue = (macros.find(rawtok->next->str()) != macros.end() || (hasInclude && rawtok->next->str() == HAS_INCLUDE));
maybeUsedMacros[rawtok->next->str()].push_back(rawtok->next->location); else if (rawtok->str() == IFNDEF)
} else if (rawtok->str() == IFNDEF) {
conditionIsTrue = (macros.find(rawtok->next->str()) == macros.end() && !(hasInclude && rawtok->next->str() == HAS_INCLUDE)); conditionIsTrue = (macros.find(rawtok->next->str()) == macros.end() && !(hasInclude && rawtok->next->str() == HAS_INCLUDE));
maybeUsedMacros[rawtok->next->str()].push_back(rawtok->next->location); else { /*if (rawtok->str() == IF || rawtok->str() == ELIF)*/
} else { /*if (rawtok->str() == IF || rawtok->str() == ELIF)*/
TokenList expr(files); TokenList expr(files);
for (const Token *tok = rawtok->next; tok && tok->location.sameline(rawtok->location); tok = tok->next) { for (const Token *tok = rawtok->next; tok && tok->location.sameline(rawtok->location); tok = tok->next) {
if (!tok->name) { if (!tok->name) {
@ -3199,7 +3071,6 @@ void simplecpp::preprocess(simplecpp::TokenList &output, const simplecpp::TokenL
const bool par = (tok && tok->op == '('); const bool par = (tok && tok->op == '(');
if (par) if (par)
tok = tok->next; tok = tok->next;
maybeUsedMacros[rawtok->next->str()].push_back(rawtok->next->location);
if (tok) { if (tok) {
if (macros.find(tok->str()) != macros.end()) if (macros.find(tok->str()) != macros.end())
expr.push_back(new Token("1", tok->location)); expr.push_back(new Token("1", tok->location));
@ -3209,7 +3080,7 @@ void simplecpp::preprocess(simplecpp::TokenList &output, const simplecpp::TokenL
expr.push_back(new Token("0", tok->location)); expr.push_back(new Token("0", tok->location));
} }
if (par) if (par)
tok = tok ? tok->next : nullptr; tok = tok ? tok->next : NULL;
if (!tok || !sameline(rawtok,tok) || (par && tok->op != ')')) { if (!tok || !sameline(rawtok,tok) || (par && tok->op != ')')) {
if (outputList) { if (outputList) {
Output out(rawtok->location.files); Output out(rawtok->location.files);
@ -3238,7 +3109,7 @@ void simplecpp::preprocess(simplecpp::TokenList &output, const simplecpp::TokenL
expr.push_back(new Token(header2.empty() ? "0" : "1", tok->location)); expr.push_back(new Token(header2.empty() ? "0" : "1", tok->location));
} }
if (par) if (par)
tok = tok ? tok->next : nullptr; tok = tok ? tok->next : NULL;
if (!tok || !sameline(rawtok,tok) || (par && tok->op != ')')) { if (!tok || !sameline(rawtok,tok) || (par && tok->op != ')')) {
if (outputList) { if (outputList) {
Output out(rawtok->location.files); Output out(rawtok->location.files);
@ -3253,8 +3124,6 @@ void simplecpp::preprocess(simplecpp::TokenList &output, const simplecpp::TokenL
continue; continue;
} }
maybeUsedMacros[rawtok->next->str()].push_back(rawtok->next->location);
const Token *tmp = tok; const Token *tmp = tok;
if (!preprocessToken(expr, &tmp, macros, files, outputList)) { if (!preprocessToken(expr, &tmp, macros, files, outputList)) {
output.clear(); output.clear();
@ -3362,11 +3231,9 @@ void simplecpp::preprocess(simplecpp::TokenList &output, const simplecpp::TokenL
} }
if (macroUsage) { if (macroUsage) {
for (simplecpp::MacroMap::const_iterator macroIt = macros.begin(); macroIt != macros.end(); ++macroIt) { for (std::map<TokenString, simplecpp::Macro>::const_iterator macroIt = macros.begin(); macroIt != macros.end(); ++macroIt) {
const Macro &macro = macroIt->second; const Macro &macro = macroIt->second;
std::list<Location> usage = macro.usage(); const std::list<Location> &usage = macro.usage();
const std::list<Location>& temp = maybeUsedMacros[macro.name()];
usage.insert(usage.end(), temp.begin(), temp.end());
for (std::list<Location>::const_iterator usageIt = usage.begin(); usageIt != usage.end(); ++usageIt) { for (std::list<Location>::const_iterator usageIt = usage.begin(); usageIt != usage.end(); ++usageIt) {
MacroUsage mu(usageIt->files, macro.valueDefinedInCode()); MacroUsage mu(usageIt->files, macro.valueDefinedInCode());
mu.macroName = macro.name(); mu.macroName = macro.name();
@ -3384,48 +3251,3 @@ void simplecpp::cleanup(std::map<std::string, TokenList*> &filedata)
delete it->second; delete it->second;
filedata.clear(); filedata.clear();
} }
std::string simplecpp::getCStdString(const std::string &std)
{
if (std == "c90" || std == "c89" || std == "iso9899:1990" || std == "iso9899:199409" || std == "gnu90" || std == "gnu89") {
// __STDC_VERSION__ is not set for C90 although the macro was added in the 1994 amendments
return "";
}
if (std == "c99" || std == "c9x" || std == "iso9899:1999" || std == "iso9899:199x" || std == "gnu99"|| std == "gnu9x")
return "199901L";
if (std == "c11" || std == "c1x" || std == "iso9899:2011" || std == "gnu11" || std == "gnu1x")
return "201112L";
if (std == "c17" || std == "c18" || std == "iso9899:2017" || std == "iso9899:2018" || std == "gnu17"|| std == "gnu18")
return "201710L";
if (std == "c2x" || std == "gnu2x") {
// Clang 11 returns "201710L"
return "202000L";
}
return "";
}
std::string simplecpp::getCppStdString(const std::string &std)
{
if (std == "c++98" || std == "c++03" || std == "gnu++98" || std == "gnu++03")
return "199711L";
if (std == "c++11" || std == "gnu++11" || std == "c++0x" || std == "gnu++0x")
return "201103L";
if (std == "c++14" || std == "c++1y" || std == "gnu++14" || std == "gnu++1y")
return "201402L";
if (std == "c++17" || std == "c++1z" || std == "gnu++17" || std == "gnu++1z")
return "201703L";
if (std == "c++20" || std == "c++2a" || std == "gnu++20" || std == "gnu++2a") {
// GCC 10 returns "201703L"
return "202002L";
}
/*
if (std == "c++23" || std == "c++2b" || std == "gnu++23" || std == "gnu++2b") {
// supported by GCC 11+
return "";
} */
return "";
}
#if (__cplusplus < 201103L) && !defined(__APPLE__)
#undef nullptr
#endif

View File

@ -1,6 +1,6 @@
/* /*
* simplecpp - A simple and high-fidelity C/C++ preprocessor library * simplecpp - A simple and high-fidelity C/C++ preprocessor library
* Copyright (C) 2016-2022 Daniel Marjamäki. * Copyright (C) 2016 Daniel Marjamäki.
* *
* This library is free software: you can redistribute it and/or * This library is free software: you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public * modify it under the terms of the GNU Lesser General Public
@ -21,7 +21,6 @@
#include <cctype> #include <cctype>
#include <cstddef> #include <cstddef>
#include <cstring>
#include <istream> #include <istream>
#include <list> #include <list>
#include <map> #include <map>
@ -41,14 +40,10 @@
# define SIMPLECPP_LIB # define SIMPLECPP_LIB
#endif #endif
#if (__cplusplus < 201103L) && !defined(__APPLE__)
#define nullptr NULL
#endif
namespace simplecpp { namespace simplecpp {
typedef std::string TokenString; typedef std::string TokenString;
class Macro;
/** /**
* Location in source code * Location in source code
@ -102,19 +97,20 @@ namespace simplecpp {
class SIMPLECPP_LIB Token { class SIMPLECPP_LIB Token {
public: public:
Token(const TokenString &s, const Location &loc) : Token(const TokenString &s, const Location &loc) :
location(loc), previous(nullptr), next(nullptr), string(s) { location(loc), previous(NULL), next(NULL), string(s) {
flags(); flags();
} }
Token(const Token &tok) : Token(const Token &tok) :
macro(tok.macro), op(tok.op), comment(tok.comment), name(tok.name), number(tok.number), location(tok.location), previous(nullptr), next(nullptr), string(tok.string), mExpandedFrom(tok.mExpandedFrom) { macro(tok.macro), location(tok.location), previous(NULL), next(NULL), string(tok.string) {
flags();
} }
void flags() { void flags() {
name = (std::isalpha(static_cast<unsigned char>(string[0])) || string[0] == '_' || string[0] == '$') name = (std::isalpha((unsigned char)string[0]) || string[0] == '_' || string[0] == '$')
&& (std::memchr(string.c_str(), '\'', string.size()) == nullptr); && (string.find('\'') == string.npos);
comment = string.size() > 1U && string[0] == '/' && (string[1] == '/' || string[1] == '*'); comment = string.size() > 1U && string[0] == '/' && (string[1] == '/' || string[1] == '*');
number = std::isdigit(static_cast<unsigned char>(string[0])) || (string.size() > 1U && string[0] == '-' && std::isdigit(static_cast<unsigned char>(string[1]))); number = std::isdigit((unsigned char)string[0]) || (string.size() > 1U && string[0] == '-' && std::isdigit((unsigned char)string[1]));
op = (string.size() == 1U) ? string[0] : '\0'; op = (string.size() == 1U) ? string[0] : '\0';
} }
@ -153,11 +149,11 @@ namespace simplecpp {
return tok; return tok;
} }
void setExpandedFrom(const Token *tok, const Macro* m) { void setExpandedFrom(const Token *tok, const void* m) {
mExpandedFrom = tok->mExpandedFrom; mExpandedFrom = tok->mExpandedFrom;
mExpandedFrom.insert(m); mExpandedFrom.insert(m);
} }
bool isExpandedFrom(const Macro* m) const { bool isExpandedFrom(const void* m) const {
return mExpandedFrom.find(m) != mExpandedFrom.end(); return mExpandedFrom.find(m) != mExpandedFrom.end();
} }
@ -166,7 +162,7 @@ namespace simplecpp {
private: private:
TokenString string; TokenString string;
std::set<const Macro*> mExpandedFrom; std::set<const void*> mExpandedFrom;
// Not implemented - prevent assignment // Not implemented - prevent assignment
Token &operator=(const Token &tok); Token &operator=(const Token &tok);
@ -195,7 +191,7 @@ namespace simplecpp {
class SIMPLECPP_LIB TokenList { class SIMPLECPP_LIB TokenList {
public: public:
explicit TokenList(std::vector<std::string> &filenames); explicit TokenList(std::vector<std::string> &filenames);
TokenList(std::istream &istr, std::vector<std::string> &filenames, const std::string &filename=std::string(), OutputList *outputList = nullptr); TokenList(std::istream &istr, std::vector<std::string> &filenames, const std::string &filename=std::string(), OutputList *outputList = NULL);
TokenList(const TokenList &other); TokenList(const TokenList &other);
#if __cplusplus >= 201103L #if __cplusplus >= 201103L
TokenList(TokenList &&other); TokenList(TokenList &&other);
@ -215,7 +211,7 @@ namespace simplecpp {
void dump() const; void dump() const;
std::string stringify() const; std::string stringify() const;
void readfile(std::istream &istr, const std::string &filename=std::string(), OutputList *outputList = nullptr); void readfile(std::istream &istr, const std::string &filename=std::string(), OutputList *outputList = NULL);
void constFold(); void constFold();
void removeComments(); void removeComments();
@ -262,7 +258,7 @@ namespace simplecpp {
other.frontToken->previous = backToken; other.frontToken->previous = backToken;
} }
backToken = other.backToken; backToken = other.backToken;
other.frontToken = other.backToken = nullptr; other.frontToken = other.backToken = NULL;
} }
/** sizeof(T) */ /** sizeof(T) */
@ -284,7 +280,6 @@ namespace simplecpp {
void lineDirective(unsigned int fileIndex, unsigned int line, Location *location); void lineDirective(unsigned int fileIndex, unsigned int line, Location *location);
std::string lastLine(int maxsize=100000) const; std::string lastLine(int maxsize=100000) const;
bool isLastLinePreprocessor(int maxsize=100000) const;
unsigned int fileIndex(const std::string &filename); unsigned int fileIndex(const std::string &filename);
@ -325,7 +320,7 @@ namespace simplecpp {
SIMPLECPP_LIB long long characterLiteralToLL(const std::string& str); SIMPLECPP_LIB long long characterLiteralToLL(const std::string& str);
SIMPLECPP_LIB std::map<std::string, TokenList*> load(const TokenList &rawtokens, std::vector<std::string> &filenames, const DUI &dui, OutputList *outputList = nullptr); SIMPLECPP_LIB std::map<std::string, TokenList*> load(const TokenList &rawtokens, std::vector<std::string> &filenames, const DUI &dui, OutputList *outputList = NULL);
/** /**
* Preprocess * Preprocess
@ -339,7 +334,7 @@ namespace simplecpp {
* @param macroUsage output: macro usage * @param macroUsage output: macro usage
* @param ifCond output: #if/#elif expressions * @param ifCond output: #if/#elif expressions
*/ */
SIMPLECPP_LIB void preprocess(TokenList &output, const TokenList &rawtokens, std::vector<std::string> &files, std::map<std::string, TokenList*> &filedata, const DUI &dui, OutputList *outputList = nullptr, std::list<MacroUsage> *macroUsage = nullptr, std::list<IfCond> *ifCond = nullptr); SIMPLECPP_LIB void preprocess(TokenList &output, const TokenList &rawtokens, std::vector<std::string> &files, std::map<std::string, TokenList*> &filedata, const DUI &dui, OutputList *outputList = NULL, std::list<MacroUsage> *macroUsage = NULL, std::list<IfCond> *ifCond = NULL);
/** /**
* Deallocate data * Deallocate data
@ -351,16 +346,6 @@ namespace simplecpp {
/** Convert Cygwin path to Windows path */ /** Convert Cygwin path to Windows path */
SIMPLECPP_LIB std::string convertCygwinToWindowsPath(const std::string &cygwinPath); SIMPLECPP_LIB std::string convertCygwinToWindowsPath(const std::string &cygwinPath);
/** Returns the __STDC_VERSION__ value for a given standard */
SIMPLECPP_LIB static std::string getCStdString(const std::string &std);
/** Returns the __cplusplus value for a given standard */
SIMPLECPP_LIB static std::string getCppStdString(const std::string &std);
} }
#if (__cplusplus < 201103L) && !defined(__APPLE__)
#undef nullptr
#endif
#endif #endif