1 // Copyright 2011 the V8 project authors. All rights reserved.
2 // Redistribution and use in source and binary forms, with or without
3 // modification, are permitted provided that the following conditions are
6 // * Redistributions of source code must retain the above copyright
7 // notice, this list of conditions and the following disclaimer.
8 // * Redistributions in binary form must reproduce the above
9 // copyright notice, this list of conditions and the following
10 // disclaimer in the documentation and/or other materials provided
11 // with the distribution.
12 // * Neither the name of Google Inc. nor the names of its
13 // contributors may be used to endorse or promote products derived
14 // from this software without specific prior written permission.
16 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
20 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28 #ifndef V8_JSON_PARSER_H_
29 #define V8_JSON_PARSER_H_
33 #include "char-predicates-inl.h"
34 #include "v8conversions.h"
36 #include "spaces-inl.h"
42 // A simple json parser.
43 template <bool seq_ascii>
44 class JsonParser BASE_EMBEDDED {
46 static Handle<Object> Parse(Handle<String> source) {
47 return JsonParser().ParseJson(source);
50 static const int kEndOfString = -1;
53 // Parse a string containing a single JSON value.
54 Handle<Object> ParseJson(Handle<String> source);
56 inline void Advance() {
58 if (position_ >= source_length_) {
60 } else if (seq_ascii) {
61 c0_ = seq_source_->SeqAsciiStringGet(position_);
63 c0_ = source_->Get(position_);
67 // The JSON lexical grammar is specified in the ECMAScript 5 standard,
68 // section 15.12.1.1. The only allowed whitespace characters between tokens
69 // are tab, carriage-return, newline and space.
71 inline void AdvanceSkipWhitespace() {
74 } while (c0_ == '\t' || c0_ == '\r' || c0_ == '\n' || c0_ == ' ');
77 inline void SkipWhitespace() {
78 while (c0_ == '\t' || c0_ == '\r' || c0_ == '\n' || c0_ == ' ') {
83 inline uc32 AdvanceGetChar() {
88 // Checks that current charater is c.
89 // If so, then consume c and skip whitespace.
90 inline bool MatchSkipWhiteSpace(uc32 c) {
92 AdvanceSkipWhitespace();
98 // A JSON string (production JSONString) is subset of valid JavaScript string
99 // literals. The string must only be double-quoted (not single-quoted), and
100 // the only allowed backslash-escapes are ", /, \, b, f, n, r, t and
101 // four-digit hex escapes (uXXXX). Any other use of backslashes is invalid.
102 Handle<String> ParseJsonString() {
103 return ScanJsonString<false>();
105 Handle<String> ParseJsonSymbol() {
106 return ScanJsonString<true>();
108 template <bool is_symbol>
109 Handle<String> ScanJsonString();
110 // Creates a new string and copies prefix[start..end] into the beginning
111 // of it. Then scans the rest of the string, adding characters after the
112 // prefix. Called by ScanJsonString when reaching a '\' or non-ASCII char.
113 template <typename StringType, typename SinkChar>
114 Handle<String> SlowScanJsonString(Handle<String> prefix, int start, int end);
116 // A JSON number (production JSONNumber) is a subset of the valid JavaScript
117 // decimal number literals.
118 // It includes an optional minus sign, must have at least one
119 // digit before and after a decimal point, may not have prefixed zeros (unless
120 // the integer part is zero), and may include an exponent part (e.g., "e-10").
121 // Hexadecimal and octal numbers are not allowed.
122 Handle<Object> ParseJsonNumber();
124 // Parse a single JSON value from input (grammar production JSONValue).
125 // A JSON value is either a (double-quoted) string literal, a number literal,
126 // one of "true", "false", or "null", or an object or array literal.
127 Handle<Object> ParseJsonValue();
129 // Parse a JSON object literal (grammar production JSONObject).
130 // An object literal is a squiggly-braced and comma separated sequence
131 // (possibly empty) of key/value pairs, where the key is a JSON string
132 // literal, the value is a JSON value, and the two are separated by a colon.
133 // A JSON array doesn't allow numbers and identifiers as keys, like a
135 Handle<Object> ParseJsonObject();
137 // Parses a JSON array literal (grammar production JSONArray). An array
138 // literal is a square-bracketed and comma separated sequence (possibly empty)
140 // A JSON array doesn't allow leaving out values from the sequence, nor does
141 // it allow a terminal comma, like a JavaScript array does.
142 Handle<Object> ParseJsonArray();
145 // Mark that a parsing error has happened at the current token, and
146 // return a null handle. Primarily for readability.
147 inline Handle<Object> ReportUnexpectedCharacter() {
148 return Handle<Object>::null();
151 inline Isolate* isolate() { return isolate_; }
153 static const int kInitialSpecialStringLength = 1024;
157 Handle<String> source_;
159 Handle<SeqAsciiString> seq_source_;
166 template <bool seq_ascii>
167 Handle<Object> JsonParser<seq_ascii>::ParseJson(Handle<String> source) {
168 isolate_ = source->map()->GetHeap()->isolate();
169 FlattenString(source);
171 source_length_ = source_->length();
173 // Optimized fast case where we only have ASCII characters.
175 seq_source_ = Handle<SeqAsciiString>::cast(source_);
178 // Set initial position right before the string.
180 // Advance to the first character (possibly EOS)
181 AdvanceSkipWhitespace();
182 Handle<Object> result = ParseJsonValue();
183 if (result.is_null() || c0_ != kEndOfString) {
184 // Parse failed. Current character is the unexpected token.
187 Factory* factory = isolate()->factory();
188 Handle<JSArray> array;
192 message = "unexpected_eos";
193 array = factory->NewJSArray(0);
206 message = "unexpected_token_number";
207 array = factory->NewJSArray(0);
210 message = "unexpected_token_string";
211 array = factory->NewJSArray(0);
214 message = "unexpected_token";
215 Handle<Object> name = LookupSingleCharacterStringFromCode(c0_);
216 Handle<FixedArray> element = factory->NewFixedArray(1);
217 element->set(0, *name);
218 array = factory->NewJSArrayWithElements(element);
222 MessageLocation location(factory->NewScript(source),
225 Handle<Object> result = factory->NewSyntaxError(message, array);
226 isolate()->Throw(*result, &location);
227 return Handle<Object>::null();
233 // Parse any JSON value.
234 template <bool seq_ascii>
235 Handle<Object> JsonParser<seq_ascii>::ParseJsonValue() {
238 return ParseJsonString();
250 return ParseJsonNumber();
252 if (AdvanceGetChar() == 'a' && AdvanceGetChar() == 'l' &&
253 AdvanceGetChar() == 's' && AdvanceGetChar() == 'e') {
254 AdvanceSkipWhitespace();
255 return isolate()->factory()->false_value();
257 return ReportUnexpectedCharacter();
260 if (AdvanceGetChar() == 'r' && AdvanceGetChar() == 'u' &&
261 AdvanceGetChar() == 'e') {
262 AdvanceSkipWhitespace();
263 return isolate()->factory()->true_value();
265 return ReportUnexpectedCharacter();
268 if (AdvanceGetChar() == 'u' && AdvanceGetChar() == 'l' &&
269 AdvanceGetChar() == 'l') {
270 AdvanceSkipWhitespace();
271 return isolate()->factory()->null_value();
273 return ReportUnexpectedCharacter();
276 return ParseJsonObject();
278 return ParseJsonArray();
280 return ReportUnexpectedCharacter();
285 // Parse a JSON object. Position must be right at '{'.
286 template <bool seq_ascii>
287 Handle<Object> JsonParser<seq_ascii>::ParseJsonObject() {
288 Handle<JSFunction> object_constructor(
289 isolate()->global_context()->object_function());
290 Handle<JSObject> json_object =
291 isolate()->factory()->NewJSObject(object_constructor);
294 AdvanceSkipWhitespace();
297 if (c0_ != '"') return ReportUnexpectedCharacter();
298 Handle<String> key = ParseJsonSymbol();
299 if (key.is_null() || c0_ != ':') return ReportUnexpectedCharacter();
300 AdvanceSkipWhitespace();
301 Handle<Object> value = ParseJsonValue();
302 if (value.is_null()) return ReportUnexpectedCharacter();
305 if (key->AsArrayIndex(&index)) {
306 JSObject::SetOwnElement(json_object, index, value, kNonStrictMode);
307 } else if (key->Equals(isolate()->heap()->Proto_symbol())) {
308 SetPrototype(json_object, value);
310 JSObject::SetLocalPropertyIgnoreAttributes(
311 json_object, key, value, NONE);
313 } while (MatchSkipWhiteSpace(','));
315 return ReportUnexpectedCharacter();
318 AdvanceSkipWhitespace();
322 // Parse a JSON array. Position must be right at '['.
323 template <bool seq_ascii>
324 Handle<Object> JsonParser<seq_ascii>::ParseJsonArray() {
325 ZoneScope zone_scope(isolate(), DELETE_ON_EXIT);
326 ZoneList<Handle<Object> > elements(4);
329 AdvanceSkipWhitespace();
332 Handle<Object> element = ParseJsonValue();
333 if (element.is_null()) return ReportUnexpectedCharacter();
334 elements.Add(element);
335 } while (MatchSkipWhiteSpace(','));
337 return ReportUnexpectedCharacter();
340 AdvanceSkipWhitespace();
341 // Allocate a fixed array with all the elements.
342 Handle<FixedArray> fast_elements =
343 isolate()->factory()->NewFixedArray(elements.length());
344 for (int i = 0, n = elements.length(); i < n; i++) {
345 fast_elements->set(i, *elements[i]);
347 return isolate()->factory()->NewJSArrayWithElements(fast_elements);
351 template <bool seq_ascii>
352 Handle<Object> JsonParser<seq_ascii>::ParseJsonNumber() {
353 bool negative = false;
354 int beg_pos = position_;
361 // Prefix zero is only allowed if it's the only digit before
362 // a decimal point or exponent.
363 if ('0' <= c0_ && c0_ <= '9') return ReportUnexpectedCharacter();
367 if (c0_ < '1' || c0_ > '9') return ReportUnexpectedCharacter();
369 i = i * 10 + c0_ - '0';
372 } while (c0_ >= '0' && c0_ <= '9');
373 if (c0_ != '.' && c0_ != 'e' && c0_ != 'E' && digits < 10) {
375 return Handle<Smi>(Smi::FromInt((negative ? -i : i)), isolate());
380 if (c0_ < '0' || c0_ > '9') return ReportUnexpectedCharacter();
383 } while (c0_ >= '0' && c0_ <= '9');
385 if (AsciiAlphaToLower(c0_) == 'e') {
387 if (c0_ == '-' || c0_ == '+') Advance();
388 if (c0_ < '0' || c0_ > '9') return ReportUnexpectedCharacter();
391 } while (c0_ >= '0' && c0_ <= '9');
393 int length = position_ - beg_pos;
396 Vector<const char> chars(seq_source_->GetChars() + beg_pos, length);
397 number = StringToDouble(isolate()->unicode_cache(),
399 NO_FLAGS, // Hex, octal or trailing junk.
402 Vector<char> buffer = Vector<char>::New(length);
403 String::WriteToFlat(*source_, buffer.start(), beg_pos, position_);
404 Vector<const char> result =
405 Vector<const char>(reinterpret_cast<const char*>(buffer.start()),
407 number = StringToDouble(isolate()->unicode_cache(),
409 NO_FLAGS, // Hex, octal or trailing junk.
414 return isolate()->factory()->NewNumber(number);
418 template <typename StringType>
419 inline void SeqStringSet(Handle<StringType> seq_str, int i, uc32 c);
422 inline void SeqStringSet(Handle<SeqTwoByteString> seq_str, int i, uc32 c) {
423 seq_str->SeqTwoByteStringSet(i, c);
427 inline void SeqStringSet(Handle<SeqAsciiString> seq_str, int i, uc32 c) {
428 seq_str->SeqAsciiStringSet(i, c);
431 template <typename StringType>
432 inline Handle<StringType> NewRawString(Factory* factory, int length);
435 inline Handle<SeqTwoByteString> NewRawString(Factory* factory, int length) {
436 return factory->NewRawTwoByteString(length, NOT_TENURED);
440 inline Handle<SeqAsciiString> NewRawString(Factory* factory, int length) {
441 return factory->NewRawAsciiString(length, NOT_TENURED);
445 // Scans the rest of a JSON string starting from position_ and writes
446 // prefix[start..end] along with the scanned characters into a
447 // sequential string of type StringType.
448 template <bool seq_ascii>
449 template <typename StringType, typename SinkChar>
450 Handle<String> JsonParser<seq_ascii>::SlowScanJsonString(
451 Handle<String> prefix, int start, int end) {
452 int count = end - start;
453 int max_length = count + source_length_ - position_;
454 int length = Min(max_length, Max(kInitialSpecialStringLength, 2 * count));
455 Handle<StringType> seq_str = NewRawString<StringType>(isolate()->factory(),
457 // Copy prefix into seq_str.
458 SinkChar* dest = seq_str->GetChars();
459 String::WriteToFlat(*prefix, dest, start, end);
462 // Check for control character (0x00-0x1f) or unterminated string (<0).
463 if (c0_ < 0x20) return Handle<String>::null();
464 if (count >= length) {
465 // We need to create a longer sequential string for the result.
466 return SlowScanJsonString<StringType, SinkChar>(seq_str, 0, count);
469 // If the sink can contain UC16 characters, or source_ contains only
470 // ASCII characters, there's no need to test whether we can store the
471 // character. Otherwise check whether the UC16 source character can fit
472 // in the ASCII sink.
473 if (sizeof(SinkChar) == kUC16Size ||
475 c0_ <= kMaxAsciiCharCode) {
476 SeqStringSet(seq_str, count++, c0_);
479 // StringType is SeqAsciiString and we just read a non-ASCII char.
480 return SlowScanJsonString<SeqTwoByteString, uc16>(seq_str, 0, count);
483 Advance(); // Advance past the \.
488 SeqStringSet(seq_str, count++, c0_);
491 SeqStringSet(seq_str, count++, '\x08');
494 SeqStringSet(seq_str, count++, '\x0c');
497 SeqStringSet(seq_str, count++, '\x0a');
500 SeqStringSet(seq_str, count++, '\x0d');
503 SeqStringSet(seq_str, count++, '\x09');
507 for (int i = 0; i < 4; i++) {
509 int digit = HexValue(c0_);
511 return Handle<String>::null();
513 value = value * 16 + digit;
515 if (sizeof(SinkChar) == kUC16Size || value <= kMaxAsciiCharCode) {
516 SeqStringSet(seq_str, count++, value);
519 // StringType is SeqAsciiString and we just read a non-ASCII char.
520 position_ -= 6; // Rewind position_ to \ in \uxxxx.
522 return SlowScanJsonString<SeqTwoByteString, uc16>(seq_str,
528 return Handle<String>::null();
533 // Shrink seq_string length to count.
534 if (isolate()->heap()->InNewSpace(*seq_str)) {
535 isolate()->heap()->new_space()->
536 template ShrinkStringAtAllocationBoundary<StringType>(
539 int string_size = StringType::SizeFor(count);
540 int allocated_string_size = StringType::SizeFor(length);
541 int delta = allocated_string_size - string_size;
542 Address start_filler_object = seq_str->address() + string_size;
543 seq_str->set_length(count);
544 isolate()->heap()->CreateFillerObjectAt(start_filler_object, delta);
547 // Advance past the last '"'.
548 AdvanceSkipWhitespace();
553 template <bool seq_ascii>
554 template <bool is_symbol>
555 Handle<String> JsonParser<seq_ascii>::ScanJsonString() {
559 AdvanceSkipWhitespace();
560 return Handle<String>(isolate()->heap()->empty_string());
562 int beg_pos = position_;
563 // Fast case for ASCII only without escape characters.
565 // Check for control character (0x00-0x1f) or unterminated string (<0).
566 if (c0_ < 0x20) return Handle<String>::null();
568 if (seq_ascii || c0_ <= kMaxAsciiCharCode) {
571 return SlowScanJsonString<SeqTwoByteString, uc16>(source_,
576 return SlowScanJsonString<SeqAsciiString, char>(source_,
580 } while (c0_ != '"');
581 int length = position_ - beg_pos;
582 Handle<String> result;
583 if (seq_ascii && is_symbol) {
584 result = isolate()->factory()->LookupAsciiSymbol(seq_source_,
588 result = isolate()->factory()->NewRawAsciiString(length);
589 char* dest = SeqAsciiString::cast(*result)->GetChars();
590 String::WriteToFlat(*source_, dest, beg_pos, position_);
593 // Advance past the last '"'.
594 AdvanceSkipWhitespace();
598 } } // namespace v8::internal
600 #endif // V8_JSON_PARSER_H_