Debian Codegraph @

src/jsontestrunner/main.cpp

raw
1 // Copyright 2007-2010 Baptiste Lepilleur and The JsonCpp Authors
2 // Distributed under MIT license, or public domain if desired and
3 // recognized in your jurisdiction.
4 // See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
5
6 #if defined(__GNUC__)
7 #pragma GCC diagnostic push
8 #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
9 #elif defined(_MSC_VER)
10 #pragma warning(disable : 4996)
11 #endif
12
13 /* This executable is used for testing parser/writer using real JSON files.
14 */
15
16 #include <algorithm> // sort
17 #include <cstdio>
18 #include <iostream>
19 #include <json/json.h>
20 #include <memory>
21 #include <sstream>
22
23 struct Options {
24 Json::String path;
25 Json::Features features;
26 bool parseOnly;
27 using writeFuncType = Json::String (*)(Json::Value const&);
28 writeFuncType write;
29 };
30
31 static Json::String normalizeFloatingPointStr(double value) {
32 char buffer[32];
33 jsoncpp_snprintf(buffer, sizeof(buffer), "%.16g", value);
34 buffer[sizeof(buffer) - 1] = 0;
35 Json::String s(buffer);
36 Json::String::size_type index = s.find_last_of("eE");
37 if (index != Json::String::npos) {
38 Json::String::size_type hasSign =
39 (s[index + 1] == '+' || s[index + 1] == '-') ? 1 : 0;
40 Json::String::size_type exponentStartIndex = index + 1 + hasSign;
41 Json::String normalized = s.substr(0, exponentStartIndex);
42 Json::String::size_type indexDigit =
43 s.find_first_not_of('0', exponentStartIndex);
44 Json::String exponent = "0";
45 if (indexDigit != Json::String::npos) // There is an exponent different
46 // from 0
47 {
48 exponent = s.substr(indexDigit);
49 }
50 return normalized + exponent;
51 }
52 return s;
53 }
54
55 static Json::String readInputTestFile(const char* path) {
56 FILE* file = fopen(path, "rb");
57 if (!file)
58 return "";
59 fseek(file, 0, SEEK_END);
60 auto const size = ftell(file);
61 auto const usize = static_cast<size_t>(size);
62 fseek(file, 0, SEEK_SET);
63 auto buffer = new char[size + 1];
64 buffer[size] = 0;
65 Json::String text;
66 if (fread(buffer, 1, usize, file) == usize)
67 text = buffer;
68 fclose(file);
69 delete[] buffer;
70 return text;
71 }
72
73 static void printValueTree(FILE* fout, Json::Value& value,
74 const Json::String& path = ".") {
75 if (value.hasComment(Json::commentBefore)) {
76 fprintf(fout, "%s\n", value.getComment(Json::commentBefore).c_str());
77 }
78 switch (value.type()) {
79 case Json::nullValue:
80 fprintf(fout, "%s=null\n", path.c_str());
81 break;
82 case Json::intValue:
83 fprintf(fout, "%s=%s\n", path.c_str(),
84 Json::valueToString(value.asLargestInt()).c_str());
85 break;
86 case Json::uintValue:
87 fprintf(fout, "%s=%s\n", path.c_str(),
88 Json::valueToString(value.asLargestUInt()).c_str());
89 break;
90 case Json::realValue:
91 fprintf(fout, "%s=%s\n", path.c_str(),
92 normalizeFloatingPointStr(value.asDouble()).c_str());
93 break;
94 case Json::stringValue:
95 fprintf(fout, "%s=\"%s\"\n", path.c_str(), value.asString().c_str());
96 break;
97 case Json::booleanValue:
98 fprintf(fout, "%s=%s\n", path.c_str(), value.asBool() ? "true" : "false");
99 break;
100 case Json::arrayValue: {
101 fprintf(fout, "%s=[]\n", path.c_str());
102 Json::ArrayIndex size = value.size();
103 for (Json::ArrayIndex index = 0; index < size; ++index) {
104 static char buffer[16];
105 jsoncpp_snprintf(buffer, sizeof(buffer), "[%u]", index);
106 printValueTree(fout, value[index], path + buffer);
107 }
108 } break;
109 case Json::objectValue: {
110 fprintf(fout, "%s={}\n", path.c_str());
111 Json::Value::Members members(value.getMemberNames());
112 std::sort(members.begin(), members.end());
113 Json::String suffix = *(path.end() - 1) == '.' ? "" : ".";
114 for (const auto& name : members) {
115 printValueTree(fout, value[name], path + suffix + name);
116 }
117 } break;
118 default:
119 break;
120 }
121
122 if (value.hasComment(Json::commentAfter)) {
123 fprintf(fout, "%s\n", value.getComment(Json::commentAfter).c_str());
124 }
125 }
126
127 static int parseAndSaveValueTree(const Json::String& input,
128 const Json::String& actual,
129 const Json::String& kind,
130 const Json::Features& features, bool parseOnly,
131 Json::Value* root, bool use_legacy) {
132 if (!use_legacy) {
133 Json::CharReaderBuilder builder;
134
135 builder.settings_["allowComments"] = features.allowComments_;
136 builder.settings_["strictRoot"] = features.strictRoot_;
137 builder.settings_["allowDroppedNullPlaceholders"] =
138 features.allowDroppedNullPlaceholders_;
139 builder.settings_["allowNumericKeys"] = features.allowNumericKeys_;
140
141 std::unique_ptr<Json::CharReader> reader(builder.newCharReader());
142 Json::String errors;
143 const bool parsingSuccessful =
144 reader->parse(input.data(), input.data() + input.size(), root, &errors);
145
146 if (!parsingSuccessful) {
147 std::cerr << "Failed to parse " << kind << " file: " << std::endl
148 << errors << std::endl;
149 return 1;
150 }
151
152 // We may instead check the legacy implementation (to ensure it doesn't
153 // randomly get broken).
154 } else {
155 Json::Reader reader(features);
156 const bool parsingSuccessful =
157 reader.parse(input.data(), input.data() + input.size(), *root);
158 if (!parsingSuccessful) {
159 std::cerr << "Failed to parse " << kind << " file: " << std::endl
160 << reader.getFormatedErrorMessages() << std::endl;
161 return 1;
162 }
163 }
164
165 if (!parseOnly) {
166 FILE* factual = fopen(actual.c_str(), "wt");
167 if (!factual) {
168 std::cerr << "Failed to create '" << kind << "' actual file."
169 << std::endl;
170 return 2;
171 }
172 printValueTree(factual, *root);
173 fclose(factual);
174 }
175 return 0;
176 }
177 // static Json::String useFastWriter(Json::Value const& root) {
178 // Json::FastWriter writer;
179 // writer.enableYAMLCompatibility();
180 // return writer.write(root);
181 // }
182 static Json::String useStyledWriter(Json::Value const& root) {
183 Json::StyledWriter writer;
184 return writer.write(root);
185 }
186 static Json::String useStyledStreamWriter(Json::Value const& root) {
187 Json::StyledStreamWriter writer;
188 Json::OStringStream sout;
189 writer.write(sout, root);
190 return sout.str();
191 }
192 static Json::String useBuiltStyledStreamWriter(Json::Value const& root) {
193 Json::StreamWriterBuilder builder;
194 return Json::writeString(builder, root);
195 }
196 static int rewriteValueTree(const Json::String& rewritePath,
197 const Json::Value& root,
198 Options::writeFuncType write,
199 Json::String* rewrite) {
200 *rewrite = write(root);
201 FILE* fout = fopen(rewritePath.c_str(), "wt");
202 if (!fout) {
203 std::cerr << "Failed to create rewrite file: " << rewritePath << std::endl;
204 return 2;
205 }
206 fprintf(fout, "%s\n", rewrite->c_str());
207 fclose(fout);
208 return 0;
209 }
210
211 static Json::String removeSuffix(const Json::String& path,
212 const Json::String& extension) {
213 if (extension.length() >= path.length())
214 return Json::String("");
215 Json::String suffix = path.substr(path.length() - extension.length());
216 if (suffix != extension)
217 return Json::String("");
218 return path.substr(0, path.length() - extension.length());
219 }
220
221 static void printConfig() {
222 // Print the configuration used to compile JsonCpp
223 #if defined(JSON_NO_INT64)
224 std::cout << "JSON_NO_INT64=1" << std::endl;
225 #else
226 std::cout << "JSON_NO_INT64=0" << std::endl;
227 #endif
228 }
229
230 static int printUsage(const char* argv[]) {
231 std::cout << "Usage: " << argv[0] << " [--strict] input-json-file"
232 << std::endl;
233 return 3;
234 }
235
236 static int parseCommandLine(int argc, const char* argv[], Options* opts) {
237 opts->parseOnly = false;
238 opts->write = &useStyledWriter;
239 if (argc < 2) {
240 return printUsage(argv);
241 }
242 int index = 1;
243 if (Json::String(argv[index]) == "--parse-only") {
244 opts->parseOnly = true;
245 ++index;
246 }
247 if (Json::String(argv[index]) == "--strict") {
248 opts->features = Json::Features::strictMode();
249 ++index;
250 }
251 if (Json::String(argv[index]) == "--json-config") {
252 printConfig();
253 return 3;
254 }
255 if (Json::String(argv[index]) == "--json-writer") {
256 ++index;
257 Json::String const writerName(argv[index++]);
258 if (writerName == "StyledWriter") {
259 opts->write = &useStyledWriter;
260 } else if (writerName == "StyledStreamWriter") {
261 opts->write = &useStyledStreamWriter;
262 } else if (writerName == "BuiltStyledStreamWriter") {
263 opts->write = &useBuiltStyledStreamWriter;
264 } else {
265 std::cerr << "Unknown '--json-writer' " << writerName << std::endl;
266 return 4;
267 }
268 }
269 if (index == argc || index + 1 < argc) {
270 return printUsage(argv);
271 }
272 opts->path = argv[index];
273 return 0;
274 }
275
276 static int runTest(Options const& opts, bool use_legacy) {
277 int exitCode = 0;
278
279 Json::String input = readInputTestFile(opts.path.c_str());
280 if (input.empty()) {
281 std::cerr << "Invalid input file: " << opts.path << std::endl;
282 return 3;
283 }
284
285 Json::String basePath = removeSuffix(opts.path, ".json");
286 if (!opts.parseOnly && basePath.empty()) {
287 std::cerr << "Bad input path '" << opts.path
288 << "'. Must end with '.expected'" << std::endl;
289 return 3;
290 }
291
292 Json::String const actualPath = basePath + ".actual";
293 Json::String const rewritePath = basePath + ".rewrite";
294 Json::String const rewriteActualPath = basePath + ".actual-rewrite";
295
296 Json::Value root;
297 exitCode = parseAndSaveValueTree(input, actualPath, "input", opts.features,
298 opts.parseOnly, &root, use_legacy);
299 if (exitCode || opts.parseOnly) {
300 return exitCode;
301 }
302
303 Json::String rewrite;
304 exitCode = rewriteValueTree(rewritePath, root, opts.write, &rewrite);
305 if (exitCode) {
306 return exitCode;
307 }
308
309 Json::Value rewriteRoot;
310 exitCode = parseAndSaveValueTree(rewrite, rewriteActualPath, "rewrite",
311 opts.features, opts.parseOnly, &rewriteRoot,
312 use_legacy);
313
314 return exitCode;
315 }
316
317 int main(int argc, const char* argv[]) {
318 Options opts;
319 try {
320 int exitCode = parseCommandLine(argc, argv, &opts);
321 if (exitCode != 0) {
322 std::cerr << "Failed to parse command-line." << std::endl;
323 return exitCode;
324 }
325
326 const int modern_return_code = runTest(opts, false);
327 if (modern_return_code) {
328 return modern_return_code;
329 }
330
331 const std::string filename =
332 opts.path.substr(opts.path.find_last_of("\\/") + 1);
333 const bool should_run_legacy = (filename.rfind("legacy_", 0) == 0);
334 if (should_run_legacy) {
335 return runTest(opts, true);
336 }
337 } catch (const std::exception& e) {
338 std::cerr << "Unhandled exception:" << std::endl << e.what() << std::endl;
339 return 1;
340 }
341 return 0;
342 }
343
344 #if defined(__GNUC__)
345 #pragma GCC diagnostic pop
346 #endif