| 6 | #define BASE_JSON_JSON_PARSER_H_ |
| 7 |
| 8 | #include <stddef.h> |
| 9 | #include <stdint.h> |
| 10 |
| 11 | #include <memory> |
| 12 | #include <string> |
| 13 |
| 14 | #include "base/base_export.h" |
| 15 | #include "base/compiler_specific.h" |
| 16 | #include "base/gtest_prod_util.h" |
| 17 | #include "base/json/json_common.h" |
| 18 | #include "base/json/json_reader.h" |
| 19 | #include "base/macros.h" |
| 20 | #include "base/optional.h" |
| 21 | #include "base/strings/string_piece.h" |
| 22 |
| 23 | namespace base { |
| 24 |
| 25 | class Value; |
| 26 |
| 27 | namespace internal { |
| 28 |
| 29 | class JSONParserTest; |
| 30 |
| 31 | // The implementation behind the JSONReader interface. This class is not meant |
| 32 | // to be used directly; it encapsulates logic that need not be exposed publicly. |
| 33 | // |
| 34 | // This parser guarantees O(n) time through the input string. Iteration happens |
| 35 | // on the byte level, with the functions ConsumeChars() and ConsumeChar(). The |
| 36 | // conversion from byte to JSON token happens without advancing the parser in |
| 37 | // GetNextToken/ParseToken, that is tokenization operates on the current parser |
| 38 | // position without advancing. |
| 39 | // |
| 40 | // Built on top of these are a family of Consume functions that iterate |
| 41 | // internally. Invariant: on entry of a Consume function, the parser is wound |
| 42 | // to the first byte of a valid JSON token. On exit, it is on the first byte |
| 43 | // after the token that was just consumed, which would likely be the first byte |
| 44 | // of the next token. |
| 45 | class BASE_EXPORT JSONParser { |
| 46 | public: |
| 47 | JSONParser(int options, size_t max_depth = kAbsoluteMaxDepth); |
| 48 | ~JSONParser(); |
| 49 |
| 50 | // Parses the input string according to the set options and returns the |
| 51 | // result as a Value. |
| 52 | // Wrap this in base::FooValue::From() to check the Value is of type Foo and |
| 53 | // convert to a FooValue at the same time. |
| 54 | Optional<Value> Parse(StringPiece input); |
| 55 |
| 56 | // Returns the error code. |
| 57 | JSONReader::JsonParseError error_code() const; |
| 58 |
| 59 | // Returns the human-friendly error message. |
| 60 | std::string GetErrorMessage() const; |
| 61 |
| 62 | // Returns the error line number if parse error happened. Otherwise always |
| 63 | // returns 0. |
| 64 | int error_line() const; |
| 65 |
| 66 | // Returns the error column number if parse error happened. Otherwise always |
| 67 | // returns 0. |
| 68 | int error_column() const; |
| 69 |
| 70 | private: |
| 71 | enum Token { |
| 72 | T_OBJECT_BEGIN, // { |
| 73 | T_OBJECT_END, // } |
| 74 | T_ARRAY_BEGIN, // [ |
| 75 | T_ARRAY_END, // ] |
| 76 | T_STRING, |
| 77 | T_NUMBER, |
| 78 | T_BOOL_TRUE, // true |
| 79 | T_BOOL_FALSE, // false |
| 80 | T_NULL, // null |
| 81 | T_LIST_SEPARATOR, // , |
| 82 | T_OBJECT_PAIR_SEPARATOR, // : |
| 83 | T_END_OF_INPUT, |
| 84 | T_INVALID_TOKEN, |
| 85 | }; |
| 86 |
| 87 | // A helper class used for parsing strings. One optimization performed is to |
| 88 | // create base::Value with a StringPiece to avoid unnecessary std::string |
| 89 | // copies. This is not possible if the input string needs to be decoded from |
| 90 | // UTF-16 to UTF-8, or if an escape sequence causes characters to be skipped. |
| 91 | // This class centralizes that logic. |
| 92 | class StringBuilder { |
| 93 | public: |
| 94 | // Empty constructor. Used for creating a builder with which to assign to. |
| 95 | StringBuilder(); |
| 96 |
| 97 | // |pos| is the beginning of an input string, excluding the |"|. |
| 98 | explicit StringBuilder(const char* pos); |
| 99 |
| 100 | ~StringBuilder(); |
| 101 |
| 102 | StringBuilder& operator=(StringBuilder&& other); |
| 103 |
| 104 | // Appends the Unicode code point |point| to the string, either by |
| 105 | // increasing the |length_| of the string if the string has not been |
| 106 | // converted, or by appending the UTF8 bytes for the code point. |
| 107 | void Append(uint32_t point); |
| 108 |
| 109 | // Converts the builder from its default StringPiece to a full std::string, |
| 110 | // performing a copy. Once a builder is converted, it cannot be made a |
| 111 | // StringPiece again. |
| 112 | void Convert(); |
| 113 |
| 114 | // Returns the builder as a string, invalidating all state. This allows |
| 115 | // the internal string buffer representation to be destructively moved |
| 116 | // in cases where the builder will not be needed any more. |
| 117 | std::string DestructiveAsString(); |
| 118 |
| 119 | private: |
| 120 | // The beginning of the input string. |
| 121 | const char* pos_; |
| 122 |
| 123 | // Number of bytes in |pos_| that make up the string being built. |
| 124 | size_t length_; |
| 125 |
| 126 | // The copied string representation. Will be unset until Convert() is |
| 127 | // called. |
| 128 | base::Optional<std::string> string_; |
| 129 | }; |
| 130 |
| 131 | // Returns the next |count| bytes of the input stream, or nullopt if fewer |
| 132 | // than |count| bytes remain. |
| 133 | Optional<StringPiece> PeekChars(size_t count); |
| 134 |
| 135 | // Calls PeekChars() with a |count| of 1. |
| 136 | Optional<char> PeekChar(); |
| 137 |
| 138 | // Returns the next |count| bytes of the input stream, or nullopt if fewer |
| 139 | // than |count| bytes remain, and advances the parser position by |count|. |
| 140 | Optional<StringPiece> ConsumeChars(size_t count); |
| 141 |
| 142 | // Calls ConsumeChars() with a |count| of 1. |
| 143 | Optional<char> ConsumeChar(); |
| 144 |
| 145 | // Returns a pointer to the current character position. |
| 146 | const char* pos(); |
| 147 |
| 148 | // Skips over whitespace and comments to find the next token in the stream. |
| 149 | // This does not advance the parser for non-whitespace or comment chars. |
| 150 | Token GetNextToken(); |
| 151 |
| 152 | // Consumes whitespace characters and comments until the next non-that is |
| 153 | // encountered. |
| 154 | void EatWhitespaceAndComments(); |
| 155 | // Helper function that consumes a comment, assuming that the parser is |
| 156 | // currently wound to a '/'. |
| 157 | bool EatComment(); |
| 158 |
| 159 | // Calls GetNextToken() and then ParseToken(). |
| 160 | Optional<Value> ParseNextToken(); |
| 161 |
| 162 | // Takes a token that represents the start of a Value ("a structural token" |
| 163 | // in RFC terms) and consumes it, returning the result as a Value. |
| 164 | Optional<Value> ParseToken(Token token); |
| 165 |
| 166 | // Assuming that the parser is currently wound to '{', this parses a JSON |
| 167 | // object into a Value. |
| 168 | Optional<Value> ConsumeDictionary(); |
| 169 |
| 170 | // Assuming that the parser is wound to '[', this parses a JSON list into a |
| 171 | // Value. |
| 172 | Optional<Value> ConsumeList(); |
| 173 |
| 174 | // Calls through ConsumeStringRaw and wraps it in a value. |
| 175 | Optional<Value> ConsumeString(); |
| 176 |
| 177 | // Assuming that the parser is wound to a double quote, this parses a string, |
| 178 | // decoding any escape sequences and converts UTF-16 to UTF-8. Returns true on |
| 179 | // success and places result into |out|. Returns false on failure with |
| 180 | // error information set. |
| 181 | bool ConsumeStringRaw(StringBuilder* out); |
| 182 | // Helper function for ConsumeStringRaw() that consumes the next four or 10 |
| 183 | // bytes (parser is wound to the first character of a HEX sequence, with the |
| 184 | // potential for consuming another \uXXXX for a surrogate). Returns true on |
| 185 | // success and places the code point |out_code_point|, and false on failure. |
| 186 | bool DecodeUTF16(uint32_t* out_code_point); |
| 187 |
| 188 | // Assuming that the parser is wound to the start of a valid JSON number, |
| 189 | // this parses and converts it to either an int or double value. |
| 190 | Optional<Value> ConsumeNumber(); |
| 191 | // Helper that reads characters that are ints. Returns true if a number was |
| 192 | // read and false on error. |
| 193 | bool ReadInt(bool allow_leading_zeros); |
| 194 |
| 195 | // Consumes the literal values of |true|, |false|, and |null|, assuming the |
| 196 | // parser is wound to the first character of any of those. |
| 197 | Optional<Value> ConsumeLiteral(); |
| 198 |
| 199 | // Helper function that returns true if the byte squence |match| can be |
| 200 | // consumed at the current parser position. Returns false if there are fewer |
| 201 | // than |match|-length bytes or if the sequence does not match, and the |
| 202 | // parser state is unchanged. |
| 203 | bool ConsumeIfMatch(StringPiece match); |
| 204 |
| 205 | // Sets the error information to |code| at the current column, based on |
| 206 | // |index_| and |index_last_line_|, with an optional positive/negative |
| 207 | // adjustment by |column_adjust|. |
| 208 | void ReportError(JSONReader::JsonParseError code, int column_adjust); |
| 209 |
| 210 | // Given the line and column number of an error, formats one of the error |
| 211 | // message contants from json_reader.h for human display. |
| 212 | static std::string FormatErrorMessage(int line, int column, |
| 213 | const std::string& description); |
| 214 |
| 215 | // base::JSONParserOptions that control parsing. |
| 216 | const int options_; |
| 217 |
| 218 | // Maximum depth to parse. |
| 219 | const size_t max_depth_; |
| 220 |
| 221 | // The input stream being parsed. Note: Not guaranteed to NUL-terminated. |
| 222 | StringPiece input_; |
| 223 |
| 224 | // The index in the input stream to which the parser is wound. |
| 225 | int index_; |
| 226 |
| 227 | // The number of times the parser has recursed (current stack depth). |
| 228 | size_t stack_depth_; |
| 229 |
| 230 | // The line number that the parser is at currently. |
| 231 | int line_number_; |
| 232 |
| 233 | // The last value of |index_| on the previous line. |
| 234 | int index_last_line_; |
| 235 |
| 236 | // Error information. |
| 237 | JSONReader::JsonParseError error_code_; |
| 238 | int error_line_; |
| 239 | int error_column_; |
| 240 |
| 241 | friend class JSONParserTest; |
| 242 | FRIEND_TEST_ALL_PREFIXES(JSONParserTest, NextChar); |
| 243 | FRIEND_TEST_ALL_PREFIXES(JSONParserTest, ConsumeDictionary); |
| 244 | FRIEND_TEST_ALL_PREFIXES(JSONParserTest, ConsumeList); |
| 245 | FRIEND_TEST_ALL_PREFIXES(JSONParserTest, ConsumeString); |
| 246 | FRIEND_TEST_ALL_PREFIXES(JSONParserTest, ConsumeLiterals); |
| 247 | FRIEND_TEST_ALL_PREFIXES(JSONParserTest, ConsumeNumbers); |
| 248 | FRIEND_TEST_ALL_PREFIXES(JSONParserTest, ErrorMessages); |
| 249 | FRIEND_TEST_ALL_PREFIXES(JSONParserTest, ReplaceInvalidCharacters); |
| 250 | FRIEND_TEST_ALL_PREFIXES(JSONParserTest, ReplaceInvalidUTF16EscapeSequence); |
| 251 |
| 252 | DISALLOW_COPY_AND_ASSIGN(JSONParser); |
| 253 | }; |
| 254 |
| 255 | // Used when decoding and an invalid utf-8 sequence is encountered. |
| 256 | BASE_EXPORT extern const char kUnicodeReplacementString[]; |
| 257 |
| 258 | } // namespace internal |
| 259 | } // namespace base |
| 260 |
| 261 | #endif // BASE_JSON_JSON_PARSER_H_ |
| 262 |