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_ascii>
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()),
36 object_constructor_(isolate_->native_context()->object_function(),
39 source_ = String::Flatten(source_);
40 pretenure_ = (source_length_ >= kPretenureTreshold) ? TENURED : NOT_TENURED;
42 // Optimized fast case where we only have ASCII characters.
44 seq_source_ = Handle<SeqOneByteString>::cast(source_);
48 // Parse a string containing a single JSON value.
49 MaybeHandle<Object> ParseJson();
51 inline void Advance() {
53 if (position_ >= source_length_) {
55 } else if (seq_ascii) {
56 c0_ = seq_source_->SeqOneByteStringGet(position_);
58 c0_ = source_->Get(position_);
62 // The JSON lexical grammar is specified in the ECMAScript 5 standard,
63 // section 15.12.1.1. The only allowed whitespace characters between tokens
64 // are tab, carriage-return, newline and space.
66 inline void AdvanceSkipWhitespace() {
69 } while (c0_ == ' ' || c0_ == '\t' || c0_ == '\n' || c0_ == '\r');
72 inline void SkipWhitespace() {
73 while (c0_ == ' ' || c0_ == '\t' || c0_ == '\n' || c0_ == '\r') {
78 inline uc32 AdvanceGetChar() {
83 // Checks that current charater is c.
84 // If so, then consume c and skip whitespace.
85 inline bool MatchSkipWhiteSpace(uc32 c) {
87 AdvanceSkipWhitespace();
93 // A JSON string (production JSONString) is subset of valid JavaScript string
94 // literals. The string must only be double-quoted (not single-quoted), and
95 // the only allowed backslash-escapes are ", /, \, b, f, n, r, t and
96 // four-digit hex escapes (uXXXX). Any other use of backslashes is invalid.
97 Handle<String> ParseJsonString() {
98 return ScanJsonString<false>();
101 bool ParseJsonString(Handle<String> expected) {
102 int length = expected->length();
103 if (source_->length() - position_ - 1 > length) {
104 DisallowHeapAllocation no_gc;
105 String::FlatContent content = expected->GetFlatContent();
106 if (content.IsAscii()) {
108 const uint8_t* input_chars = seq_source_->GetChars() + position_ + 1;
109 const uint8_t* expected_chars = content.ToOneByteVector().start();
110 for (int i = 0; i < length; i++) {
111 uint8_t c0 = input_chars[i];
112 if (c0 != expected_chars[i] ||
113 c0 == '"' || c0 < 0x20 || c0 == '\\') {
117 if (input_chars[length] == '"') {
118 position_ = position_ + length + 1;
119 AdvanceSkipWhitespace();
127 Handle<String> ParseJsonInternalizedString() {
128 return ScanJsonString<true>();
131 template <bool is_internalized>
132 Handle<String> ScanJsonString();
133 // Creates a new string and copies prefix[start..end] into the beginning
134 // of it. Then scans the rest of the string, adding characters after the
135 // prefix. Called by ScanJsonString when reaching a '\' or non-ASCII char.
136 template <typename StringType, typename SinkChar>
137 Handle<String> SlowScanJsonString(Handle<String> prefix, int start, int end);
139 // A JSON number (production JSONNumber) is a subset of the valid JavaScript
140 // decimal number literals.
141 // It includes an optional minus sign, must have at least one
142 // digit before and after a decimal point, may not have prefixed zeros (unless
143 // the integer part is zero), and may include an exponent part (e.g., "e-10").
144 // Hexadecimal and octal numbers are not allowed.
145 Handle<Object> ParseJsonNumber();
147 // Parse a single JSON value from input (grammar production JSONValue).
148 // A JSON value is either a (double-quoted) string literal, a number literal,
149 // one of "true", "false", or "null", or an object or array literal.
150 Handle<Object> ParseJsonValue();
152 // Parse a JSON object literal (grammar production JSONObject).
153 // An object literal is a squiggly-braced and comma separated sequence
154 // (possibly empty) of key/value pairs, where the key is a JSON string
155 // literal, the value is a JSON value, and the two are separated by a colon.
156 // A JSON array doesn't allow numbers and identifiers as keys, like a
158 Handle<Object> ParseJsonObject();
160 // Parses a JSON array literal (grammar production JSONArray). An array
161 // literal is a square-bracketed and comma separated sequence (possibly empty)
163 // A JSON array doesn't allow leaving out values from the sequence, nor does
164 // it allow a terminal comma, like a JavaScript array does.
165 Handle<Object> ParseJsonArray();
168 // Mark that a parsing error has happened at the current token, and
169 // return a null handle. Primarily for readability.
170 inline Handle<Object> ReportUnexpectedCharacter() {
171 return Handle<Object>::null();
174 inline Isolate* isolate() { return isolate_; }
175 inline Factory* factory() { return factory_; }
176 inline Handle<JSFunction> object_constructor() { return object_constructor_; }
178 static const int kInitialSpecialStringLength = 1024;
179 static const int kPretenureTreshold = 100 * 1024;
183 Zone* zone() { return &zone_; }
185 Handle<String> source_;
187 Handle<SeqOneByteString> seq_source_;
189 PretenureFlag pretenure_;
193 Handle<JSFunction> object_constructor_;
198 template <bool seq_ascii>
199 MaybeHandle<Object> JsonParser<seq_ascii>::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 = factory->NewSyntaxError(message, array);
248 return isolate()->template Throw<Object>(error, &location);
254 // Parse any JSON value.
255 template <bool seq_ascii>
256 Handle<Object> JsonParser<seq_ascii>::ParseJsonValue() {
257 StackLimitCheck stack_check(isolate_);
258 if (stack_check.HasOverflowed()) {
259 isolate_->StackOverflow();
260 return Handle<Object>::null();
263 if (c0_ == '"') return ParseJsonString();
264 if ((c0_ >= '0' && c0_ <= '9') || c0_ == '-') return ParseJsonNumber();
265 if (c0_ == '{') return ParseJsonObject();
266 if (c0_ == '[') return ParseJsonArray();
268 if (AdvanceGetChar() == 'a' && AdvanceGetChar() == 'l' &&
269 AdvanceGetChar() == 's' && AdvanceGetChar() == 'e') {
270 AdvanceSkipWhitespace();
271 return factory()->false_value();
273 return ReportUnexpectedCharacter();
276 if (AdvanceGetChar() == 'r' && AdvanceGetChar() == 'u' &&
277 AdvanceGetChar() == 'e') {
278 AdvanceSkipWhitespace();
279 return factory()->true_value();
281 return ReportUnexpectedCharacter();
284 if (AdvanceGetChar() == 'u' && AdvanceGetChar() == 'l' &&
285 AdvanceGetChar() == 'l') {
286 AdvanceSkipWhitespace();
287 return factory()->null_value();
289 return ReportUnexpectedCharacter();
291 return ReportUnexpectedCharacter();
295 // Parse a JSON object. Position must be right at '{'.
296 template <bool seq_ascii>
297 Handle<Object> JsonParser<seq_ascii>::ParseJsonObject() {
298 HandleScope scope(isolate());
299 Handle<JSObject> json_object =
300 factory()->NewJSObject(object_constructor(), pretenure_);
301 Handle<Map> map(json_object->map());
302 ZoneList<Handle<Object> > properties(8, zone());
305 bool transitioning = true;
307 AdvanceSkipWhitespace();
310 if (c0_ != '"') return ReportUnexpectedCharacter();
312 int start_position = position_;
316 if (c0_ >= '0' && c0_ <= '9') {
317 // Maybe an array index, try to parse it.
319 // With a leading zero, the string has to be "0" only to be an index.
324 if (index > 429496729U - ((d > 5) ? 1 : 0)) break;
325 index = (index * 10) + d;
327 } while (c0_ >= '0' && c0_ <= '9');
331 // Successfully parsed index, parse and store element.
332 AdvanceSkipWhitespace();
334 if (c0_ != ':') return ReportUnexpectedCharacter();
335 AdvanceSkipWhitespace();
336 Handle<Object> value = ParseJsonValue();
337 if (value.is_null()) return ReportUnexpectedCharacter();
339 JSObject::SetOwnElement(json_object, index, value, SLOPPY).Assert();
342 // Not an index, fallback to the slow path.
345 position_ = start_position;
351 Handle<Object> value;
353 // Try to follow existing transitions as long as possible. Once we stop
354 // transitioning, no transition can be found anymore.
356 // First check whether there is a single expected transition. If so, try
357 // to parse it first.
358 bool follow_expected = false;
361 key = Map::ExpectedTransitionKey(map);
362 follow_expected = !key.is_null() && ParseJsonString(key);
364 // If the expected transition hits, follow it.
365 if (follow_expected) {
366 target = Map::ExpectedTransitionTarget(map);
368 // If the expected transition failed, parse an internalized string and
369 // try to find a matching transition.
370 key = ParseJsonInternalizedString();
371 if (key.is_null()) return ReportUnexpectedCharacter();
373 target = Map::FindTransitionToField(map, key);
374 // If a transition was found, follow it and continue.
375 transitioning = !target.is_null();
377 if (c0_ != ':') return ReportUnexpectedCharacter();
379 AdvanceSkipWhitespace();
380 value = ParseJsonValue();
381 if (value.is_null()) return ReportUnexpectedCharacter();
384 int descriptor = map->NumberOfOwnDescriptors();
385 PropertyDetails details =
386 target->instance_descriptors()->GetDetails(descriptor);
387 Representation expected_representation = details.representation();
389 if (value->FitsRepresentation(expected_representation)) {
390 if (expected_representation.IsDouble()) {
391 value = Object::NewStorageFor(isolate(), value,
392 expected_representation);
393 } else if (expected_representation.IsHeapObject() &&
394 !target->instance_descriptors()->GetFieldType(
395 descriptor)->NowContains(value)) {
396 Handle<HeapType> value_type(value->OptimalType(
397 isolate(), expected_representation));
398 Map::GeneralizeFieldType(target, descriptor, value_type);
400 DCHECK(target->instance_descriptors()->GetFieldType(
401 descriptor)->NowContains(value));
402 properties.Add(value, zone());
406 transitioning = false;
410 // Commit the intermediate state to the object and stop transitioning.
411 JSObject::AllocateStorageForMap(json_object, map);
412 int length = properties.length();
413 for (int i = 0; i < length; i++) {
414 Handle<Object> value = properties[i];
415 FieldIndex index = FieldIndex::ForPropertyIndex(*map, i);
416 json_object->FastPropertyAtPut(index, *value);
419 key = ParseJsonInternalizedString();
420 if (key.is_null() || c0_ != ':') return ReportUnexpectedCharacter();
422 AdvanceSkipWhitespace();
423 value = ParseJsonValue();
424 if (value.is_null()) return ReportUnexpectedCharacter();
427 JSObject::SetOwnPropertyIgnoreAttributes(
428 json_object, key, value, NONE).Assert();
429 } while (MatchSkipWhiteSpace(','));
431 return ReportUnexpectedCharacter();
434 // If we transitioned until the very end, transition the map now.
436 JSObject::AllocateStorageForMap(json_object, map);
437 int length = properties.length();
438 for (int i = 0; i < length; i++) {
439 Handle<Object> value = properties[i];
440 FieldIndex index = FieldIndex::ForPropertyIndex(*map, i);
441 json_object->FastPropertyAtPut(index, *value);
445 AdvanceSkipWhitespace();
446 return scope.CloseAndEscape(json_object);
449 // Parse a JSON array. Position must be right at '['.
450 template <bool seq_ascii>
451 Handle<Object> JsonParser<seq_ascii>::ParseJsonArray() {
452 HandleScope scope(isolate());
453 ZoneList<Handle<Object> > elements(4, zone());
456 AdvanceSkipWhitespace();
459 Handle<Object> element = ParseJsonValue();
460 if (element.is_null()) return ReportUnexpectedCharacter();
461 elements.Add(element, zone());
462 } while (MatchSkipWhiteSpace(','));
464 return ReportUnexpectedCharacter();
467 AdvanceSkipWhitespace();
468 // Allocate a fixed array with all the elements.
469 Handle<FixedArray> fast_elements =
470 factory()->NewFixedArray(elements.length(), pretenure_);
471 for (int i = 0, n = elements.length(); i < n; i++) {
472 fast_elements->set(i, *elements[i]);
474 Handle<Object> json_array = factory()->NewJSArrayWithElements(
475 fast_elements, FAST_ELEMENTS, pretenure_);
476 return scope.CloseAndEscape(json_array);
480 template <bool seq_ascii>
481 Handle<Object> JsonParser<seq_ascii>::ParseJsonNumber() {
482 bool negative = false;
483 int beg_pos = position_;
490 // Prefix zero is only allowed if it's the only digit before
491 // a decimal point or exponent.
492 if ('0' <= c0_ && c0_ <= '9') return ReportUnexpectedCharacter();
496 if (c0_ < '1' || c0_ > '9') return ReportUnexpectedCharacter();
498 i = i * 10 + c0_ - '0';
501 } while (c0_ >= '0' && c0_ <= '9');
502 if (c0_ != '.' && c0_ != 'e' && c0_ != 'E' && digits < 10) {
504 return Handle<Smi>(Smi::FromInt((negative ? -i : i)), isolate());
509 if (c0_ < '0' || c0_ > '9') return ReportUnexpectedCharacter();
512 } while (c0_ >= '0' && c0_ <= '9');
514 if (AsciiAlphaToLower(c0_) == 'e') {
516 if (c0_ == '-' || c0_ == '+') Advance();
517 if (c0_ < '0' || c0_ > '9') return ReportUnexpectedCharacter();
520 } while (c0_ >= '0' && c0_ <= '9');
522 int length = position_ - beg_pos;
525 Vector<const uint8_t> chars(seq_source_->GetChars() + beg_pos, length);
526 number = StringToDouble(isolate()->unicode_cache(),
528 NO_FLAGS, // Hex, octal or trailing junk.
529 base::OS::nan_value());
531 Vector<uint8_t> buffer = Vector<uint8_t>::New(length);
532 String::WriteToFlat(*source_, buffer.start(), beg_pos, position_);
533 Vector<const uint8_t> result =
534 Vector<const uint8_t>(buffer.start(), length);
535 number = StringToDouble(isolate()->unicode_cache(),
537 NO_FLAGS, // Hex, octal or trailing junk.
542 return factory()->NewNumber(number, pretenure_);
546 template <typename StringType>
547 inline void SeqStringSet(Handle<StringType> seq_str, int i, uc32 c);
550 inline void SeqStringSet(Handle<SeqTwoByteString> seq_str, int i, uc32 c) {
551 seq_str->SeqTwoByteStringSet(i, c);
555 inline void SeqStringSet(Handle<SeqOneByteString> seq_str, int i, uc32 c) {
556 seq_str->SeqOneByteStringSet(i, c);
559 template <typename StringType>
560 inline Handle<StringType> NewRawString(Factory* factory,
562 PretenureFlag pretenure);
565 inline Handle<SeqTwoByteString> NewRawString(Factory* factory,
567 PretenureFlag pretenure) {
568 return factory->NewRawTwoByteString(length, pretenure).ToHandleChecked();
572 inline Handle<SeqOneByteString> NewRawString(Factory* factory,
574 PretenureFlag pretenure) {
575 return factory->NewRawOneByteString(length, pretenure).ToHandleChecked();
579 // Scans the rest of a JSON string starting from position_ and writes
580 // prefix[start..end] along with the scanned characters into a
581 // sequential string of type StringType.
582 template <bool seq_ascii>
583 template <typename StringType, typename SinkChar>
584 Handle<String> JsonParser<seq_ascii>::SlowScanJsonString(
585 Handle<String> prefix, int start, int end) {
586 int count = end - start;
587 int max_length = count + source_length_ - position_;
588 int length = Min(max_length, Max(kInitialSpecialStringLength, 2 * count));
589 Handle<StringType> seq_string =
590 NewRawString<StringType>(factory(), length, pretenure_);
591 // Copy prefix into seq_str.
592 SinkChar* dest = seq_string->GetChars();
593 String::WriteToFlat(*prefix, dest, start, end);
596 // Check for control character (0x00-0x1f) or unterminated string (<0).
597 if (c0_ < 0x20) return Handle<String>::null();
598 if (count >= length) {
599 // We need to create a longer sequential string for the result.
600 return SlowScanJsonString<StringType, SinkChar>(seq_string, 0, count);
603 // If the sink can contain UC16 characters, or source_ contains only
604 // ASCII characters, there's no need to test whether we can store the
605 // character. Otherwise check whether the UC16 source character can fit
606 // in the ASCII sink.
607 if (sizeof(SinkChar) == kUC16Size ||
609 c0_ <= String::kMaxOneByteCharCode) {
610 SeqStringSet(seq_string, count++, c0_);
613 // StringType is SeqOneByteString and we just read a non-ASCII char.
614 return SlowScanJsonString<SeqTwoByteString, uc16>(seq_string, 0, count);
617 Advance(); // Advance past the \.
622 SeqStringSet(seq_string, count++, c0_);
625 SeqStringSet(seq_string, count++, '\x08');
628 SeqStringSet(seq_string, count++, '\x0c');
631 SeqStringSet(seq_string, count++, '\x0a');
634 SeqStringSet(seq_string, count++, '\x0d');
637 SeqStringSet(seq_string, count++, '\x09');
641 for (int i = 0; i < 4; i++) {
643 int digit = HexValue(c0_);
645 return Handle<String>::null();
647 value = value * 16 + digit;
649 if (sizeof(SinkChar) == kUC16Size ||
650 value <= String::kMaxOneByteCharCode) {
651 SeqStringSet(seq_string, count++, value);
654 // StringType is SeqOneByteString and we just read a non-ASCII char.
655 position_ -= 6; // Rewind position_ to \ in \uxxxx.
657 return SlowScanJsonString<SeqTwoByteString, uc16>(seq_string,
663 return Handle<String>::null();
670 // Advance past the last '"'.
671 AdvanceSkipWhitespace();
673 // Shrink seq_string length to count and return.
674 return SeqString::Truncate(seq_string, count);
678 template <bool seq_ascii>
679 template <bool is_internalized>
680 Handle<String> JsonParser<seq_ascii>::ScanJsonString() {
684 AdvanceSkipWhitespace();
685 return factory()->empty_string();
688 if (seq_ascii && is_internalized) {
689 // Fast path for existing internalized strings. If the the string being
690 // parsed is not a known internalized string, contains backslashes or
691 // unexpectedly reaches the end of string, return with an empty handle.
692 uint32_t running_hash = isolate()->heap()->HashSeed();
693 int position = position_;
698 int beg_pos = position_;
699 position_ = position;
700 return SlowScanJsonString<SeqOneByteString, uint8_t>(source_,
704 if (c0 < 0x20) return Handle<String>::null();
705 if (static_cast<uint32_t>(c0) >
706 unibrow::Utf16::kMaxNonSurrogateCharCode) {
708 StringHasher::AddCharacterCore(running_hash,
709 unibrow::Utf16::LeadSurrogate(c0));
711 StringHasher::AddCharacterCore(running_hash,
712 unibrow::Utf16::TrailSurrogate(c0));
714 running_hash = StringHasher::AddCharacterCore(running_hash, c0);
717 if (position >= source_length_) return Handle<String>::null();
718 c0 = seq_source_->SeqOneByteStringGet(position);
720 int length = position - position_;
721 uint32_t hash = (length <= String::kMaxHashCalcLength)
722 ? StringHasher::GetHashCore(running_hash)
723 : static_cast<uint32_t>(length);
724 Vector<const uint8_t> string_vector(
725 seq_source_->GetChars() + position_, length);
726 StringTable* string_table = isolate()->heap()->string_table();
727 uint32_t capacity = string_table->Capacity();
728 uint32_t entry = StringTable::FirstProbe(hash, capacity);
730 Handle<String> result;
732 Object* element = string_table->KeyAt(entry);
733 if (element == isolate()->heap()->undefined_value()) {
735 result = factory()->InternalizeOneByteString(
736 seq_source_, position_, length);
739 if (element != isolate()->heap()->the_hole_value() &&
740 String::cast(element)->IsOneByteEqualTo(string_vector)) {
741 result = Handle<String>(String::cast(element), isolate());
743 uint32_t hash_field =
744 (hash << String::kHashShift) | String::kIsNotArrayIndexMask;
745 DCHECK_EQ(static_cast<int>(result->Hash()),
746 static_cast<int>(hash_field >> String::kHashShift));
750 entry = StringTable::NextProbe(entry, count++, capacity);
752 position_ = position;
753 // Advance past the last '"'.
754 AdvanceSkipWhitespace();
758 int beg_pos = position_;
759 // Fast case for ASCII only without escape characters.
761 // Check for control character (0x00-0x1f) or unterminated string (<0).
762 if (c0_ < 0x20) return Handle<String>::null();
764 if (seq_ascii || c0_ <= String::kMaxOneByteCharCode) {
767 return SlowScanJsonString<SeqTwoByteString, uc16>(source_,
772 return SlowScanJsonString<SeqOneByteString, uint8_t>(source_,
776 } while (c0_ != '"');
777 int length = position_ - beg_pos;
778 Handle<String> result =
779 factory()->NewRawOneByteString(length, pretenure_).ToHandleChecked();
780 uint8_t* dest = SeqOneByteString::cast(*result)->GetChars();
781 String::WriteToFlat(*source_, dest, beg_pos, position_);
784 // Advance past the last '"'.
785 AdvanceSkipWhitespace();
789 } } // namespace v8::internal
791 #endif // V8_JSON_PARSER_H_