1 // Copyright 2011 the V8 project authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #ifndef V8_JSON_PARSER_H_
6 #define V8_JSON_PARSER_H_
10 #include "src/char-predicates-inl.h"
11 #include "src/conversions.h"
12 #include "src/heap/spaces-inl.h"
13 #include "src/messages.h"
14 #include "src/token.h"
19 // A simple json parser.
20 template <bool seq_one_byte>
21 class JsonParser BASE_EMBEDDED {
23 MUST_USE_RESULT static MaybeHandle<Object> Parse(Handle<String> source) {
24 return JsonParser(source).ParseJson();
27 static const int kEndOfString = -1;
30 explicit JsonParser(Handle<String> source)
32 source_length_(source->length()),
33 isolate_(source->map()->GetHeap()->isolate()),
34 factory_(isolate_->factory()),
35 object_constructor_(isolate_->native_context()->object_function(),
38 source_ = String::Flatten(source_);
39 pretenure_ = (source_length_ >= kPretenureTreshold) ? TENURED : NOT_TENURED;
41 // Optimized fast case where we only have Latin1 characters.
43 seq_source_ = Handle<SeqOneByteString>::cast(source_);
47 // Parse a string containing a single JSON value.
48 MaybeHandle<Object> ParseJson();
50 inline void Advance() {
52 if (position_ >= source_length_) {
54 } else if (seq_one_byte) {
55 c0_ = seq_source_->SeqOneByteStringGet(position_);
57 c0_ = source_->Get(position_);
61 // The JSON lexical grammar is specified in the ECMAScript 5 standard,
62 // section 15.12.1.1. The only allowed whitespace characters between tokens
63 // are tab, carriage-return, newline and space.
65 inline void AdvanceSkipWhitespace() {
68 } while (c0_ == ' ' || c0_ == '\t' || c0_ == '\n' || c0_ == '\r');
71 inline void SkipWhitespace() {
72 while (c0_ == ' ' || c0_ == '\t' || c0_ == '\n' || c0_ == '\r') {
77 inline uc32 AdvanceGetChar() {
82 // Checks that current charater is c.
83 // If so, then consume c and skip whitespace.
84 inline bool MatchSkipWhiteSpace(uc32 c) {
86 AdvanceSkipWhitespace();
92 // A JSON string (production JSONString) is subset of valid JavaScript string
93 // literals. The string must only be double-quoted (not single-quoted), and
94 // the only allowed backslash-escapes are ", /, \, b, f, n, r, t and
95 // four-digit hex escapes (uXXXX). Any other use of backslashes is invalid.
96 Handle<String> ParseJsonString() {
97 return ScanJsonString<false>();
100 bool ParseJsonString(Handle<String> expected) {
101 int length = expected->length();
102 if (source_->length() - position_ - 1 > length) {
103 DisallowHeapAllocation no_gc;
104 String::FlatContent content = expected->GetFlatContent();
105 if (content.IsOneByte()) {
107 const uint8_t* input_chars = seq_source_->GetChars() + position_ + 1;
108 const uint8_t* expected_chars = content.ToOneByteVector().start();
109 for (int i = 0; i < length; i++) {
110 uint8_t c0 = input_chars[i];
111 if (c0 != expected_chars[i] || c0 == '"' || c0 < 0x20 || c0 == '\\') {
115 if (input_chars[length] == '"') {
116 position_ = position_ + length + 1;
117 AdvanceSkipWhitespace();
125 Handle<String> ParseJsonInternalizedString() {
126 return ScanJsonString<true>();
129 template <bool is_internalized>
130 Handle<String> ScanJsonString();
131 // Creates a new string and copies prefix[start..end] into the beginning
132 // of it. Then scans the rest of the string, adding characters after the
133 // prefix. Called by ScanJsonString when reaching a '\' or non-Latin1 char.
134 template <typename StringType, typename SinkChar>
135 Handle<String> SlowScanJsonString(Handle<String> prefix, int start, int end);
137 // A JSON number (production JSONNumber) is a subset of the valid JavaScript
138 // decimal number literals.
139 // It includes an optional minus sign, must have at least one
140 // digit before and after a decimal point, may not have prefixed zeros (unless
141 // the integer part is zero), and may include an exponent part (e.g., "e-10").
142 // Hexadecimal and octal numbers are not allowed.
143 Handle<Object> ParseJsonNumber();
145 // Parse a single JSON value from input (grammar production JSONValue).
146 // A JSON value is either a (double-quoted) string literal, a number literal,
147 // one of "true", "false", or "null", or an object or array literal.
148 Handle<Object> ParseJsonValue();
150 // Parse a JSON object literal (grammar production JSONObject).
151 // An object literal is a squiggly-braced and comma separated sequence
152 // (possibly empty) of key/value pairs, where the key is a JSON string
153 // literal, the value is a JSON value, and the two are separated by a colon.
154 // A JSON array doesn't allow numbers and identifiers as keys, like a
156 Handle<Object> ParseJsonObject();
158 // Parses a JSON array literal (grammar production JSONArray). An array
159 // literal is a square-bracketed and comma separated sequence (possibly empty)
161 // A JSON array doesn't allow leaving out values from the sequence, nor does
162 // it allow a terminal comma, like a JavaScript array does.
163 Handle<Object> ParseJsonArray();
166 // Mark that a parsing error has happened at the current token, and
167 // return a null handle. Primarily for readability.
168 inline Handle<Object> ReportUnexpectedCharacter() {
169 return Handle<Object>::null();
172 inline Isolate* isolate() { return isolate_; }
173 inline Factory* factory() { return factory_; }
174 inline Handle<JSFunction> object_constructor() { return object_constructor_; }
176 static const int kInitialSpecialStringLength = 32;
177 static const int kPretenureTreshold = 100 * 1024;
181 Zone* zone() { return &zone_; }
183 void CommitStateToJsonObject(Handle<JSObject> json_object, Handle<Map> map,
184 ZoneList<Handle<Object> >* properties);
186 Handle<String> source_;
188 Handle<SeqOneByteString> seq_source_;
190 PretenureFlag pretenure_;
194 Handle<JSFunction> object_constructor_;
199 template <bool seq_one_byte>
200 MaybeHandle<Object> JsonParser<seq_one_byte>::ParseJson() {
201 // Advance to the first character (possibly EOS)
202 AdvanceSkipWhitespace();
203 Handle<Object> result = ParseJsonValue();
204 if (result.is_null() || c0_ != kEndOfString) {
205 // Some exception (for example stack overflow) is already pending.
206 if (isolate_->has_pending_exception()) return Handle<Object>::null();
208 // Parse failed. Current character is the unexpected token.
210 Factory* factory = this->factory();
211 Handle<JSArray> array;
215 message = "unexpected_eos";
216 array = factory->NewJSArray(0);
229 message = "unexpected_token_number";
230 array = factory->NewJSArray(0);
233 message = "unexpected_token_string";
234 array = factory->NewJSArray(0);
237 message = "unexpected_token";
238 Handle<Object> name = factory->LookupSingleCharacterStringFromCode(c0_);
239 Handle<FixedArray> element = factory->NewFixedArray(1);
240 element->set(0, *name);
241 array = factory->NewJSArrayWithElements(element);
245 MessageLocation location(factory->NewScript(source_),
248 Handle<Object> error = factory->NewSyntaxError(message, array);
249 return isolate()->template Throw<Object>(error, &location);
255 // Parse any JSON value.
256 template <bool seq_one_byte>
257 Handle<Object> JsonParser<seq_one_byte>::ParseJsonValue() {
258 StackLimitCheck stack_check(isolate_);
259 if (stack_check.HasOverflowed()) {
260 isolate_->StackOverflow();
261 return Handle<Object>::null();
264 if (isolate_->stack_guard()->InterruptRequested()) {
265 ExecutionAccess access(isolate_);
266 // Avoid blocking GC in long running parser (v8:3974).
267 isolate_->stack_guard()->CheckAndHandleGCInterrupt();
270 if (c0_ == '"') return ParseJsonString();
271 if ((c0_ >= '0' && c0_ <= '9') || c0_ == '-') return ParseJsonNumber();
272 if (c0_ == '{') return ParseJsonObject();
273 if (c0_ == '[') return ParseJsonArray();
275 if (AdvanceGetChar() == 'a' && AdvanceGetChar() == 'l' &&
276 AdvanceGetChar() == 's' && AdvanceGetChar() == 'e') {
277 AdvanceSkipWhitespace();
278 return factory()->false_value();
280 return ReportUnexpectedCharacter();
283 if (AdvanceGetChar() == 'r' && AdvanceGetChar() == 'u' &&
284 AdvanceGetChar() == 'e') {
285 AdvanceSkipWhitespace();
286 return factory()->true_value();
288 return ReportUnexpectedCharacter();
291 if (AdvanceGetChar() == 'u' && AdvanceGetChar() == 'l' &&
292 AdvanceGetChar() == 'l') {
293 AdvanceSkipWhitespace();
294 return factory()->null_value();
296 return ReportUnexpectedCharacter();
298 return ReportUnexpectedCharacter();
302 // Parse a JSON object. Position must be right at '{'.
303 template <bool seq_one_byte>
304 Handle<Object> JsonParser<seq_one_byte>::ParseJsonObject() {
305 HandleScope scope(isolate());
306 Handle<JSObject> json_object =
307 factory()->NewJSObject(object_constructor(), pretenure_);
308 Handle<Map> map(json_object->map());
310 ZoneList<Handle<Object> > properties(8, zone());
313 bool transitioning = true;
315 AdvanceSkipWhitespace();
318 if (c0_ != '"') return ReportUnexpectedCharacter();
320 int start_position = position_;
324 if (IsDecimalDigit(c0_)) {
325 // Maybe an array index, try to parse it.
327 // With a leading zero, the string has to be "0" only to be an index.
332 if (index > 429496729U - ((d > 5) ? 1 : 0)) break;
333 index = (index * 10) + d;
335 } while (IsDecimalDigit(c0_));
339 // Successfully parsed index, parse and store element.
340 AdvanceSkipWhitespace();
342 if (c0_ != ':') return ReportUnexpectedCharacter();
343 AdvanceSkipWhitespace();
344 Handle<Object> value = ParseJsonValue();
345 if (value.is_null()) return ReportUnexpectedCharacter();
347 JSObject::SetOwnElement(json_object, index, value, SLOPPY).Assert();
350 // Not an index, fallback to the slow path.
353 position_ = start_position;
359 Handle<Object> value;
361 // Try to follow existing transitions as long as possible. Once we stop
362 // transitioning, no transition can be found anymore.
364 // First check whether there is a single expected transition. If so, try
365 // to parse it first.
366 bool follow_expected = false;
369 key = TransitionArray::ExpectedTransitionKey(map);
370 follow_expected = !key.is_null() && ParseJsonString(key);
372 // If the expected transition hits, follow it.
373 if (follow_expected) {
374 target = TransitionArray::ExpectedTransitionTarget(map);
376 // If the expected transition failed, parse an internalized string and
377 // try to find a matching transition.
378 key = ParseJsonInternalizedString();
379 if (key.is_null()) return ReportUnexpectedCharacter();
381 target = TransitionArray::FindTransitionToField(map, key);
382 // If a transition was found, follow it and continue.
383 transitioning = !target.is_null();
385 if (c0_ != ':') return ReportUnexpectedCharacter();
387 AdvanceSkipWhitespace();
388 value = ParseJsonValue();
389 if (value.is_null()) return ReportUnexpectedCharacter();
392 PropertyDetails details =
393 target->instance_descriptors()->GetDetails(descriptor);
394 Representation expected_representation = details.representation();
396 if (value->FitsRepresentation(expected_representation)) {
397 if (expected_representation.IsHeapObject() &&
398 !target->instance_descriptors()
399 ->GetFieldType(descriptor)
400 ->NowContains(value)) {
401 Handle<HeapType> value_type(value->OptimalType(
402 isolate(), expected_representation));
403 Map::GeneralizeFieldType(target, descriptor,
404 expected_representation, value_type);
406 DCHECK(target->instance_descriptors()->GetFieldType(
407 descriptor)->NowContains(value));
408 properties.Add(value, zone());
413 transitioning = false;
417 // Commit the intermediate state to the object and stop transitioning.
418 CommitStateToJsonObject(json_object, map, &properties);
420 key = ParseJsonInternalizedString();
421 if (key.is_null() || c0_ != ':') return ReportUnexpectedCharacter();
423 AdvanceSkipWhitespace();
424 value = ParseJsonValue();
425 if (value.is_null()) return ReportUnexpectedCharacter();
428 Runtime::DefineObjectProperty(json_object, key, value, NONE).Check();
429 } while (MatchSkipWhiteSpace(','));
431 return ReportUnexpectedCharacter();
434 // If we transitioned until the very end, transition the map now.
436 CommitStateToJsonObject(json_object, map, &properties);
439 AdvanceSkipWhitespace();
440 return scope.CloseAndEscape(json_object);
444 template <bool seq_one_byte>
445 void JsonParser<seq_one_byte>::CommitStateToJsonObject(
446 Handle<JSObject> json_object, Handle<Map> map,
447 ZoneList<Handle<Object> >* properties) {
448 JSObject::AllocateStorageForMap(json_object, map);
449 DCHECK(!json_object->map()->is_dictionary_map());
451 DisallowHeapAllocation no_gc;
453 int length = properties->length();
454 for (int i = 0; i < length; i++) {
455 Handle<Object> value = (*properties)[i];
456 json_object->WriteToField(i, *value);
461 // Parse a JSON array. Position must be right at '['.
462 template <bool seq_one_byte>
463 Handle<Object> JsonParser<seq_one_byte>::ParseJsonArray() {
464 HandleScope scope(isolate());
465 ZoneList<Handle<Object> > elements(4, zone());
468 AdvanceSkipWhitespace();
471 Handle<Object> element = ParseJsonValue();
472 if (element.is_null()) return ReportUnexpectedCharacter();
473 elements.Add(element, zone());
474 } while (MatchSkipWhiteSpace(','));
476 return ReportUnexpectedCharacter();
479 AdvanceSkipWhitespace();
480 // Allocate a fixed array with all the elements.
481 Handle<FixedArray> fast_elements =
482 factory()->NewFixedArray(elements.length(), pretenure_);
483 for (int i = 0, n = elements.length(); i < n; i++) {
484 fast_elements->set(i, *elements[i]);
486 Handle<Object> json_array = factory()->NewJSArrayWithElements(
487 fast_elements, FAST_ELEMENTS, pretenure_);
488 return scope.CloseAndEscape(json_array);
492 template <bool seq_one_byte>
493 Handle<Object> JsonParser<seq_one_byte>::ParseJsonNumber() {
494 bool negative = false;
495 int beg_pos = position_;
502 // Prefix zero is only allowed if it's the only digit before
503 // a decimal point or exponent.
504 if (IsDecimalDigit(c0_)) return ReportUnexpectedCharacter();
508 if (c0_ < '1' || c0_ > '9') return ReportUnexpectedCharacter();
510 i = i * 10 + c0_ - '0';
513 } while (IsDecimalDigit(c0_));
514 if (c0_ != '.' && c0_ != 'e' && c0_ != 'E' && digits < 10) {
516 return Handle<Smi>(Smi::FromInt((negative ? -i : i)), isolate());
521 if (!IsDecimalDigit(c0_)) return ReportUnexpectedCharacter();
524 } while (IsDecimalDigit(c0_));
526 if (AsciiAlphaToLower(c0_) == 'e') {
528 if (c0_ == '-' || c0_ == '+') Advance();
529 if (!IsDecimalDigit(c0_)) return ReportUnexpectedCharacter();
532 } while (IsDecimalDigit(c0_));
534 int length = position_ - beg_pos;
537 Vector<const uint8_t> chars(seq_source_->GetChars() + beg_pos, length);
538 number = StringToDouble(isolate()->unicode_cache(), chars,
539 NO_FLAGS, // Hex, octal or trailing junk.
540 std::numeric_limits<double>::quiet_NaN());
542 Vector<uint8_t> buffer = Vector<uint8_t>::New(length);
543 String::WriteToFlat(*source_, buffer.start(), beg_pos, position_);
544 Vector<const uint8_t> result =
545 Vector<const uint8_t>(buffer.start(), length);
546 number = StringToDouble(isolate()->unicode_cache(),
548 NO_FLAGS, // Hex, octal or trailing junk.
553 return factory()->NewNumber(number, pretenure_);
557 template <typename StringType>
558 inline void SeqStringSet(Handle<StringType> seq_str, int i, uc32 c);
561 inline void SeqStringSet(Handle<SeqTwoByteString> seq_str, int i, uc32 c) {
562 seq_str->SeqTwoByteStringSet(i, c);
566 inline void SeqStringSet(Handle<SeqOneByteString> seq_str, int i, uc32 c) {
567 seq_str->SeqOneByteStringSet(i, c);
570 template <typename StringType>
571 inline Handle<StringType> NewRawString(Factory* factory,
573 PretenureFlag pretenure);
576 inline Handle<SeqTwoByteString> NewRawString(Factory* factory,
578 PretenureFlag pretenure) {
579 return factory->NewRawTwoByteString(length, pretenure).ToHandleChecked();
583 inline Handle<SeqOneByteString> NewRawString(Factory* factory,
585 PretenureFlag pretenure) {
586 return factory->NewRawOneByteString(length, pretenure).ToHandleChecked();
590 // Scans the rest of a JSON string starting from position_ and writes
591 // prefix[start..end] along with the scanned characters into a
592 // sequential string of type StringType.
593 template <bool seq_one_byte>
594 template <typename StringType, typename SinkChar>
595 Handle<String> JsonParser<seq_one_byte>::SlowScanJsonString(
596 Handle<String> prefix, int start, int end) {
597 int count = end - start;
598 int max_length = count + source_length_ - position_;
599 int length = Min(max_length, Max(kInitialSpecialStringLength, 2 * count));
600 Handle<StringType> seq_string =
601 NewRawString<StringType>(factory(), length, pretenure_);
602 // Copy prefix into seq_str.
603 SinkChar* dest = seq_string->GetChars();
604 String::WriteToFlat(*prefix, dest, start, end);
607 // Check for control character (0x00-0x1f) or unterminated string (<0).
608 if (c0_ < 0x20) return Handle<String>::null();
609 if (count >= length) {
610 // We need to create a longer sequential string for the result.
611 return SlowScanJsonString<StringType, SinkChar>(seq_string, 0, count);
614 // If the sink can contain UC16 characters, or source_ contains only
615 // Latin1 characters, there's no need to test whether we can store the
616 // character. Otherwise check whether the UC16 source character can fit
617 // in the Latin1 sink.
618 if (sizeof(SinkChar) == kUC16Size || seq_one_byte ||
619 c0_ <= String::kMaxOneByteCharCode) {
620 SeqStringSet(seq_string, count++, c0_);
623 // StringType is SeqOneByteString and we just read a non-Latin1 char.
624 return SlowScanJsonString<SeqTwoByteString, uc16>(seq_string, 0, count);
627 Advance(); // Advance past the \.
632 SeqStringSet(seq_string, count++, c0_);
635 SeqStringSet(seq_string, count++, '\x08');
638 SeqStringSet(seq_string, count++, '\x0c');
641 SeqStringSet(seq_string, count++, '\x0a');
644 SeqStringSet(seq_string, count++, '\x0d');
647 SeqStringSet(seq_string, count++, '\x09');
651 for (int i = 0; i < 4; i++) {
653 int digit = HexValue(c0_);
655 return Handle<String>::null();
657 value = value * 16 + digit;
659 if (sizeof(SinkChar) == kUC16Size ||
660 value <= String::kMaxOneByteCharCode) {
661 SeqStringSet(seq_string, count++, value);
664 // StringType is SeqOneByteString and we just read a non-Latin1
666 position_ -= 6; // Rewind position_ to \ in \uxxxx.
668 return SlowScanJsonString<SeqTwoByteString, uc16>(seq_string,
674 return Handle<String>::null();
681 // Advance past the last '"'.
682 AdvanceSkipWhitespace();
684 // Shrink seq_string length to count and return.
685 return SeqString::Truncate(seq_string, count);
689 template <bool seq_one_byte>
690 template <bool is_internalized>
691 Handle<String> JsonParser<seq_one_byte>::ScanJsonString() {
695 AdvanceSkipWhitespace();
696 return factory()->empty_string();
699 if (seq_one_byte && is_internalized) {
700 // Fast path for existing internalized strings. If the the string being
701 // parsed is not a known internalized string, contains backslashes or
702 // unexpectedly reaches the end of string, return with an empty handle.
703 uint32_t running_hash = isolate()->heap()->HashSeed();
704 int position = position_;
709 int beg_pos = position_;
710 position_ = position;
711 return SlowScanJsonString<SeqOneByteString, uint8_t>(source_,
715 if (c0 < 0x20) return Handle<String>::null();
716 if (static_cast<uint32_t>(c0) >
717 unibrow::Utf16::kMaxNonSurrogateCharCode) {
719 StringHasher::AddCharacterCore(running_hash,
720 unibrow::Utf16::LeadSurrogate(c0));
722 StringHasher::AddCharacterCore(running_hash,
723 unibrow::Utf16::TrailSurrogate(c0));
725 running_hash = StringHasher::AddCharacterCore(running_hash, c0);
728 if (position >= source_length_) return Handle<String>::null();
729 c0 = seq_source_->SeqOneByteStringGet(position);
731 int length = position - position_;
732 uint32_t hash = (length <= String::kMaxHashCalcLength)
733 ? StringHasher::GetHashCore(running_hash)
734 : static_cast<uint32_t>(length);
735 Vector<const uint8_t> string_vector(
736 seq_source_->GetChars() + position_, length);
737 StringTable* string_table = isolate()->heap()->string_table();
738 uint32_t capacity = string_table->Capacity();
739 uint32_t entry = StringTable::FirstProbe(hash, capacity);
741 Handle<String> result;
743 Object* element = string_table->KeyAt(entry);
744 if (element == isolate()->heap()->undefined_value()) {
746 result = factory()->InternalizeOneByteString(
747 seq_source_, position_, length);
750 if (element != isolate()->heap()->the_hole_value() &&
751 String::cast(element)->IsOneByteEqualTo(string_vector)) {
752 result = Handle<String>(String::cast(element), isolate());
754 uint32_t hash_field =
755 (hash << String::kHashShift) | String::kIsNotArrayIndexMask;
756 DCHECK_EQ(static_cast<int>(result->Hash()),
757 static_cast<int>(hash_field >> String::kHashShift));
761 entry = StringTable::NextProbe(entry, count++, capacity);
763 position_ = position;
764 // Advance past the last '"'.
765 AdvanceSkipWhitespace();
769 int beg_pos = position_;
770 // Fast case for Latin1 only without escape characters.
772 // Check for control character (0x00-0x1f) or unterminated string (<0).
773 if (c0_ < 0x20) return Handle<String>::null();
775 if (seq_one_byte || c0_ <= String::kMaxOneByteCharCode) {
778 return SlowScanJsonString<SeqTwoByteString, uc16>(source_,
783 return SlowScanJsonString<SeqOneByteString, uint8_t>(source_,
787 } while (c0_ != '"');
788 int length = position_ - beg_pos;
789 Handle<String> result =
790 factory()->NewRawOneByteString(length, pretenure_).ToHandleChecked();
791 uint8_t* dest = SeqOneByteString::cast(*result)->GetChars();
792 String::WriteToFlat(*source_, dest, beg_pos, position_);
795 // Advance past the last '"'.
796 AdvanceSkipWhitespace();
800 } } // namespace v8::internal
802 #endif // V8_JSON_PARSER_H_