1 //===- JsonSupport.h - JSON Output Utilities --------------------*- C++ -*-===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 #ifndef LLVM_CLANG_BASIC_JSONSUPPORT_H
10 #define LLVM_CLANG_BASIC_JSONSUPPORT_H
12 #include "clang/Basic/LLVM.h"
13 #include "clang/Basic/SourceManager.h"
14 #include "llvm/ADT/StringRef.h"
15 #include "llvm/Support/raw_ostream.h"
20 inline raw_ostream &Indent(raw_ostream &Out, const unsigned int Space,
22 for (unsigned int I = 0; I < Space * 2; ++I)
23 Out << (IsDot ? " " : " ");
27 inline std::string JsonFormat(StringRef RawSR, bool AddQuotes) {
31 // Trim special characters.
32 std::string Str = RawSR.trim().str();
35 // Escape backslashes.
37 Pos = Str.find('\\', Pos);
38 if (Pos == std::string::npos)
41 // Prevent bad conversions.
42 size_t TempPos = (Pos != 0) ? Pos - 1 : 0;
44 // See whether the current backslash is not escaped.
45 if (TempPos != Str.find("\\\\", Pos)) {
46 Str.insert(Pos, "\\");
47 ++Pos; // As we insert the backslash move plus one.
53 // Escape double quotes.
56 Pos = Str.find('\"', Pos);
57 if (Pos == std::string::npos)
60 // Prevent bad conversions.
61 size_t TempPos = (Pos != 0) ? Pos - 1 : 0;
63 // See whether the current double quote is not escaped.
64 if (TempPos != Str.find("\\\"", Pos)) {
65 Str.insert(Pos, "\\");
66 ++Pos; // As we insert the escape-character move plus one.
73 Str.erase(std::remove(Str.begin(), Str.end(), '\n'), Str.end());
78 return '\"' + Str + '\"';
81 inline void printSourceLocationAsJson(raw_ostream &Out, SourceLocation Loc,
82 const SourceManager &SM,
83 bool AddBraces = true) {
84 // Mostly copy-pasted from SourceLocation::print.
91 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
93 if (PLoc.isInvalid()) {
97 // The macro expansion and spelling pos is identical for file locs.
100 Out << "\"line\": " << PLoc.getLine()
101 << ", \"column\": " << PLoc.getColumn()
102 << ", \"file\": \"" << PLoc.getFilename() << "\"";
108 // We want 'location: { ..., spelling: { ... }}' but not
109 // 'location: { ... }, spelling: { ... }', hence the dance
112 printSourceLocationAsJson(Out, SM.getExpansionLoc(Loc), SM, false);
113 Out << ", \"spelling\": ";
114 printSourceLocationAsJson(Out, SM.getSpellingLoc(Loc), SM, true);
119 #endif // LLVM_CLANG_BASIC_JSONSUPPORT_H