Adds a JSON parser and a benchmark (json-bench) to catch performance regressions.
[oota-llvm.git] / unittests / Support / JSONParserTest.cpp
1 //===- unittest/Tooling/JSONParserTest ------------------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9
10 #include "llvm/Support/Casting.h"
11 #include "llvm/Support/JSONParser.h"
12 #include "llvm/ADT/Twine.h"
13 #include "gtest/gtest.h"
14
15 namespace llvm {
16
17 // Returns a buffer that contains the content of the given string without
18 // the trailing zero, in order to get valgrind to catch out-of-bound reads.
19 static std::vector<char> CutTrailingZero(StringRef String) {
20   std::vector<char> InputWithoutZero(String.size());
21   memcpy(&InputWithoutZero[0], String.data(), String.size());
22   return InputWithoutZero;
23 }
24
25 // Checks that the given input gives a parse error. Makes sure that an error
26 // text is available and the parse fails.
27 static void ExpectParseError(StringRef Message,
28                              const std::vector<char> &InputWithoutZero) {
29   StringRef Input = StringRef(&InputWithoutZero[0], InputWithoutZero.size());
30   JSONParser Parser(Input);
31   EXPECT_FALSE(Parser.validate()) << Message << ": " << Input;
32   EXPECT_TRUE(Parser.failed()) << Message << ": " << Input;
33   EXPECT_FALSE(Parser.getErrorMessage().empty()) << Message << ": " << Input;
34 }
35
36 // Overloads the above to allow using const char * as Input.
37 static void ExpectParseError(StringRef Message, StringRef Input) {
38   return ExpectParseError(Message, CutTrailingZero(Input));
39 }
40
41 // Checks that the given input can be parsed without error.
42 static void ExpectParseSuccess(StringRef Message,
43                                const std::vector<char> &InputWithoutZero) {
44   StringRef Input = StringRef(&InputWithoutZero[0], InputWithoutZero.size());
45   JSONParser Parser(Input);
46   EXPECT_TRUE(Parser.validate())
47     << Message << ": " << Input << " - " << Parser.getErrorMessage();
48 }
49
50 // Overloads the above to allow using const char * as Input.
51 static void ExpectParseSuccess(StringRef Message, StringRef Input) {
52   return ExpectParseSuccess(Message, CutTrailingZero(Input));
53 }
54
55 TEST(JSONParser, FailsOnEmptyString) {
56   JSONParser Parser("");
57   EXPECT_EQ(NULL, Parser.parseRoot());
58 }
59
60 TEST(JSONParser, DoesNotReadAfterInput) {
61   JSONParser Parser(llvm::StringRef(NULL, 0));
62   EXPECT_EQ(NULL, Parser.parseRoot());
63 }
64
65 TEST(JSONParser, FailsIfStartsWithString) {
66   JSONParser Character("\"x\"");
67   EXPECT_EQ(NULL, Character.parseRoot());
68 }
69
70 TEST(JSONParser, ParsesEmptyArray) {
71   ExpectParseSuccess("Empty array", "[]");
72 }
73
74 TEST(JSONParser, FailsIfNotClosingArray) {
75   ExpectParseError("Not closing array", "[");
76   ExpectParseError("Not closing array", "  [  ");
77   ExpectParseError("Not closing array", "  [x");
78 }
79
80 TEST(JSONParser, ParsesEmptyArrayWithWhitespace) {
81   ExpectParseSuccess("Array with spaces", "  [  ]  ");
82   ExpectParseSuccess("All whitespaces", "\t\r\n[\t\n \t\r ]\t\r \n\n");
83 }
84
85 TEST(JSONParser, ParsesEmptyObject) {
86   ExpectParseSuccess("Empty object", "[{}]");
87 }
88
89 TEST(JSONParser, ParsesObject) {
90   ExpectParseSuccess("Object with an entry", "[{\"a\":\"/b\"}]");
91 }
92
93 TEST(JSONParser, ParsesMultipleKeyValuePairsInObject) {
94   ExpectParseSuccess("Multiple key, value pairs",
95                      "[{\"a\":\"/b\",\"c\":\"d\",\"e\":\"f\"}]");
96 }
97
98 TEST(JSONParser, FailsIfNotClosingObject) {
99   ExpectParseError("Missing close on empty", "[{]");
100   ExpectParseError("Missing close after pair", "[{\"a\":\"b\"]");
101 }
102
103 TEST(JSONParser, FailsIfMissingColon) {
104   ExpectParseError("Missing colon between key and value", "[{\"a\"\"/b\"}]");
105   ExpectParseError("Missing colon between key and value", "[{\"a\" \"b\"}]");
106 }
107
108 TEST(JSONParser, FailsOnMissingQuote) {
109   ExpectParseError("Missing open quote", "[{a\":\"b\"}]");
110   ExpectParseError("Missing closing quote", "[{\"a\":\"b}]");
111 }
112
113 TEST(JSONParser, ParsesEscapedQuotes) {
114   ExpectParseSuccess("Parses escaped string in key and value",
115                      "[{\"a\":\"\\\"b\\\"  \\\" \\\"\"}]");
116 }
117
118 TEST(JSONParser, ParsesEmptyString) {
119   ExpectParseSuccess("Parses empty string in value", "[{\"a\":\"\"}]");
120 }
121
122 TEST(JSONParser, FailsOnMissingString) {
123   ExpectParseError("Missing value", "[{\"a\":}]");
124   ExpectParseError("Missing key", "[{:\"b\"}]");
125 }
126
127 TEST(JSONParser, ParsesMultipleObjects) {
128   ExpectParseSuccess(
129       "Multiple objects in array",
130       "["
131       " { \"a\" : \"b\" },"
132       " { \"a\" : \"b\" },"
133       " { \"a\" : \"b\" }"
134       "]");
135 }
136
137 TEST(JSONParser, FailsOnMissingComma) {
138   ExpectParseError(
139       "Missing comma",
140       "["
141       " { \"a\" : \"b\" }"
142       " { \"a\" : \"b\" }"
143       "]");
144 }
145
146 TEST(JSONParser, FailsOnSuperfluousComma) {
147   ExpectParseError("Superfluous comma in array", "[ { \"a\" : \"b\" }, ]");
148   ExpectParseError("Superfluous comma in object", "{ \"a\" : \"b\", }");
149 }
150
151 TEST(JSONParser, ParsesSpacesInBetweenTokens) {
152   ExpectParseSuccess(
153       "Various whitespace between tokens",
154       " \t \n\n \r [ \t \n\n \r"
155       " \t \n\n \r { \t \n\n \r\"a\"\t \n\n \r :"
156       " \t \n\n \r \"b\"\t \n\n \r } \t \n\n \r,\t \n\n \r"
157       " \t \n\n \r { \t \n\n \r\"a\"\t \n\n \r :"
158       " \t \n\n \r \"b\"\t \n\n \r } \t \n\n \r]\t \n\n \r");
159 }
160
161 TEST(JSONParser, ParsesArrayOfArrays) {
162   ExpectParseSuccess("Array of arrays", "[[]]");
163 }
164
165 TEST(JSONParser, HandlesEndOfFileGracefully) {
166   ExpectParseError("In string starting with EOF", "[\"");
167   ExpectParseError("In string hitting EOF", "[\"   ");
168   ExpectParseError("In string escaping EOF", "[\"  \\");
169   ExpectParseError("In array starting with EOF", "[");
170   ExpectParseError("In array element starting with EOF", "[[], ");
171   ExpectParseError("In array hitting EOF", "[[] ");
172   ExpectParseError("In array hitting EOF", "[[]");
173   ExpectParseError("In object hitting EOF", "{\"\"");
174 }
175
176 // Checks that the given string can be parsed into an identical string inside
177 // of an array.
178 static void ExpectCanParseString(StringRef String) {
179   std::string StringInArray = (llvm::Twine("[\"") + String + "\"]").str();
180   JSONParser Parser(StringInArray);
181   const JSONArray *ParsedArray = dyn_cast<JSONArray>(Parser.parseRoot());
182   StringRef ParsedString =
183       dyn_cast<JSONString>(*ParsedArray->begin())->getRawText();
184   EXPECT_EQ(String, ParsedString.str()) << Parser.getErrorMessage();
185 }
186
187 // Checks that parsing the given string inside an array fails.
188 static void ExpectCannotParseString(StringRef String) {
189   std::string StringInArray = (llvm::Twine("[\"") + String + "\"]").str();
190   ExpectParseError((Twine("When parsing string \"") + String + "\"").str(),
191                    StringInArray);
192 }
193
194 TEST(JSONParser, ParsesStrings) {
195   ExpectCanParseString("");
196   ExpectCannotParseString("\\");
197   ExpectCannotParseString("\"");
198   ExpectCanParseString(" ");
199   ExpectCanParseString("\\ ");
200   ExpectCanParseString("\\\"");
201   ExpectCannotParseString("\"\\");
202   ExpectCannotParseString(" \\");
203   ExpectCanParseString("\\\\");
204   ExpectCannotParseString("\\\\\\");
205   ExpectCanParseString("\\\\\\\\");
206   ExpectCanParseString("\\\" ");
207   ExpectCannotParseString("\\\\\" ");
208   ExpectCanParseString("\\\\\\\" ");
209   ExpectCanParseString("    \\\\  \\\"  \\\\\\\"   ");
210 }
211
212 TEST(JSONParser, WorksWithIteratorAlgorithms) {
213   JSONParser Parser("[\"1\", \"2\", \"3\", \"4\", \"5\", \"6\"]");
214   const JSONArray *Array = dyn_cast<JSONArray>(Parser.parseRoot());
215   EXPECT_EQ(6, std::distance(Array->begin(), Array->end()));
216 }
217
218 } // end namespace llvm