1 //===--- JSONParser.h - Simple JSON parser ----------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements a JSON parser.
12 // See http://www.json.org/ for an overview.
13 // See http://www.ietf.org/rfc/rfc4627.txt for the full standard.
15 // FIXME: Currently this supports a subset of JSON. Specifically, support
16 // for numbers, booleans and null for values is missing.
18 //===----------------------------------------------------------------------===//
20 #ifndef LLVM_SUPPORT_JSON_PARSER_H
21 #define LLVM_SUPPORT_JSON_PARSER_H
23 #include "llvm/ADT/StringRef.h"
24 #include "llvm/Support/Allocator.h"
25 #include "llvm/Support/ErrorHandling.h"
31 class JSONKeyValuePair;
33 /// \brief Base class for a parsable JSON atom.
35 /// This class has no semantics other than being a unit of JSON data which can
36 /// be parsed out of a JSON document.
39 /// \brief Possible types of JSON objects.
40 enum Kind { JK_KeyValuePair, JK_Array, JK_Object, JK_String };
42 /// \brief Returns the type of this value.
43 Kind getKind() const { return MyKind; }
45 static bool classof(const JSONAtom *Atom) { return true; }
48 JSONAtom(Kind MyKind) : MyKind(MyKind) {}
53 friend class JSONParser;
54 friend class JSONKeyValuePair;
55 template <typename, char, char, JSONAtom::Kind> friend class JSONContainer;
58 /// \brief A parser for JSON text.
60 /// Use an object of JSONParser to iterate over the values of a JSON text.
61 /// All objects are parsed during the iteration, so you can only iterate once
62 /// over the JSON text, but the cost of partial iteration is minimized.
63 /// Create a new JSONParser if you want to iterate multiple times.
66 /// \brief Create a JSONParser for the given input.
68 /// Parsing is started via parseRoot(). Access to the object returned from
69 /// parseRoot() will parse the input lazily.
70 JSONParser(StringRef Input);
72 /// \brief Returns the outermost JSON value (either an array or an object).
74 /// Can return NULL if the input does not start with an array or an object.
75 /// The object is not parsed yet - the caller must iterate over the
76 /// returned object to trigger parsing.
78 /// A JSONValue can be either a JSONString, JSONObject or JSONArray.
79 JSONValue *parseRoot();
81 /// \brief Parses the JSON text and returns whether it is valid JSON.
83 /// In case validate() return false, failed() will return true and
84 /// getErrorMessage() will return the parsing error.
87 /// \brief Returns true if an error occurs during parsing.
89 /// If there was an error while parsing an object that was created by
90 /// iterating over the result of 'parseRoot', 'failed' will return true.
93 /// \brief Returns an error message when 'failed' returns true.
94 std::string getErrorMessage() const;
97 /// \brief These methods manage the implementation details of parsing new JSON
100 JSONString *parseString();
101 JSONValue *parseValue();
102 JSONKeyValuePair *parseKeyValuePair();
105 /// \brief Templated helpers to parse the elements out of both forms of JSON
108 template <typename AtomT> AtomT *parseElement();
109 template <typename AtomT, char StartChar, char EndChar>
110 StringRef::iterator parseFirstElement(const AtomT *&Element);
111 template <typename AtomT, char EndChar>
112 StringRef::iterator parseNextElement(const AtomT *&Element);
115 /// \brief Whitespace parsing.
117 void nextNonWhitespace();
121 /// \brief These methods are used for error handling.
123 void setExpectedError(StringRef Expected, StringRef Found);
124 void setExpectedError(StringRef Expected, char Found);
125 bool errorIfAtEndOfFile(StringRef Message);
126 bool errorIfNotAt(char C, StringRef Message);
129 /// \brief Skips all elements in the given container.
130 template <typename ContainerT>
131 bool skipContainer(const ContainerT &Container);
133 /// \brief Skips to the next position behind the given JSON atom.
134 bool skip(const JSONAtom &Atom);
136 /// All nodes are allocated by the parser and will be deallocated when the
137 /// parser is destroyed.
138 BumpPtrAllocator ValueAllocator;
140 /// \brief The original input to the parser.
141 const StringRef Input;
143 /// \brief The current position in the parse stream.
144 StringRef::iterator Position;
146 /// \brief If non-empty, an error has occurred.
147 std::string ErrorMessage;
149 template <typename AtomT, char StartChar, char EndChar,
150 JSONAtom::Kind ContainerKind>
151 friend class JSONContainer;
155 /// \brief Base class for JSON value objects.
157 /// This object represents an abstract JSON value. It is the root node behind
158 /// the group of JSON entities that can represent top-level values in a JSON
159 /// document. It has no API, and is just a placeholder in the type hierarchy of
161 class JSONValue : public JSONAtom {
163 JSONValue(Kind MyKind) : JSONAtom(MyKind) {}
166 /// \brief dyn_cast helpers
168 static bool classof(const JSONAtom *Atom) {
169 switch (Atom->getKind()) {
174 case JK_KeyValuePair:
177 llvm_unreachable("Invalid JSONAtom kind");
179 static bool classof(const JSONValue *Value) { return true; }
183 /// \brief Gives access to the text of a JSON string.
185 /// FIXME: Implement a method to return the unescaped text.
186 class JSONString : public JSONValue {
188 /// \brief Returns the underlying parsed text of the string.
190 /// This is the unescaped content of the JSON text.
191 /// See http://www.ietf.org/rfc/rfc4627.txt for details.
192 StringRef getRawText() const { return RawText; };
195 JSONString(StringRef RawText) : JSONValue(JK_String), RawText(RawText) {}
199 friend class JSONAtom;
200 friend class JSONParser;
203 /// \brief dyn_cast helpers
205 static bool classof(const JSONAtom *Atom) {
206 return Atom->getKind() == JK_String;
208 static bool classof(const JSONString *String) { return true; }
212 /// \brief A (key, value) tuple of type (JSONString *, JSONValue *).
214 /// Note that JSONKeyValuePair is not a JSONValue, it is a bare JSONAtom.
215 /// JSONKeyValuePairs can be elements of a JSONObject, but not of a JSONArray.
216 /// They are not viable as top-level values either.
217 class JSONKeyValuePair : public JSONAtom {
219 const JSONString * const Key;
220 const JSONValue * const Value;
223 JSONKeyValuePair(const JSONString *Key, const JSONValue *Value)
224 : JSONAtom(JK_KeyValuePair), Key(Key), Value(Value) {}
226 friend class JSONAtom;
227 friend class JSONParser;
228 template <typename, char, char, JSONAtom::Kind> friend class JSONContainer;
231 /// \brief dyn_cast helpers
233 static bool classof(const JSONAtom *Atom) {
234 return Atom->getKind() == JK_KeyValuePair;
236 static bool classof(const JSONKeyValuePair *KeyValuePair) { return true; }
240 /// \brief Implementation of JSON containers (arrays and objects).
242 /// JSONContainers drive the lazy parsing of JSON arrays and objects via
243 /// forward iterators.
244 template <typename AtomT, char StartChar, char EndChar,
245 JSONAtom::Kind ContainerKind>
246 class JSONContainer : public JSONValue {
248 /// \brief An iterator that parses the underlying container during iteration.
250 /// Iterators on the same collection use shared state, so when multiple copies
251 /// of an iterator exist, only one is allowed to be used for iteration;
252 /// iterating multiple copies of an iterator of the same collection will lead
253 /// to undefined behavior.
254 class const_iterator : public std::iterator<std::forward_iterator_tag,
257 const_iterator(const const_iterator &I) : Container(I.Container) {}
259 bool operator==(const const_iterator &I) const {
260 if (isEnd() || I.isEnd())
261 return isEnd() == I.isEnd();
262 return Container->Position == I.Container->Position;
264 bool operator!=(const const_iterator &I) const { return !(*this == I); }
266 const_iterator &operator++() {
267 Container->parseNextElement();
271 const AtomT *operator*() { return Container->Current; }
274 /// \brief Create an iterator for which 'isEnd' returns true.
275 const_iterator() : Container(0) {}
277 /// \brief Create an iterator for the given container.
278 const_iterator(const JSONContainer *Container) : Container(Container) {}
281 return Container == 0 || Container->Position == StringRef::iterator();
284 const JSONContainer * const Container;
286 friend class JSONContainer;
289 /// \brief Returns a lazy parsing iterator over the container.
291 /// As the iterator drives the parse stream, begin() must only be called
292 /// once per container.
293 const_iterator begin() const {
295 report_fatal_error("Cannot parse container twice.");
297 // Set up the position and current element when we begin iterating over the
299 Position = Parser->parseFirstElement<AtomT, StartChar, EndChar>(Current);
300 return const_iterator(this);
303 const_iterator end() const {
304 return const_iterator();
308 JSONContainer(JSONParser *Parser)
309 : JSONValue(ContainerKind), Parser(Parser),
310 Position(), Current(0), Started(false) {}
312 const_iterator current() const {
316 return const_iterator(this);
319 /// \brief Parse the next element in the container into the Current element.
321 /// This routine is called as an iterator into this container walks through
322 /// its elements. It mutates the container's internal current node to point to
323 /// the next atom of the container.
324 void parseNextElement() const {
325 Parser->skip(*Current);
326 Position = Parser->parseNextElement<AtomT, EndChar>(Current);
329 // For parsing, JSONContainers call back into the JSONParser.
330 JSONParser * const Parser;
332 // 'Position', 'Current' and 'Started' store the state of the parse stream
333 // for iterators on the container, they don't change the container's elements
334 // and are thus marked as mutable.
335 mutable StringRef::iterator Position;
336 mutable const AtomT *Current;
337 mutable bool Started;
339 friend class JSONAtom;
340 friend class JSONParser;
341 friend class const_iterator;
344 /// \brief dyn_cast helpers
346 static bool classof(const JSONAtom *Atom) {
347 return Atom->getKind() == ContainerKind;
349 static bool classof(const JSONContainer *Container) { return true; }
353 /// \brief A simple JSON array.
354 typedef JSONContainer<JSONValue, '[', ']', JSONAtom::JK_Array> JSONArray;
356 /// \brief A JSON object: an iterable list of JSON key-value pairs.
357 typedef JSONContainer<JSONKeyValuePair, '{', '}', JSONAtom::JK_Object>
360 /// \brief Template adaptor to dispatch element parsing for values.
361 template <> JSONValue *JSONParser::parseElement();
363 /// \brief Template adaptor to dispatch element parsing for key value pairs.
364 template <> JSONKeyValuePair *JSONParser::parseElement();
366 /// \brief Parses the first element of a JSON array or object, or closes the
369 /// The method assumes that the current position is before the first character
370 /// of the element, with possible white space in between. When successful, it
371 /// returns the new position after parsing the element. Otherwise, if there is
372 /// no next value, it returns a default constructed StringRef::iterator.
373 template <typename AtomT, char StartChar, char EndChar>
374 StringRef::iterator JSONParser::parseFirstElement(const AtomT *&Element) {
375 assert(*Position == StartChar);
378 if (errorIfAtEndOfFile("value or end of container at start of container"))
379 return StringRef::iterator();
381 if (*Position == EndChar)
382 return StringRef::iterator();
384 Element = parseElement<AtomT>();
386 return StringRef::iterator();
391 /// \brief Parses the next element of a JSON array or object, or closes the
394 /// The method assumes that the current position is before the ',' which
395 /// separates the next element from the current element. When successful, it
396 /// returns the new position after parsing the element. Otherwise, if there is
397 /// no next value, it returns a default constructed StringRef::iterator.
398 template <typename AtomT, char EndChar>
399 StringRef::iterator JSONParser::parseNextElement(const AtomT *&Element) {
402 if (errorIfAtEndOfFile("',' or end of container for next element"))
408 if (errorIfAtEndOfFile("element in container"))
409 return StringRef::iterator();
411 Element = parseElement<AtomT>();
413 return StringRef::iterator();
418 return StringRef::iterator();
421 setExpectedError("',' or end of container for next element", *Position);
422 return StringRef::iterator();
426 } // end namespace llvm
428 #endif // LLVM_SUPPORT_JSON_PARSER_H