blob: 5ebbcdd861b351bc072d08ba209037bc1ed36678 [file] [log] [blame]
Ben Murdoch257744e2011-11-30 15:57:28 +00001// Copyright 2011 the V8 project authors. All rights reserved.
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
Ben Murdoch257744e2011-11-30 15:57:28 +00004
5#ifndef V8_JSON_PARSER_H_
6#define V8_JSON_PARSER_H_
7
Ben Murdochb8a8cc12014-11-26 15:28:44 +00008#include "src/v8.h"
Ben Murdoch3fb3ca82011-12-02 17:19:32 +00009
Ben Murdochb8a8cc12014-11-26 15:28:44 +000010#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"
Ben Murdoch257744e2011-11-30 15:57:28 +000015
16namespace v8 {
17namespace internal {
18
19// A simple json parser.
Ben Murdochb8a8cc12014-11-26 15:28:44 +000020template <bool seq_one_byte>
Ben Murdoch257744e2011-11-30 15:57:28 +000021class JsonParser BASE_EMBEDDED {
22 public:
Ben Murdochb8a8cc12014-11-26 15:28:44 +000023 MUST_USE_RESULT static MaybeHandle<Object> Parse(Handle<String> source) {
24 return JsonParser(source).ParseJson();
Ben Murdoch257744e2011-11-30 15:57:28 +000025 }
26
27 static const int kEndOfString = -1;
28
29 private:
Ben Murdochb8a8cc12014-11-26 15:28:44 +000030 explicit JsonParser(Handle<String> source)
31 : source_(source),
32 source_length_(source->length()),
33 isolate_(source->map()->GetHeap()->isolate()),
34 factory_(isolate_->factory()),
35 zone_(isolate_),
36 object_constructor_(isolate_->native_context()->object_function(),
37 isolate_),
38 position_(-1) {
39 source_ = String::Flatten(source_);
40 pretenure_ = (source_length_ >= kPretenureTreshold) ? TENURED : NOT_TENURED;
41
42 // Optimized fast case where we only have Latin1 characters.
43 if (seq_one_byte) {
44 seq_source_ = Handle<SeqOneByteString>::cast(source_);
45 }
46 }
47
Ben Murdoch257744e2011-11-30 15:57:28 +000048 // Parse a string containing a single JSON value.
Ben Murdochb8a8cc12014-11-26 15:28:44 +000049 MaybeHandle<Object> ParseJson();
Ben Murdoch257744e2011-11-30 15:57:28 +000050
51 inline void Advance() {
Ben Murdoch3fb3ca82011-12-02 17:19:32 +000052 position_++;
Ben Murdoch257744e2011-11-30 15:57:28 +000053 if (position_ >= source_length_) {
Ben Murdoch257744e2011-11-30 15:57:28 +000054 c0_ = kEndOfString;
Ben Murdochb8a8cc12014-11-26 15:28:44 +000055 } else if (seq_one_byte) {
56 c0_ = seq_source_->SeqOneByteStringGet(position_);
Ben Murdoch257744e2011-11-30 15:57:28 +000057 } else {
Ben Murdoch257744e2011-11-30 15:57:28 +000058 c0_ = source_->Get(position_);
59 }
60 }
61
Ben Murdoch3fb3ca82011-12-02 17:19:32 +000062 // 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.
Ben Murdoch257744e2011-11-30 15:57:28 +000065
Ben Murdoch3fb3ca82011-12-02 17:19:32 +000066 inline void AdvanceSkipWhitespace() {
67 do {
68 Advance();
Ben Murdochb8a8cc12014-11-26 15:28:44 +000069 } while (c0_ == ' ' || c0_ == '\t' || c0_ == '\n' || c0_ == '\r');
Ben Murdoch3fb3ca82011-12-02 17:19:32 +000070 }
Ben Murdoch257744e2011-11-30 15:57:28 +000071
Ben Murdoch3fb3ca82011-12-02 17:19:32 +000072 inline void SkipWhitespace() {
Ben Murdochb8a8cc12014-11-26 15:28:44 +000073 while (c0_ == ' ' || c0_ == '\t' || c0_ == '\n' || c0_ == '\r') {
Ben Murdoch3fb3ca82011-12-02 17:19:32 +000074 Advance();
75 }
76 }
77
78 inline uc32 AdvanceGetChar() {
79 Advance();
80 return c0_;
81 }
82
83 // Checks that current charater is c.
84 // If so, then consume c and skip whitespace.
85 inline bool MatchSkipWhiteSpace(uc32 c) {
86 if (c0_ == c) {
87 AdvanceSkipWhitespace();
88 return true;
89 }
90 return false;
91 }
Ben Murdoch257744e2011-11-30 15:57:28 +000092
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.
Ben Murdoch3fb3ca82011-12-02 17:19:32 +000097 Handle<String> ParseJsonString() {
98 return ScanJsonString<false>();
99 }
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000100
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.IsOneByte()) {
107 DCHECK_EQ('"', c0_);
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 == '\\') {
114 return false;
115 }
116 }
117 if (input_chars[length] == '"') {
118 position_ = position_ + length + 1;
119 AdvanceSkipWhitespace();
120 return true;
121 }
122 }
123 }
124 return false;
125 }
126
127 Handle<String> ParseJsonInternalizedString() {
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000128 return ScanJsonString<true>();
129 }
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000130
131 template <bool is_internalized>
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000132 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
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000135 // prefix. Called by ScanJsonString when reaching a '\' or non-Latin1 char.
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000136 template <typename StringType, typename SinkChar>
137 Handle<String> SlowScanJsonString(Handle<String> prefix, int start, int end);
Ben Murdoch257744e2011-11-30 15:57:28 +0000138
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.
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000145 Handle<Object> ParseJsonNumber();
Ben Murdoch257744e2011-11-30 15:57:28 +0000146
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();
151
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.
Ben Murdoch3ef787d2012-04-12 10:51:47 +0100156 // A JSON array doesn't allow numbers and identifiers as keys, like a
Ben Murdoch257744e2011-11-30 15:57:28 +0000157 // JavaScript array.
158 Handle<Object> ParseJsonObject();
159
160 // Parses a JSON array literal (grammar production JSONArray). An array
161 // literal is a square-bracketed and comma separated sequence (possibly empty)
162 // of JSON values.
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();
166
167
168 // Mark that a parsing error has happened at the current token, and
169 // return a null handle. Primarily for readability.
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000170 inline Handle<Object> ReportUnexpectedCharacter() {
171 return Handle<Object>::null();
172 }
Ben Murdoch257744e2011-11-30 15:57:28 +0000173
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000174 inline Isolate* isolate() { return isolate_; }
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000175 inline Factory* factory() { return factory_; }
176 inline Handle<JSFunction> object_constructor() { return object_constructor_; }
Ben Murdoch257744e2011-11-30 15:57:28 +0000177
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000178 static const int kInitialSpecialStringLength = 1024;
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000179 static const int kPretenureTreshold = 100 * 1024;
Ben Murdoch257744e2011-11-30 15:57:28 +0000180
181
182 private:
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000183 Zone* zone() { return &zone_; }
184
185 void CommitStateToJsonObject(Handle<JSObject> json_object, Handle<Map> map,
186 ZoneList<Handle<Object> >* properties);
187
Ben Murdoch257744e2011-11-30 15:57:28 +0000188 Handle<String> source_;
189 int source_length_;
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000190 Handle<SeqOneByteString> seq_source_;
Ben Murdoch257744e2011-11-30 15:57:28 +0000191
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000192 PretenureFlag pretenure_;
Ben Murdoch257744e2011-11-30 15:57:28 +0000193 Isolate* isolate_;
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000194 Factory* factory_;
195 Zone zone_;
196 Handle<JSFunction> object_constructor_;
Ben Murdoch257744e2011-11-30 15:57:28 +0000197 uc32 c0_;
198 int position_;
Ben Murdoch257744e2011-11-30 15:57:28 +0000199};
200
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000201template <bool seq_one_byte>
202MaybeHandle<Object> JsonParser<seq_one_byte>::ParseJson() {
Ben Murdoch3ef787d2012-04-12 10:51:47 +0100203 // Advance to the first character (possibly EOS)
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000204 AdvanceSkipWhitespace();
205 Handle<Object> result = ParseJsonValue();
206 if (result.is_null() || c0_ != kEndOfString) {
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000207 // Some exception (for example stack overflow) is already pending.
208 if (isolate_->has_pending_exception()) return Handle<Object>::null();
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000209
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000210 // Parse failed. Current character is the unexpected token.
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000211 const char* message;
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000212 Factory* factory = this->factory();
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000213 Handle<JSArray> array;
214
215 switch (c0_) {
216 case kEndOfString:
217 message = "unexpected_eos";
218 array = factory->NewJSArray(0);
219 break;
220 case '-':
221 case '0':
222 case '1':
223 case '2':
224 case '3':
225 case '4':
226 case '5':
227 case '6':
228 case '7':
229 case '8':
230 case '9':
231 message = "unexpected_token_number";
232 array = factory->NewJSArray(0);
233 break;
234 case '"':
235 message = "unexpected_token_string";
236 array = factory->NewJSArray(0);
237 break;
238 default:
239 message = "unexpected_token";
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000240 Handle<Object> name = factory->LookupSingleCharacterStringFromCode(c0_);
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000241 Handle<FixedArray> element = factory->NewFixedArray(1);
242 element->set(0, *name);
243 array = factory->NewJSArrayWithElements(element);
244 break;
245 }
246
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000247 MessageLocation location(factory->NewScript(source_),
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000248 position_,
249 position_ + 1);
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000250 Handle<Object> error;
251 ASSIGN_RETURN_ON_EXCEPTION(isolate(), error,
252 factory->NewSyntaxError(message, array), Object);
253 return isolate()->template Throw<Object>(error, &location);
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000254 }
255 return result;
256}
257
258
259// Parse any JSON value.
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000260template <bool seq_one_byte>
261Handle<Object> JsonParser<seq_one_byte>::ParseJsonValue() {
262 StackLimitCheck stack_check(isolate_);
263 if (stack_check.HasOverflowed()) {
264 isolate_->StackOverflow();
265 return Handle<Object>::null();
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000266 }
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000267
268 if (c0_ == '"') return ParseJsonString();
269 if ((c0_ >= '0' && c0_ <= '9') || c0_ == '-') return ParseJsonNumber();
270 if (c0_ == '{') return ParseJsonObject();
271 if (c0_ == '[') return ParseJsonArray();
272 if (c0_ == 'f') {
273 if (AdvanceGetChar() == 'a' && AdvanceGetChar() == 'l' &&
274 AdvanceGetChar() == 's' && AdvanceGetChar() == 'e') {
275 AdvanceSkipWhitespace();
276 return factory()->false_value();
277 }
278 return ReportUnexpectedCharacter();
279 }
280 if (c0_ == 't') {
281 if (AdvanceGetChar() == 'r' && AdvanceGetChar() == 'u' &&
282 AdvanceGetChar() == 'e') {
283 AdvanceSkipWhitespace();
284 return factory()->true_value();
285 }
286 return ReportUnexpectedCharacter();
287 }
288 if (c0_ == 'n') {
289 if (AdvanceGetChar() == 'u' && AdvanceGetChar() == 'l' &&
290 AdvanceGetChar() == 'l') {
291 AdvanceSkipWhitespace();
292 return factory()->null_value();
293 }
294 return ReportUnexpectedCharacter();
295 }
296 return ReportUnexpectedCharacter();
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000297}
298
299
300// Parse a JSON object. Position must be right at '{'.
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000301template <bool seq_one_byte>
302Handle<Object> JsonParser<seq_one_byte>::ParseJsonObject() {
303 HandleScope scope(isolate());
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000304 Handle<JSObject> json_object =
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000305 factory()->NewJSObject(object_constructor(), pretenure_);
306 Handle<Map> map(json_object->map());
307 ZoneList<Handle<Object> > properties(8, zone());
308 DCHECK_EQ(c0_, '{');
309
310 bool transitioning = true;
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000311
312 AdvanceSkipWhitespace();
313 if (c0_ != '}') {
314 do {
315 if (c0_ != '"') return ReportUnexpectedCharacter();
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000316
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000317 int start_position = position_;
318 Advance();
319
320 uint32_t index = 0;
321 if (c0_ >= '0' && c0_ <= '9') {
322 // Maybe an array index, try to parse it.
323 if (c0_ == '0') {
324 // With a leading zero, the string has to be "0" only to be an index.
325 Advance();
326 } else {
327 do {
328 int d = c0_ - '0';
329 if (index > 429496729U - ((d > 5) ? 1 : 0)) break;
330 index = (index * 10) + d;
331 Advance();
332 } while (c0_ >= '0' && c0_ <= '9');
333 }
334
335 if (c0_ == '"') {
336 // Successfully parsed index, parse and store element.
337 AdvanceSkipWhitespace();
338
339 if (c0_ != ':') return ReportUnexpectedCharacter();
340 AdvanceSkipWhitespace();
341 Handle<Object> value = ParseJsonValue();
342 if (value.is_null()) return ReportUnexpectedCharacter();
343
344 JSObject::SetOwnElement(json_object, index, value, SLOPPY).Assert();
345 continue;
346 }
347 // Not an index, fallback to the slow path.
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000348 }
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000349
350 position_ = start_position;
351#ifdef DEBUG
352 c0_ = '"';
353#endif
354
355 Handle<String> key;
356 Handle<Object> value;
357
358 // Try to follow existing transitions as long as possible. Once we stop
359 // transitioning, no transition can be found anymore.
360 if (transitioning) {
361 // First check whether there is a single expected transition. If so, try
362 // to parse it first.
363 bool follow_expected = false;
364 Handle<Map> target;
365 if (seq_one_byte) {
366 key = Map::ExpectedTransitionKey(map);
367 follow_expected = !key.is_null() && ParseJsonString(key);
368 }
369 // If the expected transition hits, follow it.
370 if (follow_expected) {
371 target = Map::ExpectedTransitionTarget(map);
372 } else {
373 // If the expected transition failed, parse an internalized string and
374 // try to find a matching transition.
375 key = ParseJsonInternalizedString();
376 if (key.is_null()) return ReportUnexpectedCharacter();
377
378 target = Map::FindTransitionToField(map, key);
379 // If a transition was found, follow it and continue.
380 transitioning = !target.is_null();
381 }
382 if (c0_ != ':') return ReportUnexpectedCharacter();
383
384 AdvanceSkipWhitespace();
385 value = ParseJsonValue();
386 if (value.is_null()) return ReportUnexpectedCharacter();
387
388 if (transitioning) {
389 int descriptor = map->NumberOfOwnDescriptors();
390 PropertyDetails details =
391 target->instance_descriptors()->GetDetails(descriptor);
392 Representation expected_representation = details.representation();
393
394 if (value->FitsRepresentation(expected_representation)) {
395 if (expected_representation.IsDouble()) {
396 value = Object::NewStorageFor(isolate(), value,
397 expected_representation);
398 } else if (expected_representation.IsHeapObject() &&
399 !target->instance_descriptors()->GetFieldType(
400 descriptor)->NowContains(value)) {
401 Handle<HeapType> value_type(value->OptimalType(
402 isolate(), expected_representation));
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400403 Map::GeneralizeFieldType(target, descriptor,
404 expected_representation, value_type);
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000405 }
406 DCHECK(target->instance_descriptors()->GetFieldType(
407 descriptor)->NowContains(value));
408 properties.Add(value, zone());
409 map = target;
410 continue;
411 } else {
412 transitioning = false;
413 }
414 }
415
416 // Commit the intermediate state to the object and stop transitioning.
417 CommitStateToJsonObject(json_object, map, &properties);
418 } else {
419 key = ParseJsonInternalizedString();
420 if (key.is_null() || c0_ != ':') return ReportUnexpectedCharacter();
421
422 AdvanceSkipWhitespace();
423 value = ParseJsonValue();
424 if (value.is_null()) return ReportUnexpectedCharacter();
425 }
426
427 Runtime::DefineObjectProperty(json_object, key, value, NONE).Check();
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000428 } while (MatchSkipWhiteSpace(','));
429 if (c0_ != '}') {
430 return ReportUnexpectedCharacter();
431 }
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000432
433 // If we transitioned until the very end, transition the map now.
434 if (transitioning) {
435 CommitStateToJsonObject(json_object, map, &properties);
436 }
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000437 }
438 AdvanceSkipWhitespace();
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000439 return scope.CloseAndEscape(json_object);
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000440}
441
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000442
443template <bool seq_one_byte>
444void JsonParser<seq_one_byte>::CommitStateToJsonObject(
445 Handle<JSObject> json_object, Handle<Map> map,
446 ZoneList<Handle<Object> >* properties) {
447 JSObject::AllocateStorageForMap(json_object, map);
448 DCHECK(!json_object->map()->is_dictionary_map());
449
450 DisallowHeapAllocation no_gc;
451 Factory* factory = isolate()->factory();
452 // If the |json_object|'s map is exactly the same as |map| then the
453 // |properties| values correspond to the |map| and nothing more has to be
454 // done. But if the |json_object|'s map is different then we have to
455 // iterate descriptors to ensure that properties still correspond to the
456 // map.
457 bool slow_case = json_object->map() != *map;
458 DescriptorArray* descriptors = NULL;
459
460 int length = properties->length();
461 if (slow_case) {
462 descriptors = json_object->map()->instance_descriptors();
463 DCHECK(json_object->map()->NumberOfOwnDescriptors() == length);
464 }
465 for (int i = 0; i < length; i++) {
466 Handle<Object> value = (*properties)[i];
467 if (slow_case && value->IsMutableHeapNumber() &&
468 !descriptors->GetDetails(i).representation().IsDouble()) {
469 // Turn mutable heap numbers into immutable if the field representation
470 // is not double.
471 HeapNumber::cast(*value)->set_map(*factory->heap_number_map());
472 }
473 FieldIndex index = FieldIndex::ForPropertyIndex(*map, i);
474 json_object->FastPropertyAtPut(index, *value);
475 }
476}
477
478
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000479// Parse a JSON array. Position must be right at '['.
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000480template <bool seq_one_byte>
481Handle<Object> JsonParser<seq_one_byte>::ParseJsonArray() {
482 HandleScope scope(isolate());
483 ZoneList<Handle<Object> > elements(4, zone());
484 DCHECK_EQ(c0_, '[');
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000485
486 AdvanceSkipWhitespace();
487 if (c0_ != ']') {
488 do {
489 Handle<Object> element = ParseJsonValue();
490 if (element.is_null()) return ReportUnexpectedCharacter();
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000491 elements.Add(element, zone());
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000492 } while (MatchSkipWhiteSpace(','));
493 if (c0_ != ']') {
494 return ReportUnexpectedCharacter();
495 }
496 }
497 AdvanceSkipWhitespace();
498 // Allocate a fixed array with all the elements.
499 Handle<FixedArray> fast_elements =
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000500 factory()->NewFixedArray(elements.length(), pretenure_);
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000501 for (int i = 0, n = elements.length(); i < n; i++) {
502 fast_elements->set(i, *elements[i]);
503 }
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000504 Handle<Object> json_array = factory()->NewJSArrayWithElements(
505 fast_elements, FAST_ELEMENTS, pretenure_);
506 return scope.CloseAndEscape(json_array);
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000507}
508
509
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000510template <bool seq_one_byte>
511Handle<Object> JsonParser<seq_one_byte>::ParseJsonNumber() {
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000512 bool negative = false;
513 int beg_pos = position_;
514 if (c0_ == '-') {
515 Advance();
516 negative = true;
517 }
518 if (c0_ == '0') {
519 Advance();
520 // Prefix zero is only allowed if it's the only digit before
521 // a decimal point or exponent.
522 if ('0' <= c0_ && c0_ <= '9') return ReportUnexpectedCharacter();
523 } else {
524 int i = 0;
525 int digits = 0;
526 if (c0_ < '1' || c0_ > '9') return ReportUnexpectedCharacter();
527 do {
528 i = i * 10 + c0_ - '0';
529 digits++;
530 Advance();
531 } while (c0_ >= '0' && c0_ <= '9');
532 if (c0_ != '.' && c0_ != 'e' && c0_ != 'E' && digits < 10) {
533 SkipWhitespace();
534 return Handle<Smi>(Smi::FromInt((negative ? -i : i)), isolate());
535 }
536 }
537 if (c0_ == '.') {
538 Advance();
539 if (c0_ < '0' || c0_ > '9') return ReportUnexpectedCharacter();
540 do {
541 Advance();
542 } while (c0_ >= '0' && c0_ <= '9');
543 }
544 if (AsciiAlphaToLower(c0_) == 'e') {
545 Advance();
546 if (c0_ == '-' || c0_ == '+') Advance();
547 if (c0_ < '0' || c0_ > '9') return ReportUnexpectedCharacter();
548 do {
549 Advance();
550 } while (c0_ >= '0' && c0_ <= '9');
551 }
552 int length = position_ - beg_pos;
553 double number;
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000554 if (seq_one_byte) {
555 Vector<const uint8_t> chars(seq_source_->GetChars() + beg_pos, length);
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000556 number = StringToDouble(isolate()->unicode_cache(),
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000557 chars,
558 NO_FLAGS, // Hex, octal or trailing junk.
559 base::OS::nan_value());
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000560 } else {
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000561 Vector<uint8_t> buffer = Vector<uint8_t>::New(length);
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000562 String::WriteToFlat(*source_, buffer.start(), beg_pos, position_);
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000563 Vector<const uint8_t> result =
564 Vector<const uint8_t>(buffer.start(), length);
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000565 number = StringToDouble(isolate()->unicode_cache(),
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000566 result,
567 NO_FLAGS, // Hex, octal or trailing junk.
568 0.0);
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000569 buffer.Dispose();
570 }
571 SkipWhitespace();
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000572 return factory()->NewNumber(number, pretenure_);
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000573}
574
575
576template <typename StringType>
577inline void SeqStringSet(Handle<StringType> seq_str, int i, uc32 c);
578
579template <>
580inline void SeqStringSet(Handle<SeqTwoByteString> seq_str, int i, uc32 c) {
581 seq_str->SeqTwoByteStringSet(i, c);
582}
583
584template <>
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000585inline void SeqStringSet(Handle<SeqOneByteString> seq_str, int i, uc32 c) {
586 seq_str->SeqOneByteStringSet(i, c);
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000587}
588
589template <typename StringType>
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000590inline Handle<StringType> NewRawString(Factory* factory,
591 int length,
592 PretenureFlag pretenure);
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000593
594template <>
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000595inline Handle<SeqTwoByteString> NewRawString(Factory* factory,
596 int length,
597 PretenureFlag pretenure) {
598 return factory->NewRawTwoByteString(length, pretenure).ToHandleChecked();
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000599}
600
601template <>
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000602inline Handle<SeqOneByteString> NewRawString(Factory* factory,
603 int length,
604 PretenureFlag pretenure) {
605 return factory->NewRawOneByteString(length, pretenure).ToHandleChecked();
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000606}
607
608
609// Scans the rest of a JSON string starting from position_ and writes
610// prefix[start..end] along with the scanned characters into a
611// sequential string of type StringType.
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000612template <bool seq_one_byte>
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000613template <typename StringType, typename SinkChar>
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000614Handle<String> JsonParser<seq_one_byte>::SlowScanJsonString(
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000615 Handle<String> prefix, int start, int end) {
616 int count = end - start;
617 int max_length = count + source_length_ - position_;
618 int length = Min(max_length, Max(kInitialSpecialStringLength, 2 * count));
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000619 Handle<StringType> seq_string =
620 NewRawString<StringType>(factory(), length, pretenure_);
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000621 // Copy prefix into seq_str.
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000622 SinkChar* dest = seq_string->GetChars();
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000623 String::WriteToFlat(*prefix, dest, start, end);
624
625 while (c0_ != '"') {
626 // Check for control character (0x00-0x1f) or unterminated string (<0).
627 if (c0_ < 0x20) return Handle<String>::null();
628 if (count >= length) {
629 // We need to create a longer sequential string for the result.
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000630 return SlowScanJsonString<StringType, SinkChar>(seq_string, 0, count);
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000631 }
632 if (c0_ != '\\') {
633 // If the sink can contain UC16 characters, or source_ contains only
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000634 // Latin1 characters, there's no need to test whether we can store the
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000635 // character. Otherwise check whether the UC16 source character can fit
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000636 // in the Latin1 sink.
637 if (sizeof(SinkChar) == kUC16Size || seq_one_byte ||
638 c0_ <= String::kMaxOneByteCharCode) {
639 SeqStringSet(seq_string, count++, c0_);
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000640 Advance();
641 } else {
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000642 // StringType is SeqOneByteString and we just read a non-Latin1 char.
643 return SlowScanJsonString<SeqTwoByteString, uc16>(seq_string, 0, count);
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000644 }
645 } else {
646 Advance(); // Advance past the \.
647 switch (c0_) {
648 case '"':
649 case '\\':
650 case '/':
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000651 SeqStringSet(seq_string, count++, c0_);
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000652 break;
653 case 'b':
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000654 SeqStringSet(seq_string, count++, '\x08');
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000655 break;
656 case 'f':
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000657 SeqStringSet(seq_string, count++, '\x0c');
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000658 break;
659 case 'n':
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000660 SeqStringSet(seq_string, count++, '\x0a');
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000661 break;
662 case 'r':
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000663 SeqStringSet(seq_string, count++, '\x0d');
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000664 break;
665 case 't':
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000666 SeqStringSet(seq_string, count++, '\x09');
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000667 break;
668 case 'u': {
669 uc32 value = 0;
670 for (int i = 0; i < 4; i++) {
671 Advance();
672 int digit = HexValue(c0_);
673 if (digit < 0) {
674 return Handle<String>::null();
675 }
676 value = value * 16 + digit;
677 }
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000678 if (sizeof(SinkChar) == kUC16Size ||
679 value <= String::kMaxOneByteCharCode) {
680 SeqStringSet(seq_string, count++, value);
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000681 break;
682 } else {
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000683 // StringType is SeqOneByteString and we just read a non-Latin1
684 // char.
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000685 position_ -= 6; // Rewind position_ to \ in \uxxxx.
686 Advance();
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000687 return SlowScanJsonString<SeqTwoByteString, uc16>(seq_string,
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000688 0,
689 count);
690 }
691 }
692 default:
693 return Handle<String>::null();
694 }
695 Advance();
696 }
697 }
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000698
699 DCHECK_EQ('"', c0_);
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000700 // Advance past the last '"'.
701 AdvanceSkipWhitespace();
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000702
703 // Shrink seq_string length to count and return.
704 return SeqString::Truncate(seq_string, count);
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000705}
706
707
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000708template <bool seq_one_byte>
709template <bool is_internalized>
710Handle<String> JsonParser<seq_one_byte>::ScanJsonString() {
711 DCHECK_EQ('"', c0_);
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000712 Advance();
713 if (c0_ == '"') {
714 AdvanceSkipWhitespace();
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000715 return factory()->empty_string();
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000716 }
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000717
718 if (seq_one_byte && is_internalized) {
719 // Fast path for existing internalized strings. If the the string being
720 // parsed is not a known internalized string, contains backslashes or
721 // unexpectedly reaches the end of string, return with an empty handle.
722 uint32_t running_hash = isolate()->heap()->HashSeed();
723 int position = position_;
724 uc32 c0 = c0_;
725 do {
726 if (c0 == '\\') {
727 c0_ = c0;
728 int beg_pos = position_;
729 position_ = position;
730 return SlowScanJsonString<SeqOneByteString, uint8_t>(source_,
731 beg_pos,
732 position_);
733 }
734 if (c0 < 0x20) return Handle<String>::null();
735 if (static_cast<uint32_t>(c0) >
736 unibrow::Utf16::kMaxNonSurrogateCharCode) {
737 running_hash =
738 StringHasher::AddCharacterCore(running_hash,
739 unibrow::Utf16::LeadSurrogate(c0));
740 running_hash =
741 StringHasher::AddCharacterCore(running_hash,
742 unibrow::Utf16::TrailSurrogate(c0));
743 } else {
744 running_hash = StringHasher::AddCharacterCore(running_hash, c0);
745 }
746 position++;
747 if (position >= source_length_) return Handle<String>::null();
748 c0 = seq_source_->SeqOneByteStringGet(position);
749 } while (c0 != '"');
750 int length = position - position_;
751 uint32_t hash = (length <= String::kMaxHashCalcLength)
752 ? StringHasher::GetHashCore(running_hash)
753 : static_cast<uint32_t>(length);
754 Vector<const uint8_t> string_vector(
755 seq_source_->GetChars() + position_, length);
756 StringTable* string_table = isolate()->heap()->string_table();
757 uint32_t capacity = string_table->Capacity();
758 uint32_t entry = StringTable::FirstProbe(hash, capacity);
759 uint32_t count = 1;
760 Handle<String> result;
761 while (true) {
762 Object* element = string_table->KeyAt(entry);
763 if (element == isolate()->heap()->undefined_value()) {
764 // Lookup failure.
765 result = factory()->InternalizeOneByteString(
766 seq_source_, position_, length);
767 break;
768 }
769 if (element != isolate()->heap()->the_hole_value() &&
770 String::cast(element)->IsOneByteEqualTo(string_vector)) {
771 result = Handle<String>(String::cast(element), isolate());
772#ifdef DEBUG
773 uint32_t hash_field =
774 (hash << String::kHashShift) | String::kIsNotArrayIndexMask;
775 DCHECK_EQ(static_cast<int>(result->Hash()),
776 static_cast<int>(hash_field >> String::kHashShift));
777#endif
778 break;
779 }
780 entry = StringTable::NextProbe(entry, count++, capacity);
781 }
782 position_ = position;
783 // Advance past the last '"'.
784 AdvanceSkipWhitespace();
785 return result;
786 }
787
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000788 int beg_pos = position_;
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000789 // Fast case for Latin1 only without escape characters.
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000790 do {
791 // Check for control character (0x00-0x1f) or unterminated string (<0).
792 if (c0_ < 0x20) return Handle<String>::null();
793 if (c0_ != '\\') {
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000794 if (seq_one_byte || c0_ <= String::kMaxOneByteCharCode) {
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000795 Advance();
796 } else {
797 return SlowScanJsonString<SeqTwoByteString, uc16>(source_,
798 beg_pos,
799 position_);
800 }
801 } else {
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000802 return SlowScanJsonString<SeqOneByteString, uint8_t>(source_,
803 beg_pos,
804 position_);
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000805 }
806 } while (c0_ != '"');
807 int length = position_ - beg_pos;
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000808 Handle<String> result =
809 factory()->NewRawOneByteString(length, pretenure_).ToHandleChecked();
810 uint8_t* dest = SeqOneByteString::cast(*result)->GetChars();
811 String::WriteToFlat(*source_, dest, beg_pos, position_);
812
813 DCHECK_EQ('"', c0_);
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000814 // Advance past the last '"'.
815 AdvanceSkipWhitespace();
816 return result;
817}
818
Ben Murdoch257744e2011-11-30 15:57:28 +0000819} } // namespace v8::internal
820
821#endif // V8_JSON_PARSER_H_