Skip to content

Commit 8217efd

Browse files
committed
Properly escape filenames in Windows
1 parent 1639a2a commit 8217efd

File tree

3 files changed

+29
-3
lines changed

3 files changed

+29
-3
lines changed

JsonImpl.hpp

+7-2
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,7 @@ using namespace std;
3838

3939
#define JSON_NOEXCEPTION
4040
#include "json.hpp"
41+
#include "utils.hpp"
4142
#include "clang/include/clang/Sema/CodeCompleteConsumer.h"
4243
using json = nlohmann::json;
4344

@@ -50,8 +51,10 @@ inline json encode(const SourceManager &sm, const SourceLocation &loc) {
5051
PresumedLoc presumed = sm.getPresumedLoc(loc);
5152
stringstream pos;
5253
pos << presumed.getLine() << ":" << presumed.getColumn();
54+
std::string filename(presumed.getFilename());
55+
filename = quoteCppString(filename);
5356
return json{
54-
{"file", presumed.getFilename()},
57+
{"file", filename.c_str()},
5558
{"pos", pos.str()}};
5659
}
5760

@@ -225,7 +228,9 @@ inline json encode(const CodeCompletionResult &cc, const CodeCompletionString *c
225228
{
226229
SourceLocation loc = cc.Declaration->getLocation();
227230
PresumedLoc presumedLoc = sm.getPresumedLoc(loc);
228-
res["location"] = presumedLoc.getFilename();
231+
std::string filename(presumedLoc.getFilename());
232+
filename = quoteCppString(filename);
233+
res["location"] = filename.c_str();
229234
res["type"] = cc.Declaration->getDeclKindName();
230235

231236
// For each parameter extract type and name

main.cpp

+3-1
Original file line numberDiff line numberDiff line change
@@ -233,7 +233,9 @@ class INOPreprocessorMatcherCallback : public MatchFinder::MatchCallback {
233233
ostringstream lineInfo;
234234
lineInfo << "#line " << presumed.getLine();
235235
lineInfo << " \"" << presumed.getFilename() << "\"\n";
236-
rewriter.InsertTextAfter(insertionPoint, lineInfo.str());
236+
std::string lineInfoAsStr = lineInfo.str();
237+
lineInfoAsStr = quoteCppString(lineInfoAsStr);
238+
rewriter.InsertTextAfter(insertionPoint, lineInfoAsStr);
237239
}
238240
};
239241

utils.hpp

+19
Original file line numberDiff line numberDiff line change
@@ -75,3 +75,22 @@ inline bool cStrEndsWith(const char *str, const char *suffix) {
7575

7676
return strncmp(str + strLen - suffixLen, suffix, suffixLen) == 0;
7777
}
78+
79+
#ifdef WIN32
80+
inline bool replace(std::string& str, const std::string& from, const std::string& to) {
81+
size_t start_pos = str.find(from);
82+
if(start_pos == std::string::npos)
83+
return false;
84+
str.replace(start_pos, from.length(), to);
85+
return true;
86+
}
87+
88+
inline std::string quoteCppString(std::string& str) {
89+
replace(str, "\\", "\\\\");
90+
return str;
91+
}
92+
#else
93+
inline std::string quoteCppString(std::string& str) {
94+
return str;
95+
}
96+
#endif

0 commit comments

Comments
 (0)