9a22738e98d9ae806366d94da030a345b10fed63
[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           // The expected string has to be free of \, " and characters < 0x20.
112           if (c0 != expected_chars[i]) return false;
113         }
114         if (input_chars[length] == '"') {
115           position_ = position_ + length + 1;
116           AdvanceSkipWhitespace();
117           return true;
118         }
119       }
120     }
121     return false;
122   }
123
124   Handle<String> ParseJsonInternalizedString() {
125     return ScanJsonString<true>();
126   }
127
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);
135
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();
143
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();
148
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
154   // JavaScript array.
155   Handle<Object> ParseJsonObject();
156
157   // Parses a JSON array literal (grammar production JSONArray). An array
158   // literal is a square-bracketed and comma separated sequence (possibly empty)
159   // of JSON values.
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();
163
164
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();
169   }
170
171   inline Isolate* isolate() { return isolate_; }
172   inline Factory* factory() { return factory_; }
173   inline Handle<JSFunction> object_constructor() { return object_constructor_; }
174
175   static const int kInitialSpecialStringLength = 1024;
176   static const int kPretenureTreshold = 100 * 1024;
177
178
179  private:
180   Zone* zone() { return &zone_; }
181
182   void CommitStateToJsonObject(Handle<JSObject> json_object, Handle<Map> map,
183                                ZoneList<Handle<Object> >* properties);
184
185   Handle<String> source_;
186   int source_length_;
187   Handle<SeqOneByteString> seq_source_;
188
189   PretenureFlag pretenure_;
190   Isolate* isolate_;
191   Factory* factory_;
192   Zone zone_;
193   Handle<JSFunction> object_constructor_;
194   uc32 c0_;
195   int position_;
196 };
197
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();
206
207     // Parse failed. Current character is the unexpected token.
208     const char* message;
209     Factory* factory = this->factory();
210     Handle<JSArray> array;
211
212     switch (c0_) {
213       case kEndOfString:
214         message = "unexpected_eos";
215         array = factory->NewJSArray(0);
216         break;
217       case '-':
218       case '0':
219       case '1':
220       case '2':
221       case '3':
222       case '4':
223       case '5':
224       case '6':
225       case '7':
226       case '8':
227       case '9':
228         message = "unexpected_token_number";
229         array = factory->NewJSArray(0);
230         break;
231       case '"':
232         message = "unexpected_token_string";
233         array = factory->NewJSArray(0);
234         break;
235       default:
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);
241         break;
242     }
243
244     MessageLocation location(factory->NewScript(source_),
245                              position_,
246                              position_ + 1);
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);
251   }
252   return result;
253 }
254
255
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();
263   }
264
265   if (c0_ == '"') return ParseJsonString();
266   if ((c0_ >= '0' && c0_ <= '9') || c0_ == '-') return ParseJsonNumber();
267   if (c0_ == '{') return ParseJsonObject();
268   if (c0_ == '[') return ParseJsonArray();
269   if (c0_ == 'f') {
270     if (AdvanceGetChar() == 'a' && AdvanceGetChar() == 'l' &&
271         AdvanceGetChar() == 's' && AdvanceGetChar() == 'e') {
272       AdvanceSkipWhitespace();
273       return factory()->false_value();
274     }
275     return ReportUnexpectedCharacter();
276   }
277   if (c0_ == 't') {
278     if (AdvanceGetChar() == 'r' && AdvanceGetChar() == 'u' &&
279         AdvanceGetChar() == 'e') {
280       AdvanceSkipWhitespace();
281       return factory()->true_value();
282     }
283     return ReportUnexpectedCharacter();
284   }
285   if (c0_ == 'n') {
286     if (AdvanceGetChar() == 'u' && AdvanceGetChar() == 'l' &&
287         AdvanceGetChar() == 'l') {
288       AdvanceSkipWhitespace();
289       return factory()->null_value();
290     }
291     return ReportUnexpectedCharacter();
292   }
293   return ReportUnexpectedCharacter();
294 }
295
296
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());
305   DCHECK_EQ(c0_, '{');
306
307   bool transitioning = true;
308
309   AdvanceSkipWhitespace();
310   if (c0_ != '}') {
311     do {
312       if (c0_ != '"') return ReportUnexpectedCharacter();
313
314       int start_position = position_;
315       Advance();
316
317       uint32_t index = 0;
318       if (c0_ >= '0' && c0_ <= '9') {
319         // Maybe an array index, try to parse it.
320         if (c0_ == '0') {
321           // With a leading zero, the string has to be "0" only to be an index.
322           Advance();
323         } else {
324           do {
325             int d = c0_ - '0';
326             if (index > 429496729U - ((d > 5) ? 1 : 0)) break;
327             index = (index * 10) + d;
328             Advance();
329           } while (c0_ >= '0' && c0_ <= '9');
330         }
331
332         if (c0_ == '"') {
333           // Successfully parsed index, parse and store element.
334           AdvanceSkipWhitespace();
335
336           if (c0_ != ':') return ReportUnexpectedCharacter();
337           AdvanceSkipWhitespace();
338           Handle<Object> value = ParseJsonValue();
339           if (value.is_null()) return ReportUnexpectedCharacter();
340
341           JSObject::SetOwnElement(json_object, index, value, SLOPPY).Assert();
342           continue;
343         }
344         // Not an index, fallback to the slow path.
345       }
346
347       position_ = start_position;
348 #ifdef DEBUG
349       c0_ = '"';
350 #endif
351
352       Handle<String> key;
353       Handle<Object> value;
354
355       // Try to follow existing transitions as long as possible. Once we stop
356       // transitioning, no transition can be found anymore.
357       if (transitioning) {
358         // First check whether there is a single expected transition. If so, try
359         // to parse it first.
360         bool follow_expected = false;
361         Handle<Map> target;
362         if (seq_one_byte) {
363           key = Map::ExpectedTransitionKey(map);
364           follow_expected = !key.is_null() && ParseJsonString(key);
365         }
366         // If the expected transition hits, follow it.
367         if (follow_expected) {
368           target = Map::ExpectedTransitionTarget(map);
369         } else {
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();
374
375           target = Map::FindTransitionToField(map, key);
376           // If a transition was found, follow it and continue.
377           transitioning = !target.is_null();
378         }
379         if (c0_ != ':') return ReportUnexpectedCharacter();
380
381         AdvanceSkipWhitespace();
382         value = ParseJsonValue();
383         if (value.is_null()) return ReportUnexpectedCharacter();
384
385         if (transitioning) {
386           int descriptor = map->NumberOfOwnDescriptors();
387           PropertyDetails details =
388               target->instance_descriptors()->GetDetails(descriptor);
389           Representation expected_representation = details.representation();
390
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);
402             }
403             DCHECK(target->instance_descriptors()->GetFieldType(
404                     descriptor)->NowContains(value));
405             properties.Add(value, zone());
406             map = target;
407             continue;
408           } else {
409             transitioning = false;
410           }
411         }
412
413         // Commit the intermediate state to the object and stop transitioning.
414         CommitStateToJsonObject(json_object, map, &properties);
415       } else {
416         key = ParseJsonInternalizedString();
417         if (key.is_null() || c0_ != ':') return ReportUnexpectedCharacter();
418
419         AdvanceSkipWhitespace();
420         value = ParseJsonValue();
421         if (value.is_null()) return ReportUnexpectedCharacter();
422       }
423
424       Runtime::DefineObjectProperty(json_object, key, value, NONE).Check();
425     } while (MatchSkipWhiteSpace(','));
426     if (c0_ != '}') {
427       return ReportUnexpectedCharacter();
428     }
429
430     // If we transitioned until the very end, transition the map now.
431     if (transitioning) {
432       CommitStateToJsonObject(json_object, map, &properties);
433     }
434   }
435   AdvanceSkipWhitespace();
436   return scope.CloseAndEscape(json_object);
437 }
438
439
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());
446
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
453   // map.
454   bool slow_case = json_object->map() != *map;
455   DescriptorArray* descriptors = NULL;
456
457   int length = properties->length();
458   if (slow_case) {
459     descriptors = json_object->map()->instance_descriptors();
460     DCHECK(json_object->map()->NumberOfOwnDescriptors() == length);
461   }
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
467       // is not double.
468       HeapNumber::cast(*value)->set_map(*factory->heap_number_map());
469     }
470     FieldIndex index = FieldIndex::ForPropertyIndex(*map, i);
471     json_object->FastPropertyAtPut(index, *value);
472   }
473 }
474
475
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());
481   DCHECK_EQ(c0_, '[');
482
483   AdvanceSkipWhitespace();
484   if (c0_ != ']') {
485     do {
486       Handle<Object> element = ParseJsonValue();
487       if (element.is_null()) return ReportUnexpectedCharacter();
488       elements.Add(element, zone());
489     } while (MatchSkipWhiteSpace(','));
490     if (c0_ != ']') {
491       return ReportUnexpectedCharacter();
492     }
493   }
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]);
500   }
501   Handle<Object> json_array = factory()->NewJSArrayWithElements(
502       fast_elements, FAST_ELEMENTS, pretenure_);
503   return scope.CloseAndEscape(json_array);
504 }
505
506
507 template <bool seq_one_byte>
508 Handle<Object> JsonParser<seq_one_byte>::ParseJsonNumber() {
509   bool negative = false;
510   int beg_pos = position_;
511   if (c0_ == '-') {
512     Advance();
513     negative = true;
514   }
515   if (c0_ == '0') {
516     Advance();
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();
520   } else {
521     int i = 0;
522     int digits = 0;
523     if (c0_ < '1' || c0_ > '9') return ReportUnexpectedCharacter();
524     do {
525       i = i * 10 + c0_ - '0';
526       digits++;
527       Advance();
528     } while (c0_ >= '0' && c0_ <= '9');
529     if (c0_ != '.' && c0_ != 'e' && c0_ != 'E' && digits < 10) {
530       SkipWhitespace();
531       return Handle<Smi>(Smi::FromInt((negative ? -i : i)), isolate());
532     }
533   }
534   if (c0_ == '.') {
535     Advance();
536     if (c0_ < '0' || c0_ > '9') return ReportUnexpectedCharacter();
537     do {
538       Advance();
539     } while (c0_ >= '0' && c0_ <= '9');
540   }
541   if (AsciiAlphaToLower(c0_) == 'e') {
542     Advance();
543     if (c0_ == '-' || c0_ == '+') Advance();
544     if (c0_ < '0' || c0_ > '9') return ReportUnexpectedCharacter();
545     do {
546       Advance();
547     } while (c0_ >= '0' && c0_ <= '9');
548   }
549   int length = position_ - beg_pos;
550   double number;
551   if (seq_one_byte) {
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());
556   } else {
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(),
562                             result,
563                             NO_FLAGS,  // Hex, octal or trailing junk.
564                             0.0);
565     buffer.Dispose();
566   }
567   SkipWhitespace();
568   return factory()->NewNumber(number, pretenure_);
569 }
570
571
572 template <typename StringType>
573 inline void SeqStringSet(Handle<StringType> seq_str, int i, uc32 c);
574
575 template <>
576 inline void SeqStringSet(Handle<SeqTwoByteString> seq_str, int i, uc32 c) {
577   seq_str->SeqTwoByteStringSet(i, c);
578 }
579
580 template <>
581 inline void SeqStringSet(Handle<SeqOneByteString> seq_str, int i, uc32 c) {
582   seq_str->SeqOneByteStringSet(i, c);
583 }
584
585 template <typename StringType>
586 inline Handle<StringType> NewRawString(Factory* factory,
587                                        int length,
588                                        PretenureFlag pretenure);
589
590 template <>
591 inline Handle<SeqTwoByteString> NewRawString(Factory* factory,
592                                              int length,
593                                              PretenureFlag pretenure) {
594   return factory->NewRawTwoByteString(length, pretenure).ToHandleChecked();
595 }
596
597 template <>
598 inline Handle<SeqOneByteString> NewRawString(Factory* factory,
599                                            int length,
600                                            PretenureFlag pretenure) {
601   return factory->NewRawOneByteString(length, pretenure).ToHandleChecked();
602 }
603
604
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);
620
621   while (c0_ != '"') {
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);
627     }
628     if (c0_ != '\\') {
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_);
636         Advance();
637       } else {
638         // StringType is SeqOneByteString and we just read a non-Latin1 char.
639         return SlowScanJsonString<SeqTwoByteString, uc16>(seq_string, 0, count);
640       }
641     } else {
642       Advance();  // Advance past the \.
643       switch (c0_) {
644         case '"':
645         case '\\':
646         case '/':
647           SeqStringSet(seq_string, count++, c0_);
648           break;
649         case 'b':
650           SeqStringSet(seq_string, count++, '\x08');
651           break;
652         case 'f':
653           SeqStringSet(seq_string, count++, '\x0c');
654           break;
655         case 'n':
656           SeqStringSet(seq_string, count++, '\x0a');
657           break;
658         case 'r':
659           SeqStringSet(seq_string, count++, '\x0d');
660           break;
661         case 't':
662           SeqStringSet(seq_string, count++, '\x09');
663           break;
664         case 'u': {
665           uc32 value = 0;
666           for (int i = 0; i < 4; i++) {
667             Advance();
668             int digit = HexValue(c0_);
669             if (digit < 0) {
670               return Handle<String>::null();
671             }
672             value = value * 16 + digit;
673           }
674           if (sizeof(SinkChar) == kUC16Size ||
675               value <= String::kMaxOneByteCharCode) {
676             SeqStringSet(seq_string, count++, value);
677             break;
678           } else {
679             // StringType is SeqOneByteString and we just read a non-Latin1
680             // char.
681             position_ -= 6;  // Rewind position_ to \ in \uxxxx.
682             Advance();
683             return SlowScanJsonString<SeqTwoByteString, uc16>(seq_string,
684                                                               0,
685                                                               count);
686           }
687         }
688         default:
689           return Handle<String>::null();
690       }
691       Advance();
692     }
693   }
694
695   DCHECK_EQ('"', c0_);
696   // Advance past the last '"'.
697   AdvanceSkipWhitespace();
698
699   // Shrink seq_string length to count and return.
700   return SeqString::Truncate(seq_string, count);
701 }
702
703
704 template <bool seq_one_byte>
705 template <bool is_internalized>
706 Handle<String> JsonParser<seq_one_byte>::ScanJsonString() {
707   DCHECK_EQ('"', c0_);
708   Advance();
709   if (c0_ == '"') {
710     AdvanceSkipWhitespace();
711     return factory()->empty_string();
712   }
713
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_;
720     uc32 c0 = c0_;
721     do {
722       if (c0 == '\\') {
723         c0_ = c0;
724         int beg_pos = position_;
725         position_ = position;
726         return SlowScanJsonString<SeqOneByteString, uint8_t>(source_,
727                                                              beg_pos,
728                                                              position_);
729       }
730       if (c0 < 0x20) return Handle<String>::null();
731       if (static_cast<uint32_t>(c0) >
732           unibrow::Utf16::kMaxNonSurrogateCharCode) {
733         running_hash =
734             StringHasher::AddCharacterCore(running_hash,
735                                            unibrow::Utf16::LeadSurrogate(c0));
736         running_hash =
737             StringHasher::AddCharacterCore(running_hash,
738                                            unibrow::Utf16::TrailSurrogate(c0));
739       } else {
740         running_hash = StringHasher::AddCharacterCore(running_hash, c0);
741       }
742       position++;
743       if (position >= source_length_) return Handle<String>::null();
744       c0 = seq_source_->SeqOneByteStringGet(position);
745     } while (c0 != '"');
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);
755     uint32_t count = 1;
756     Handle<String> result;
757     while (true) {
758       Object* element = string_table->KeyAt(entry);
759       if (element == isolate()->heap()->undefined_value()) {
760         // Lookup failure.
761         result = factory()->InternalizeOneByteString(
762             seq_source_, position_, length);
763         break;
764       }
765       if (element != isolate()->heap()->the_hole_value() &&
766           String::cast(element)->IsOneByteEqualTo(string_vector)) {
767         result = Handle<String>(String::cast(element), isolate());
768 #ifdef DEBUG
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));
773 #endif
774         break;
775       }
776       entry = StringTable::NextProbe(entry, count++, capacity);
777     }
778     position_ = position;
779     // Advance past the last '"'.
780     AdvanceSkipWhitespace();
781     return result;
782   }
783
784   int beg_pos = position_;
785   // Fast case for Latin1 only without escape characters.
786   do {
787     // Check for control character (0x00-0x1f) or unterminated string (<0).
788     if (c0_ < 0x20) return Handle<String>::null();
789     if (c0_ != '\\') {
790       if (seq_one_byte || c0_ <= String::kMaxOneByteCharCode) {
791         Advance();
792       } else {
793         return SlowScanJsonString<SeqTwoByteString, uc16>(source_,
794                                                           beg_pos,
795                                                           position_);
796       }
797     } else {
798       return SlowScanJsonString<SeqOneByteString, uint8_t>(source_,
799                                                            beg_pos,
800                                                            position_);
801     }
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_);
808
809   DCHECK_EQ('"', c0_);
810   // Advance past the last '"'.
811   AdvanceSkipWhitespace();
812   return result;
813 }
814
815 } }  // namespace v8::internal
816
817 #endif  // V8_JSON_PARSER_H_