deps: update v8 to 4.3.61.21
[platform/upstream/nodejs.git] / deps / v8 / src / json-parser.h
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.
4
5 #ifndef V8_JSON_PARSER_H_
6 #define V8_JSON_PARSER_H_
7
8 #include "src/v8.h"
9
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"
15
16 namespace v8 {
17 namespace internal {
18
19 // A simple json parser.
20 template <bool seq_one_byte>
21 class JsonParser BASE_EMBEDDED {
22  public:
23   MUST_USE_RESULT static MaybeHandle<Object> Parse(Handle<String> source) {
24     return JsonParser(source).ParseJson();
25   }
26
27   static const int kEndOfString = -1;
28
29  private:
30   explicit JsonParser(Handle<String> source)
31       : source_(source),
32         source_length_(source->length()),
33         isolate_(source->map()->GetHeap()->isolate()),
34         factory_(isolate_->factory()),
35         object_constructor_(isolate_->native_context()->object_function(),
36                             isolate_),
37         position_(-1) {
38     source_ = String::Flatten(source_);
39     pretenure_ = (source_length_ >= kPretenureTreshold) ? TENURED : NOT_TENURED;
40
41     // Optimized fast case where we only have Latin1 characters.
42     if (seq_one_byte) {
43       seq_source_ = Handle<SeqOneByteString>::cast(source_);
44     }
45   }
46
47   // Parse a string containing a single JSON value.
48   MaybeHandle<Object> ParseJson();
49
50   inline void Advance() {
51     position_++;
52     if (position_ >= source_length_) {
53       c0_ = kEndOfString;
54     } else if (seq_one_byte) {
55       c0_ = seq_source_->SeqOneByteStringGet(position_);
56     } else {
57       c0_ = source_->Get(position_);
58     }
59   }
60
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.
64
65   inline void AdvanceSkipWhitespace() {
66     do {
67       Advance();
68     } while (c0_ == ' ' || c0_ == '\t' || c0_ == '\n' || c0_ == '\r');
69   }
70
71   inline void SkipWhitespace() {
72     while (c0_ == ' ' || c0_ == '\t' || c0_ == '\n' || c0_ == '\r') {
73       Advance();
74     }
75   }
76
77   inline uc32 AdvanceGetChar() {
78     Advance();
79     return c0_;
80   }
81
82   // Checks that current charater is c.
83   // If so, then consume c and skip whitespace.
84   inline bool MatchSkipWhiteSpace(uc32 c) {
85     if (c0_ == c) {
86       AdvanceSkipWhitespace();
87       return true;
88     }
89     return false;
90   }
91
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>();
98   }
99
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()) {
106         DCHECK_EQ('"', c0_);
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 == '\\') {
112             return false;
113           }
114         }
115         if (input_chars[length] == '"') {
116           position_ = position_ + length + 1;
117           AdvanceSkipWhitespace();
118           return true;
119         }
120       }
121     }
122     return false;
123   }
124
125   Handle<String> ParseJsonInternalizedString() {
126     return ScanJsonString<true>();
127   }
128
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);
136
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();
144
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();
149
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
155   // JavaScript array.
156   Handle<Object> ParseJsonObject();
157
158   // Parses a JSON array literal (grammar production JSONArray). An array
159   // literal is a square-bracketed and comma separated sequence (possibly empty)
160   // of JSON values.
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();
164
165
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();
170   }
171
172   inline Isolate* isolate() { return isolate_; }
173   inline Factory* factory() { return factory_; }
174   inline Handle<JSFunction> object_constructor() { return object_constructor_; }
175
176   static const int kInitialSpecialStringLength = 32;
177   static const int kPretenureTreshold = 100 * 1024;
178
179
180  private:
181   Zone* zone() { return &zone_; }
182
183   void CommitStateToJsonObject(Handle<JSObject> json_object, Handle<Map> map,
184                                ZoneList<Handle<Object> >* properties);
185
186   Handle<String> source_;
187   int source_length_;
188   Handle<SeqOneByteString> seq_source_;
189
190   PretenureFlag pretenure_;
191   Isolate* isolate_;
192   Factory* factory_;
193   Zone zone_;
194   Handle<JSFunction> object_constructor_;
195   uc32 c0_;
196   int position_;
197 };
198
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();
207
208     // Parse failed. Current character is the unexpected token.
209     const char* message;
210     Factory* factory = this->factory();
211     Handle<JSArray> array;
212
213     switch (c0_) {
214       case kEndOfString:
215         message = "unexpected_eos";
216         array = factory->NewJSArray(0);
217         break;
218       case '-':
219       case '0':
220       case '1':
221       case '2':
222       case '3':
223       case '4':
224       case '5':
225       case '6':
226       case '7':
227       case '8':
228       case '9':
229         message = "unexpected_token_number";
230         array = factory->NewJSArray(0);
231         break;
232       case '"':
233         message = "unexpected_token_string";
234         array = factory->NewJSArray(0);
235         break;
236       default:
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);
242         break;
243     }
244
245     MessageLocation location(factory->NewScript(source_),
246                              position_,
247                              position_ + 1);
248     Handle<Object> error = factory->NewSyntaxError(message, array);
249     return isolate()->template Throw<Object>(error, &location);
250   }
251   return result;
252 }
253
254
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();
262   }
263
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();
268   }
269
270   if (c0_ == '"') return ParseJsonString();
271   if ((c0_ >= '0' && c0_ <= '9') || c0_ == '-') return ParseJsonNumber();
272   if (c0_ == '{') return ParseJsonObject();
273   if (c0_ == '[') return ParseJsonArray();
274   if (c0_ == 'f') {
275     if (AdvanceGetChar() == 'a' && AdvanceGetChar() == 'l' &&
276         AdvanceGetChar() == 's' && AdvanceGetChar() == 'e') {
277       AdvanceSkipWhitespace();
278       return factory()->false_value();
279     }
280     return ReportUnexpectedCharacter();
281   }
282   if (c0_ == 't') {
283     if (AdvanceGetChar() == 'r' && AdvanceGetChar() == 'u' &&
284         AdvanceGetChar() == 'e') {
285       AdvanceSkipWhitespace();
286       return factory()->true_value();
287     }
288     return ReportUnexpectedCharacter();
289   }
290   if (c0_ == 'n') {
291     if (AdvanceGetChar() == 'u' && AdvanceGetChar() == 'l' &&
292         AdvanceGetChar() == 'l') {
293       AdvanceSkipWhitespace();
294       return factory()->null_value();
295     }
296     return ReportUnexpectedCharacter();
297   }
298   return ReportUnexpectedCharacter();
299 }
300
301
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());
309   int descriptor = 0;
310   ZoneList<Handle<Object> > properties(8, zone());
311   DCHECK_EQ(c0_, '{');
312
313   bool transitioning = true;
314
315   AdvanceSkipWhitespace();
316   if (c0_ != '}') {
317     do {
318       if (c0_ != '"') return ReportUnexpectedCharacter();
319
320       int start_position = position_;
321       Advance();
322
323       uint32_t index = 0;
324       if (IsDecimalDigit(c0_)) {
325         // Maybe an array index, try to parse it.
326         if (c0_ == '0') {
327           // With a leading zero, the string has to be "0" only to be an index.
328           Advance();
329         } else {
330           do {
331             int d = c0_ - '0';
332             if (index > 429496729U - ((d > 5) ? 1 : 0)) break;
333             index = (index * 10) + d;
334             Advance();
335           } while (IsDecimalDigit(c0_));
336         }
337
338         if (c0_ == '"') {
339           // Successfully parsed index, parse and store element.
340           AdvanceSkipWhitespace();
341
342           if (c0_ != ':') return ReportUnexpectedCharacter();
343           AdvanceSkipWhitespace();
344           Handle<Object> value = ParseJsonValue();
345           if (value.is_null()) return ReportUnexpectedCharacter();
346
347           JSObject::SetOwnElement(json_object, index, value, SLOPPY).Assert();
348           continue;
349         }
350         // Not an index, fallback to the slow path.
351       }
352
353       position_ = start_position;
354 #ifdef DEBUG
355       c0_ = '"';
356 #endif
357
358       Handle<String> key;
359       Handle<Object> value;
360
361       // Try to follow existing transitions as long as possible. Once we stop
362       // transitioning, no transition can be found anymore.
363       if (transitioning) {
364         // First check whether there is a single expected transition. If so, try
365         // to parse it first.
366         bool follow_expected = false;
367         Handle<Map> target;
368         if (seq_one_byte) {
369           key = TransitionArray::ExpectedTransitionKey(map);
370           follow_expected = !key.is_null() && ParseJsonString(key);
371         }
372         // If the expected transition hits, follow it.
373         if (follow_expected) {
374           target = TransitionArray::ExpectedTransitionTarget(map);
375         } else {
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();
380
381           target = TransitionArray::FindTransitionToField(map, key);
382           // If a transition was found, follow it and continue.
383           transitioning = !target.is_null();
384         }
385         if (c0_ != ':') return ReportUnexpectedCharacter();
386
387         AdvanceSkipWhitespace();
388         value = ParseJsonValue();
389         if (value.is_null()) return ReportUnexpectedCharacter();
390
391         if (transitioning) {
392           PropertyDetails details =
393               target->instance_descriptors()->GetDetails(descriptor);
394           Representation expected_representation = details.representation();
395
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);
405             }
406             DCHECK(target->instance_descriptors()->GetFieldType(
407                     descriptor)->NowContains(value));
408             properties.Add(value, zone());
409             map = target;
410             descriptor++;
411             continue;
412           } else {
413             transitioning = false;
414           }
415         }
416
417         // Commit the intermediate state to the object and stop transitioning.
418         CommitStateToJsonObject(json_object, map, &properties);
419       } else {
420         key = ParseJsonInternalizedString();
421         if (key.is_null() || c0_ != ':') return ReportUnexpectedCharacter();
422
423         AdvanceSkipWhitespace();
424         value = ParseJsonValue();
425         if (value.is_null()) return ReportUnexpectedCharacter();
426       }
427
428       Runtime::DefineObjectProperty(json_object, key, value, NONE).Check();
429     } while (MatchSkipWhiteSpace(','));
430     if (c0_ != '}') {
431       return ReportUnexpectedCharacter();
432     }
433
434     // If we transitioned until the very end, transition the map now.
435     if (transitioning) {
436       CommitStateToJsonObject(json_object, map, &properties);
437     }
438   }
439   AdvanceSkipWhitespace();
440   return scope.CloseAndEscape(json_object);
441 }
442
443
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());
450
451   DisallowHeapAllocation no_gc;
452
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);
457   }
458 }
459
460
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());
466   DCHECK_EQ(c0_, '[');
467
468   AdvanceSkipWhitespace();
469   if (c0_ != ']') {
470     do {
471       Handle<Object> element = ParseJsonValue();
472       if (element.is_null()) return ReportUnexpectedCharacter();
473       elements.Add(element, zone());
474     } while (MatchSkipWhiteSpace(','));
475     if (c0_ != ']') {
476       return ReportUnexpectedCharacter();
477     }
478   }
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]);
485   }
486   Handle<Object> json_array = factory()->NewJSArrayWithElements(
487       fast_elements, FAST_ELEMENTS, pretenure_);
488   return scope.CloseAndEscape(json_array);
489 }
490
491
492 template <bool seq_one_byte>
493 Handle<Object> JsonParser<seq_one_byte>::ParseJsonNumber() {
494   bool negative = false;
495   int beg_pos = position_;
496   if (c0_ == '-') {
497     Advance();
498     negative = true;
499   }
500   if (c0_ == '0') {
501     Advance();
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();
505   } else {
506     int i = 0;
507     int digits = 0;
508     if (c0_ < '1' || c0_ > '9') return ReportUnexpectedCharacter();
509     do {
510       i = i * 10 + c0_ - '0';
511       digits++;
512       Advance();
513     } while (IsDecimalDigit(c0_));
514     if (c0_ != '.' && c0_ != 'e' && c0_ != 'E' && digits < 10) {
515       SkipWhitespace();
516       return Handle<Smi>(Smi::FromInt((negative ? -i : i)), isolate());
517     }
518   }
519   if (c0_ == '.') {
520     Advance();
521     if (!IsDecimalDigit(c0_)) return ReportUnexpectedCharacter();
522     do {
523       Advance();
524     } while (IsDecimalDigit(c0_));
525   }
526   if (AsciiAlphaToLower(c0_) == 'e') {
527     Advance();
528     if (c0_ == '-' || c0_ == '+') Advance();
529     if (!IsDecimalDigit(c0_)) return ReportUnexpectedCharacter();
530     do {
531       Advance();
532     } while (IsDecimalDigit(c0_));
533   }
534   int length = position_ - beg_pos;
535   double number;
536   if (seq_one_byte) {
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());
541   } else {
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(),
547                             result,
548                             NO_FLAGS,  // Hex, octal or trailing junk.
549                             0.0);
550     buffer.Dispose();
551   }
552   SkipWhitespace();
553   return factory()->NewNumber(number, pretenure_);
554 }
555
556
557 template <typename StringType>
558 inline void SeqStringSet(Handle<StringType> seq_str, int i, uc32 c);
559
560 template <>
561 inline void SeqStringSet(Handle<SeqTwoByteString> seq_str, int i, uc32 c) {
562   seq_str->SeqTwoByteStringSet(i, c);
563 }
564
565 template <>
566 inline void SeqStringSet(Handle<SeqOneByteString> seq_str, int i, uc32 c) {
567   seq_str->SeqOneByteStringSet(i, c);
568 }
569
570 template <typename StringType>
571 inline Handle<StringType> NewRawString(Factory* factory,
572                                        int length,
573                                        PretenureFlag pretenure);
574
575 template <>
576 inline Handle<SeqTwoByteString> NewRawString(Factory* factory,
577                                              int length,
578                                              PretenureFlag pretenure) {
579   return factory->NewRawTwoByteString(length, pretenure).ToHandleChecked();
580 }
581
582 template <>
583 inline Handle<SeqOneByteString> NewRawString(Factory* factory,
584                                            int length,
585                                            PretenureFlag pretenure) {
586   return factory->NewRawOneByteString(length, pretenure).ToHandleChecked();
587 }
588
589
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);
605
606   while (c0_ != '"') {
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);
612     }
613     if (c0_ != '\\') {
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_);
621         Advance();
622       } else {
623         // StringType is SeqOneByteString and we just read a non-Latin1 char.
624         return SlowScanJsonString<SeqTwoByteString, uc16>(seq_string, 0, count);
625       }
626     } else {
627       Advance();  // Advance past the \.
628       switch (c0_) {
629         case '"':
630         case '\\':
631         case '/':
632           SeqStringSet(seq_string, count++, c0_);
633           break;
634         case 'b':
635           SeqStringSet(seq_string, count++, '\x08');
636           break;
637         case 'f':
638           SeqStringSet(seq_string, count++, '\x0c');
639           break;
640         case 'n':
641           SeqStringSet(seq_string, count++, '\x0a');
642           break;
643         case 'r':
644           SeqStringSet(seq_string, count++, '\x0d');
645           break;
646         case 't':
647           SeqStringSet(seq_string, count++, '\x09');
648           break;
649         case 'u': {
650           uc32 value = 0;
651           for (int i = 0; i < 4; i++) {
652             Advance();
653             int digit = HexValue(c0_);
654             if (digit < 0) {
655               return Handle<String>::null();
656             }
657             value = value * 16 + digit;
658           }
659           if (sizeof(SinkChar) == kUC16Size ||
660               value <= String::kMaxOneByteCharCode) {
661             SeqStringSet(seq_string, count++, value);
662             break;
663           } else {
664             // StringType is SeqOneByteString and we just read a non-Latin1
665             // char.
666             position_ -= 6;  // Rewind position_ to \ in \uxxxx.
667             Advance();
668             return SlowScanJsonString<SeqTwoByteString, uc16>(seq_string,
669                                                               0,
670                                                               count);
671           }
672         }
673         default:
674           return Handle<String>::null();
675       }
676       Advance();
677     }
678   }
679
680   DCHECK_EQ('"', c0_);
681   // Advance past the last '"'.
682   AdvanceSkipWhitespace();
683
684   // Shrink seq_string length to count and return.
685   return SeqString::Truncate(seq_string, count);
686 }
687
688
689 template <bool seq_one_byte>
690 template <bool is_internalized>
691 Handle<String> JsonParser<seq_one_byte>::ScanJsonString() {
692   DCHECK_EQ('"', c0_);
693   Advance();
694   if (c0_ == '"') {
695     AdvanceSkipWhitespace();
696     return factory()->empty_string();
697   }
698
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_;
705     uc32 c0 = c0_;
706     do {
707       if (c0 == '\\') {
708         c0_ = c0;
709         int beg_pos = position_;
710         position_ = position;
711         return SlowScanJsonString<SeqOneByteString, uint8_t>(source_,
712                                                              beg_pos,
713                                                              position_);
714       }
715       if (c0 < 0x20) return Handle<String>::null();
716       if (static_cast<uint32_t>(c0) >
717           unibrow::Utf16::kMaxNonSurrogateCharCode) {
718         running_hash =
719             StringHasher::AddCharacterCore(running_hash,
720                                            unibrow::Utf16::LeadSurrogate(c0));
721         running_hash =
722             StringHasher::AddCharacterCore(running_hash,
723                                            unibrow::Utf16::TrailSurrogate(c0));
724       } else {
725         running_hash = StringHasher::AddCharacterCore(running_hash, c0);
726       }
727       position++;
728       if (position >= source_length_) return Handle<String>::null();
729       c0 = seq_source_->SeqOneByteStringGet(position);
730     } while (c0 != '"');
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);
740     uint32_t count = 1;
741     Handle<String> result;
742     while (true) {
743       Object* element = string_table->KeyAt(entry);
744       if (element == isolate()->heap()->undefined_value()) {
745         // Lookup failure.
746         result = factory()->InternalizeOneByteString(
747             seq_source_, position_, length);
748         break;
749       }
750       if (element != isolate()->heap()->the_hole_value() &&
751           String::cast(element)->IsOneByteEqualTo(string_vector)) {
752         result = Handle<String>(String::cast(element), isolate());
753 #ifdef DEBUG
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));
758 #endif
759         break;
760       }
761       entry = StringTable::NextProbe(entry, count++, capacity);
762     }
763     position_ = position;
764     // Advance past the last '"'.
765     AdvanceSkipWhitespace();
766     return result;
767   }
768
769   int beg_pos = position_;
770   // Fast case for Latin1 only without escape characters.
771   do {
772     // Check for control character (0x00-0x1f) or unterminated string (<0).
773     if (c0_ < 0x20) return Handle<String>::null();
774     if (c0_ != '\\') {
775       if (seq_one_byte || c0_ <= String::kMaxOneByteCharCode) {
776         Advance();
777       } else {
778         return SlowScanJsonString<SeqTwoByteString, uc16>(source_,
779                                                           beg_pos,
780                                                           position_);
781       }
782     } else {
783       return SlowScanJsonString<SeqOneByteString, uint8_t>(source_,
784                                                            beg_pos,
785                                                            position_);
786     }
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_);
793
794   DCHECK_EQ('"', c0_);
795   // Advance past the last '"'.
796   AdvanceSkipWhitespace();
797   return result;
798 }
799
800 } }  // namespace v8::internal
801
802 #endif  // V8_JSON_PARSER_H_