Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add macro to string conversion #947

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,9 @@
*.suo
*.user

# IDEA
.idea/

# Build directories
CrazyDebug*/
Debug*/
Expand Down
17 changes: 15 additions & 2 deletions compiler/lexer.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,8 @@
#include <string>
#include <unordered_set>
#include <utility>
#include <iomanip>
#include <sstream>

#if defined __linux__ || defined __FreeBSD__ || defined __OpenBSD__ || defined DARWIN
# include <unistd.h>
Expand Down Expand Up @@ -2571,8 +2573,13 @@ std::string Lexer::PerformMacroSubstitution(MacroEntry* macro,
out.push_back(substitute[pos + 1]);
continue;
}
if (stringize)
out += '"' + iter->second + '"';
if (stringize) {
auto arg_macro = FindMacro(cc_.atom(iter->second));
if (arg_macro != nullptr && !arg_macro->args)
out += QuoteString(arg_macro->substitute->str());
else
out += QuoteString(iter->second);
}
else
out += iter->second;
}
Expand Down Expand Up @@ -2654,4 +2661,10 @@ void Lexer::DiscardCachedTokens() {
injected_token_stream_.clear();
}

std::string QuoteString(const std::string& string) {
std::stringstream ss;
ss << std::quoted(string);
return ss.str();
}

} // namespace sp
1 change: 1 addition & 0 deletions compiler/lexer.h
Original file line number Diff line number Diff line change
Expand Up @@ -533,5 +533,6 @@ class Lexer
};

std::string StringizePath(const std::filesystem::path& in_path);
std::string QuoteString(const std::string& string);

} // namespace sp
6 changes: 6 additions & 0 deletions tests/macros/stringification.out
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
ab
"ab"
C3
C3()
C4(15)
UNDEFINED
27 changes: 27 additions & 0 deletions tests/macros/stringification.sp
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
#include <shell>

#define TO_STR(%0) #%0

#define C1 ab
#define C2 "ab"
#define C3() cd
#define C4(%0) %0

public main() {
print(TO_STR(C1));
print("\n");

print(TO_STR(C2));
print("\n");

print(TO_STR(C3));
print("\n");

print(TO_STR(C3()));
print("\n");

print(TO_STR(C4(15)));
print("\n");

print(TO_STR(UNDEFINED));
}
Loading