Skip to content

Commit

Permalink
Fix an issue with unescaped values + Add tests
Browse files Browse the repository at this point in the history
  • Loading branch information
Classes123 committed Feb 16, 2024
1 parent 35c4576 commit f5cf941
Show file tree
Hide file tree
Showing 4 changed files with 44 additions and 6 deletions.
16 changes: 10 additions & 6 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 @@ -2572,15 +2574,11 @@ std::string Lexer::PerformMacroSubstitution(MacroEntry* macro,
continue;
}
if (stringize) {
out += '"';

auto arg_macro = FindMacro(cc_.atom(iter->second));
if (arg_macro != nullptr && !arg_macro->args)
out += arg_macro->substitute->str();
out += QuoteString(arg_macro->substitute->str());
else
out += iter->second;

out += '"';
out += QuoteString(iter->second);
}
else
out += iter->second;
Expand Down Expand Up @@ -2663,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));
}

0 comments on commit f5cf941

Please sign in to comment.