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 // The expected string has to be free of \, " and characters < 0x20.
112 if (c0 != expected_chars[i]) return false;
114 if (input_chars[length] == '"') {
115 position_ = position_ + length + 1;
116 AdvanceSkipWhitespace();
124 Handle<String> ParseJsonInternalizedString() {
125 return ScanJsonString<true>();
128 template <bool is_internalized>
129 Handle<String> ScanJsonString();
130 // Creates a new string and copies prefix[start..end] into the beginning
131 // of it. Then scans the rest of the string, adding characters after the
132 // prefix. Called by ScanJsonString when reaching a '\' or non-Latin1 char.
133 template <typename StringType, typename SinkChar>
134 Handle<String> SlowScanJsonString(Handle<String> prefix, int start, int end);
136 // A JSON number (production JSONNumber) is a subset of the valid JavaScript
137 // decimal number literals.
138 // It includes an optional minus sign, must have at least one
139 // digit before and after a decimal point, may not have prefixed zeros (unless
140 // the integer part is zero), and may include an exponent part (e.g., "e-10").
141 // Hexadecimal and octal numbers are not allowed.
142 Handle<Object> ParseJsonNumber();
144 // Parse a single JSON value from input (grammar production JSONValue).
145 // A JSON value is either a (double-quoted) string literal, a number literal,
146 // one of "true", "false", or "null", or an object or array literal.
147 Handle<Object> ParseJsonValue();
149 // Parse a JSON object literal (grammar production JSONObject).
150 // An object literal is a squiggly-braced and comma separated sequence
151 // (possibly empty) of key/value pairs, where the key is a JSON string
152 // literal, the value is a JSON value, and the two are separated by a colon.
153 // A JSON array doesn't allow numbers and identifiers as keys, like a
155 Handle<Object> ParseJsonObject();
157 // Parses a JSON array literal (grammar production JSONArray). An array
158 // literal is a square-bracketed and comma separated sequence (possibly empty)
160 // A JSON array doesn't allow leaving out values from the sequence, nor does
161 // it allow a terminal comma, like a JavaScript array does.
162 Handle<Object> ParseJsonArray();
165 // Mark that a parsing error has happened at the current token, and
166 // return a null handle. Primarily for readability.
167 inline Handle<Object> ReportUnexpectedCharacter() {
168 return Handle<Object>::null();
171 inline Isolate* isolate() { return isolate_; }
172 inline Factory* factory() { return factory_; }
173 inline Handle<JSFunction> object_constructor() { return object_constructor_; }
175 static const int kInitialSpecialStringLength = 1024;
176 static const int kPretenureTreshold = 100 * 1024;
180 Zone* zone() { return &zone_; }
182 void CommitStateToJsonObject(Handle<JSObject> json_object, Handle<Map> map,
183 ZoneList<Handle<Object> >* properties);
185 Handle<String> source_;
187 Handle<SeqOneByteString> seq_source_;
189 PretenureFlag pretenure_;
193 Handle<JSFunction> object_constructor_;
198 template <bool seq_one_byte>
199 MaybeHandle<Object> JsonParser<seq_one_byte>::ParseJson() {
200 // Advance to the first character (possibly EOS)
201 AdvanceSkipWhitespace();
202 Handle<Object> result = ParseJsonValue();
203 if (result.is_null() || c0_ != kEndOfString) {
204 // Some exception (for example stack overflow) is already pending.
205 if (isolate_->has_pending_exception()) return Handle<Object>::null();
207 // Parse failed. Current character is the unexpected token.
209 Factory* factory = this->factory();
210 Handle<JSArray> array;
214 message = "unexpected_eos";
215 array = factory->NewJSArray(0);
228 message = "unexpected_token_number";
229 array = factory->NewJSArray(0);
232 message = "unexpected_token_string";
233 array = factory->NewJSArray(0);
236 message = "unexpected_token";
237 Handle<Object> name = factory->LookupSingleCharacterStringFromCode(c0_);
238 Handle<FixedArray> element = factory->NewFixedArray(1);
239 element->set(0, *name);
240 array = factory->NewJSArrayWithElements(element);
244 MessageLocation location(factory->NewScript(source_),
247 Handle<Object> error;
248 ASSIGN_RETURN_ON_EXCEPTION(isolate(), error,
249 factory->NewSyntaxError(message, array), Object);
250 return isolate()->template Throw<Object>(error, &location);
256 // Parse any JSON value.
257 template <bool seq_one_byte>
258 Handle<Object> JsonParser<seq_one_byte>::ParseJsonValue() {
259 StackLimitCheck stack_check(isolate_);
260 if (stack_check.HasOverflowed()) {
261 isolate_->StackOverflow();
262 return Handle<Object>::null();
265 if (c0_ == '"') return ParseJsonString();
266 if ((c0_ >= '0' && c0_ <= '9') || c0_ == '-') return ParseJsonNumber();
267 if (c0_ == '{') return ParseJsonObject();
268 if (c0_ == '[') return ParseJsonArray();
270 if (AdvanceGetChar() == 'a' && AdvanceGetChar() == 'l' &&
271 AdvanceGetChar() == 's' && AdvanceGetChar() == 'e') {
272 AdvanceSkipWhitespace();
273 return factory()->false_value();
275 return ReportUnexpectedCharacter();
278 if (AdvanceGetChar() == 'r' && AdvanceGetChar() == 'u' &&
279 AdvanceGetChar() == 'e') {
280 AdvanceSkipWhitespace();
281 return factory()->true_value();
283 return ReportUnexpectedCharacter();
286 if (AdvanceGetChar() == 'u' && AdvanceGetChar() == 'l' &&
287 AdvanceGetChar() == 'l') {
288 AdvanceSkipWhitespace();
289 return factory()->null_value();
291 return ReportUnexpectedCharacter();
293 return ReportUnexpectedCharacter();
297 // Parse a JSON object. Position must be right at '{'.
298 template <bool seq_one_byte>
299 Handle<Object> JsonParser<seq_one_byte>::ParseJsonObject() {
300 HandleScope scope(isolate());
301 Handle<JSObject> json_object =
302 factory()->NewJSObject(object_constructor(), pretenure_);
303 Handle<Map> map(json_object->map());
304 ZoneList<Handle<Object> > properties(8, zone());
307 bool transitioning = true;
309 AdvanceSkipWhitespace();
312 if (c0_ != '"') return ReportUnexpectedCharacter();
314 int start_position = position_;
318 if (c0_ >= '0' && c0_ <= '9') {
319 // Maybe an array index, try to parse it.
321 // With a leading zero, the string has to be "0" only to be an index.
326 if (index > 429496729U - ((d > 5) ? 1 : 0)) break;
327 index = (index * 10) + d;
329 } while (c0_ >= '0' && c0_ <= '9');
333 // Successfully parsed index, parse and store element.
334 AdvanceSkipWhitespace();
336 if (c0_ != ':') return ReportUnexpectedCharacter();
337 AdvanceSkipWhitespace();
338 Handle<Object> value = ParseJsonValue();
339 if (value.is_null()) return ReportUnexpectedCharacter();
341 JSObject::SetOwnElement(json_object, index, value, SLOPPY).Assert();
344 // Not an index, fallback to the slow path.
347 position_ = start_position;
353 Handle<Object> value;
355 // Try to follow existing transitions as long as possible. Once we stop
356 // transitioning, no transition can be found anymore.
358 // First check whether there is a single expected transition. If so, try
359 // to parse it first.
360 bool follow_expected = false;
363 key = Map::ExpectedTransitionKey(map);
364 follow_expected = !key.is_null() && ParseJsonString(key);
366 // If the expected transition hits, follow it.
367 if (follow_expected) {
368 target = Map::ExpectedTransitionTarget(map);
370 // If the expected transition failed, parse an internalized string and
371 // try to find a matching transition.
372 key = ParseJsonInternalizedString();
373 if (key.is_null()) return ReportUnexpectedCharacter();
375 target = Map::FindTransitionToField(map, key);
376 // If a transition was found, follow it and continue.
377 transitioning = !target.is_null();
379 if (c0_ != ':') return ReportUnexpectedCharacter();
381 AdvanceSkipWhitespace();
382 value = ParseJsonValue();
383 if (value.is_null()) return ReportUnexpectedCharacter();
386 int descriptor = map->NumberOfOwnDescriptors();
387 PropertyDetails details =
388 target->instance_descriptors()->GetDetails(descriptor);
389 Representation expected_representation = details.representation();
391 if (value->FitsRepresentation(expected_representation)) {
392 if (expected_representation.IsDouble()) {
393 value = Object::NewStorageFor(isolate(), value,
394 expected_representation);
395 } else if (expected_representation.IsHeapObject() &&
396 !target->instance_descriptors()->GetFieldType(
397 descriptor)->NowContains(value)) {
398 Handle<HeapType> value_type(value->OptimalType(
399 isolate(), expected_representation));
400 Map::GeneralizeFieldType(target, descriptor,
401 expected_representation, value_type);
403 DCHECK(target->instance_descriptors()->GetFieldType(
404 descriptor)->NowContains(value));
405 properties.Add(value, zone());
409 transitioning = false;
413 // Commit the intermediate state to the object and stop transitioning.
414 CommitStateToJsonObject(json_object, map, &properties);
416 key = ParseJsonInternalizedString();
417 if (key.is_null() || c0_ != ':') return ReportUnexpectedCharacter();
419 AdvanceSkipWhitespace();
420 value = ParseJsonValue();
421 if (value.is_null()) return ReportUnexpectedCharacter();
424 Runtime::DefineObjectProperty(json_object, key, value, NONE).Check();
425 } while (MatchSkipWhiteSpace(','));
427 return ReportUnexpectedCharacter();
430 // If we transitioned until the very end, transition the map now.
432 CommitStateToJsonObject(json_object, map, &properties);
435 AdvanceSkipWhitespace();
436 return scope.CloseAndEscape(json_object);
440 template <bool seq_one_byte>
441 void JsonParser<seq_one_byte>::CommitStateToJsonObject(
442 Handle<JSObject> json_object, Handle<Map> map,
443 ZoneList<Handle<Object> >* properties) {
444 JSObject::AllocateStorageForMap(json_object, map);
445 DCHECK(!json_object->map()->is_dictionary_map());
447 DisallowHeapAllocation no_gc;
448 Factory* factory = isolate()->factory();
449 // If the |json_object|'s map is exactly the same as |map| then the
450 // |properties| values correspond to the |map| and nothing more has to be
451 // done. But if the |json_object|'s map is different then we have to
452 // iterate descriptors to ensure that properties still correspond to the
454 bool slow_case = json_object->map() != *map;
455 DescriptorArray* descriptors = NULL;
457 int length = properties->length();
459 descriptors = json_object->map()->instance_descriptors();
460 DCHECK(json_object->map()->NumberOfOwnDescriptors() == length);
462 for (int i = 0; i < length; i++) {
463 Handle<Object> value = (*properties)[i];
464 if (slow_case && value->IsMutableHeapNumber() &&
465 !descriptors->GetDetails(i).representation().IsDouble()) {
466 // Turn mutable heap numbers into immutable if the field representation
468 HeapNumber::cast(*value)->set_map(*factory->heap_number_map());
470 FieldIndex index = FieldIndex::ForPropertyIndex(*map, i);
471 json_object->FastPropertyAtPut(index, *value);
476 // Parse a JSON array. Position must be right at '['.
477 template <bool seq_one_byte>
478 Handle<Object> JsonParser<seq_one_byte>::ParseJsonArray() {
479 HandleScope scope(isolate());
480 ZoneList<Handle<Object> > elements(4, zone());
483 AdvanceSkipWhitespace();
486 Handle<Object> element = ParseJsonValue();
487 if (element.is_null()) return ReportUnexpectedCharacter();
488 elements.Add(element, zone());
489 } while (MatchSkipWhiteSpace(','));
491 return ReportUnexpectedCharacter();
494 AdvanceSkipWhitespace();
495 // Allocate a fixed array with all the elements.
496 Handle<FixedArray> fast_elements =
497 factory()->NewFixedArray(elements.length(), pretenure_);
498 for (int i = 0, n = elements.length(); i < n; i++) {
499 fast_elements->set(i, *elements[i]);
501 Handle<Object> json_array = factory()->NewJSArrayWithElements(
502 fast_elements, FAST_ELEMENTS, pretenure_);
503 return scope.CloseAndEscape(json_array);
507 template <bool seq_one_byte>
508 Handle<Object> JsonParser<seq_one_byte>::ParseJsonNumber() {
509 bool negative = false;
510 int beg_pos = position_;
517 // Prefix zero is only allowed if it's the only digit before
518 // a decimal point or exponent.
519 if ('0' <= c0_ && c0_ <= '9') return ReportUnexpectedCharacter();
523 if (c0_ < '1' || c0_ > '9') return ReportUnexpectedCharacter();
525 i = i * 10 + c0_ - '0';
528 } while (c0_ >= '0' && c0_ <= '9');
529 if (c0_ != '.' && c0_ != 'e' && c0_ != 'E' && digits < 10) {
531 return Handle<Smi>(Smi::FromInt((negative ? -i : i)), isolate());
536 if (c0_ < '0' || c0_ > '9') return ReportUnexpectedCharacter();
539 } while (c0_ >= '0' && c0_ <= '9');
541 if (AsciiAlphaToLower(c0_) == 'e') {
543 if (c0_ == '-' || c0_ == '+') Advance();
544 if (c0_ < '0' || c0_ > '9') return ReportUnexpectedCharacter();
547 } while (c0_ >= '0' && c0_ <= '9');
549 int length = position_ - beg_pos;
552 Vector<const uint8_t> chars(seq_source_->GetChars() + beg_pos, length);
553 number = StringToDouble(isolate()->unicode_cache(), chars,
554 NO_FLAGS, // Hex, octal or trailing junk.
555 std::numeric_limits<double>::quiet_NaN());
557 Vector<uint8_t> buffer = Vector<uint8_t>::New(length);
558 String::WriteToFlat(*source_, buffer.start(), beg_pos, position_);
559 Vector<const uint8_t> result =
560 Vector<const uint8_t>(buffer.start(), length);
561 number = StringToDouble(isolate()->unicode_cache(),
563 NO_FLAGS, // Hex, octal or trailing junk.
568 return factory()->NewNumber(number, pretenure_);
572 template <typename StringType>
573 inline void SeqStringSet(Handle<StringType> seq_str, int i, uc32 c);
576 inline void SeqStringSet(Handle<SeqTwoByteString> seq_str, int i, uc32 c) {
577 seq_str->SeqTwoByteStringSet(i, c);
581 inline void SeqStringSet(Handle<SeqOneByteString> seq_str, int i, uc32 c) {
582 seq_str->SeqOneByteStringSet(i, c);
585 template <typename StringType>
586 inline Handle<StringType> NewRawString(Factory* factory,
588 PretenureFlag pretenure);
591 inline Handle<SeqTwoByteString> NewRawString(Factory* factory,
593 PretenureFlag pretenure) {
594 return factory->NewRawTwoByteString(length, pretenure).ToHandleChecked();
598 inline Handle<SeqOneByteString> NewRawString(Factory* factory,
600 PretenureFlag pretenure) {
601 return factory->NewRawOneByteString(length, pretenure).ToHandleChecked();
605 // Scans the rest of a JSON string starting from position_ and writes
606 // prefix[start..end] along with the scanned characters into a
607 // sequential string of type StringType.
608 template <bool seq_one_byte>
609 template <typename StringType, typename SinkChar>
610 Handle<String> JsonParser<seq_one_byte>::SlowScanJsonString(
611 Handle<String> prefix, int start, int end) {
612 int count = end - start;
613 int max_length = count + source_length_ - position_;
614 int length = Min(max_length, Max(kInitialSpecialStringLength, 2 * count));
615 Handle<StringType> seq_string =
616 NewRawString<StringType>(factory(), length, pretenure_);
617 // Copy prefix into seq_str.
618 SinkChar* dest = seq_string->GetChars();
619 String::WriteToFlat(*prefix, dest, start, end);
622 // Check for control character (0x00-0x1f) or unterminated string (<0).
623 if (c0_ < 0x20) return Handle<String>::null();
624 if (count >= length) {
625 // We need to create a longer sequential string for the result.
626 return SlowScanJsonString<StringType, SinkChar>(seq_string, 0, count);
629 // If the sink can contain UC16 characters, or source_ contains only
630 // Latin1 characters, there's no need to test whether we can store the
631 // character. Otherwise check whether the UC16 source character can fit
632 // in the Latin1 sink.
633 if (sizeof(SinkChar) == kUC16Size || seq_one_byte ||
634 c0_ <= String::kMaxOneByteCharCode) {
635 SeqStringSet(seq_string, count++, c0_);
638 // StringType is SeqOneByteString and we just read a non-Latin1 char.
639 return SlowScanJsonString<SeqTwoByteString, uc16>(seq_string, 0, count);
642 Advance(); // Advance past the \.
647 SeqStringSet(seq_string, count++, c0_);
650 SeqStringSet(seq_string, count++, '\x08');
653 SeqStringSet(seq_string, count++, '\x0c');
656 SeqStringSet(seq_string, count++, '\x0a');
659 SeqStringSet(seq_string, count++, '\x0d');
662 SeqStringSet(seq_string, count++, '\x09');
666 for (int i = 0; i < 4; i++) {
668 int digit = HexValue(c0_);
670 return Handle<String>::null();
672 value = value * 16 + digit;
674 if (sizeof(SinkChar) == kUC16Size ||
675 value <= String::kMaxOneByteCharCode) {
676 SeqStringSet(seq_string, count++, value);
679 // StringType is SeqOneByteString and we just read a non-Latin1
681 position_ -= 6; // Rewind position_ to \ in \uxxxx.
683 return SlowScanJsonString<SeqTwoByteString, uc16>(seq_string,
689 return Handle<String>::null();
696 // Advance past the last '"'.
697 AdvanceSkipWhitespace();
699 // Shrink seq_string length to count and return.
700 return SeqString::Truncate(seq_string, count);
704 template <bool seq_one_byte>
705 template <bool is_internalized>
706 Handle<String> JsonParser<seq_one_byte>::ScanJsonString() {
710 AdvanceSkipWhitespace();
711 return factory()->empty_string();
714 if (seq_one_byte && is_internalized) {
715 // Fast path for existing internalized strings. If the the string being
716 // parsed is not a known internalized string, contains backslashes or
717 // unexpectedly reaches the end of string, return with an empty handle.
718 uint32_t running_hash = isolate()->heap()->HashSeed();
719 int position = position_;
724 int beg_pos = position_;
725 position_ = position;
726 return SlowScanJsonString<SeqOneByteString, uint8_t>(source_,
730 if (c0 < 0x20) return Handle<String>::null();
731 if (static_cast<uint32_t>(c0) >
732 unibrow::Utf16::kMaxNonSurrogateCharCode) {
734 StringHasher::AddCharacterCore(running_hash,
735 unibrow::Utf16::LeadSurrogate(c0));
737 StringHasher::AddCharacterCore(running_hash,
738 unibrow::Utf16::TrailSurrogate(c0));
740 running_hash = StringHasher::AddCharacterCore(running_hash, c0);
743 if (position >= source_length_) return Handle<String>::null();
744 c0 = seq_source_->SeqOneByteStringGet(position);
746 int length = position - position_;
747 uint32_t hash = (length <= String::kMaxHashCalcLength)
748 ? StringHasher::GetHashCore(running_hash)
749 : static_cast<uint32_t>(length);
750 Vector<const uint8_t> string_vector(
751 seq_source_->GetChars() + position_, length);
752 StringTable* string_table = isolate()->heap()->string_table();
753 uint32_t capacity = string_table->Capacity();
754 uint32_t entry = StringTable::FirstProbe(hash, capacity);
756 Handle<String> result;
758 Object* element = string_table->KeyAt(entry);
759 if (element == isolate()->heap()->undefined_value()) {
761 result = factory()->InternalizeOneByteString(
762 seq_source_, position_, length);
765 if (element != isolate()->heap()->the_hole_value() &&
766 String::cast(element)->IsOneByteEqualTo(string_vector)) {
767 result = Handle<String>(String::cast(element), isolate());
769 uint32_t hash_field =
770 (hash << String::kHashShift) | String::kIsNotArrayIndexMask;
771 DCHECK_EQ(static_cast<int>(result->Hash()),
772 static_cast<int>(hash_field >> String::kHashShift));
776 entry = StringTable::NextProbe(entry, count++, capacity);
778 position_ = position;
779 // Advance past the last '"'.
780 AdvanceSkipWhitespace();
784 int beg_pos = position_;
785 // Fast case for Latin1 only without escape characters.
787 // Check for control character (0x00-0x1f) or unterminated string (<0).
788 if (c0_ < 0x20) return Handle<String>::null();
790 if (seq_one_byte || c0_ <= String::kMaxOneByteCharCode) {
793 return SlowScanJsonString<SeqTwoByteString, uc16>(source_,
798 return SlowScanJsonString<SeqOneByteString, uint8_t>(source_,
802 } while (c0_ != '"');
803 int length = position_ - beg_pos;
804 Handle<String> result =
805 factory()->NewRawOneByteString(length, pretenure_).ToHandleChecked();
806 uint8_t* dest = SeqOneByteString::cast(*result)->GetChars();
807 String::WriteToFlat(*source_, dest, beg_pos, position_);
810 // Advance past the last '"'.
811 AdvanceSkipWhitespace();
815 } } // namespace v8::internal
817 #endif // V8_JSON_PARSER_H_