1 // Copyright 2012 the V8 project authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #ifndef V8_JSON_STRINGIFIER_H_
6 #define V8_JSON_STRINGIFIER_H_
8 #include "src/conversions.h"
9 #include "src/lookup.h"
10 #include "src/messages.h"
11 #include "src/string-builder.h"
12 #include "src/utils.h"
17 class BasicJsonStringifier BASE_EMBEDDED {
19 explicit BasicJsonStringifier(Isolate* isolate);
21 MUST_USE_RESULT MaybeHandle<Object> Stringify(Handle<Object> object);
23 MUST_USE_RESULT INLINE(static MaybeHandle<Object> StringifyString(
25 Handle<String> object));
28 enum Result { UNCHANGED, SUCCESS, EXCEPTION };
30 MUST_USE_RESULT MaybeHandle<Object> ApplyToJsonFunction(
31 Handle<Object> object,
34 Result SerializeGeneric(Handle<Object> object,
39 // Entry point to serialize the object.
40 INLINE(Result SerializeObject(Handle<Object> obj)) {
41 return Serialize_<false>(obj, false, factory()->empty_string());
44 // Serialize an array element.
45 // The index may serve as argument for the toJSON function.
46 INLINE(Result SerializeElement(Isolate* isolate,
47 Handle<Object> object,
49 return Serialize_<false>(object,
51 Handle<Object>(Smi::FromInt(i), isolate));
54 // Serialize a object property.
55 // The key may or may not be serialized depending on the property.
56 // The key may also serve as argument for the toJSON function.
57 INLINE(Result SerializeProperty(Handle<Object> object,
59 Handle<String> deferred_key)) {
60 DCHECK(!deferred_key.is_null());
61 return Serialize_<true>(object, deferred_comma, deferred_key);
64 template <bool deferred_string_key>
65 Result Serialize_(Handle<Object> object, bool comma, Handle<Object> key);
67 void SerializeDeferredKey(bool deferred_comma, Handle<Object> deferred_key) {
68 if (deferred_comma) builder_.AppendCharacter(',');
69 SerializeString(Handle<String>::cast(deferred_key));
70 builder_.AppendCharacter(':');
73 Result SerializeSmi(Smi* object);
75 Result SerializeDouble(double number);
76 INLINE(Result SerializeHeapNumber(Handle<HeapNumber> object)) {
77 return SerializeDouble(object->value());
80 Result SerializeJSValue(Handle<JSValue> object);
82 INLINE(Result SerializeJSArray(Handle<JSArray> object));
83 INLINE(Result SerializeJSObject(Handle<JSObject> object));
85 Result SerializeJSArraySlow(Handle<JSArray> object, uint32_t length);
87 void SerializeString(Handle<String> object);
89 template <typename SrcChar, typename DestChar>
90 INLINE(static void SerializeStringUnchecked_(
91 Vector<const SrcChar> src,
92 IncrementalStringBuilder::NoExtend<DestChar>* dest));
94 template <typename SrcChar, typename DestChar>
95 INLINE(void SerializeString_(Handle<String> string));
97 template <typename Char>
98 INLINE(static bool DoNotEscape(Char c));
100 Result StackPush(Handle<Object> object);
103 Factory* factory() { return isolate_->factory(); }
106 IncrementalStringBuilder builder_;
107 Handle<String> tojson_string_;
108 Handle<JSArray> stack_;
110 static const int kJsonEscapeTableEntrySize = 8;
111 static const char* const JsonEscapeTable;
115 // Translation table to escape Latin1 characters.
116 // Table entries start at a multiple of 8 and are null-terminated.
117 const char* const BasicJsonStringifier::JsonEscapeTable =
118 "\\u0000\0 \\u0001\0 \\u0002\0 \\u0003\0 "
119 "\\u0004\0 \\u0005\0 \\u0006\0 \\u0007\0 "
120 "\\b\0 \\t\0 \\n\0 \\u000b\0 "
121 "\\f\0 \\r\0 \\u000e\0 \\u000f\0 "
122 "\\u0010\0 \\u0011\0 \\u0012\0 \\u0013\0 "
123 "\\u0014\0 \\u0015\0 \\u0016\0 \\u0017\0 "
124 "\\u0018\0 \\u0019\0 \\u001a\0 \\u001b\0 "
125 "\\u001c\0 \\u001d\0 \\u001e\0 \\u001f\0 "
126 " \0 !\0 \\\"\0 #\0 "
141 "\\\\\0 ]\0 ^\0 _\0 "
149 "|\0 }\0 ~\0 \177\0 "
150 "\200\0 \201\0 \202\0 \203\0 "
151 "\204\0 \205\0 \206\0 \207\0 "
152 "\210\0 \211\0 \212\0 \213\0 "
153 "\214\0 \215\0 \216\0 \217\0 "
154 "\220\0 \221\0 \222\0 \223\0 "
155 "\224\0 \225\0 \226\0 \227\0 "
156 "\230\0 \231\0 \232\0 \233\0 "
157 "\234\0 \235\0 \236\0 \237\0 "
158 "\240\0 \241\0 \242\0 \243\0 "
159 "\244\0 \245\0 \246\0 \247\0 "
160 "\250\0 \251\0 \252\0 \253\0 "
161 "\254\0 \255\0 \256\0 \257\0 "
162 "\260\0 \261\0 \262\0 \263\0 "
163 "\264\0 \265\0 \266\0 \267\0 "
164 "\270\0 \271\0 \272\0 \273\0 "
165 "\274\0 \275\0 \276\0 \277\0 "
166 "\300\0 \301\0 \302\0 \303\0 "
167 "\304\0 \305\0 \306\0 \307\0 "
168 "\310\0 \311\0 \312\0 \313\0 "
169 "\314\0 \315\0 \316\0 \317\0 "
170 "\320\0 \321\0 \322\0 \323\0 "
171 "\324\0 \325\0 \326\0 \327\0 "
172 "\330\0 \331\0 \332\0 \333\0 "
173 "\334\0 \335\0 \336\0 \337\0 "
174 "\340\0 \341\0 \342\0 \343\0 "
175 "\344\0 \345\0 \346\0 \347\0 "
176 "\350\0 \351\0 \352\0 \353\0 "
177 "\354\0 \355\0 \356\0 \357\0 "
178 "\360\0 \361\0 \362\0 \363\0 "
179 "\364\0 \365\0 \366\0 \367\0 "
180 "\370\0 \371\0 \372\0 \373\0 "
181 "\374\0 \375\0 \376\0 \377\0 ";
184 BasicJsonStringifier::BasicJsonStringifier(Isolate* isolate)
185 : isolate_(isolate), builder_(isolate) {
186 tojson_string_ = factory()->toJSON_string();
187 stack_ = factory()->NewJSArray(8);
191 MaybeHandle<Object> BasicJsonStringifier::Stringify(Handle<Object> object) {
192 Result result = SerializeObject(object);
193 if (result == UNCHANGED) return factory()->undefined_value();
194 if (result == SUCCESS) return builder_.Finish();
195 DCHECK(result == EXCEPTION);
196 return MaybeHandle<Object>();
200 MaybeHandle<Object> BasicJsonStringifier::StringifyString(
201 Isolate* isolate, Handle<String> object) {
202 static const int kJsonQuoteWorstCaseBlowup = 6;
203 static const int kSpaceForQuotes = 2;
204 int worst_case_length =
205 object->length() * kJsonQuoteWorstCaseBlowup + kSpaceForQuotes;
207 if (worst_case_length > 32 * KB) { // Slow path if too large.
208 BasicJsonStringifier stringifier(isolate);
209 return stringifier.Stringify(object);
212 object = String::Flatten(object);
213 DCHECK(object->IsFlat());
214 Handle<SeqString> result;
215 if (object->IsOneByteRepresentationUnderneath()) {
216 result = isolate->factory()
217 ->NewRawOneByteString(worst_case_length)
219 IncrementalStringBuilder::NoExtendString<uint8_t> no_extend(
220 result, worst_case_length);
221 no_extend.Append('\"');
222 SerializeStringUnchecked_(object->GetFlatContent().ToOneByteVector(),
224 no_extend.Append('\"');
226 result = isolate->factory()
227 ->NewRawTwoByteString(worst_case_length)
229 IncrementalStringBuilder::NoExtendString<uc16> no_extend(result,
231 no_extend.Append('\"');
232 SerializeStringUnchecked_(object->GetFlatContent().ToUC16Vector(),
234 no_extend.Append('\"');
240 MaybeHandle<Object> BasicJsonStringifier::ApplyToJsonFunction(
241 Handle<Object> object, Handle<Object> key) {
242 LookupIterator it(object, tojson_string_,
243 LookupIterator::PROTOTYPE_CHAIN_SKIP_INTERCEPTOR);
245 ASSIGN_RETURN_ON_EXCEPTION(isolate_, fun, Object::GetProperty(&it), Object);
246 if (!fun->IsJSFunction()) return object;
248 // Call toJSON function.
249 if (key->IsSmi()) key = factory()->NumberToString(key);
250 Handle<Object> argv[] = { key };
251 HandleScope scope(isolate_);
252 ASSIGN_RETURN_ON_EXCEPTION(
254 Execution::Call(isolate_, fun, object, 1, argv),
256 return scope.CloseAndEscape(object);
260 BasicJsonStringifier::Result BasicJsonStringifier::StackPush(
261 Handle<Object> object) {
262 StackLimitCheck check(isolate_);
263 if (check.HasOverflowed()) {
264 isolate_->StackOverflow();
268 int length = Smi::cast(stack_->length())->value();
270 DisallowHeapAllocation no_allocation;
271 FixedArray* elements = FixedArray::cast(stack_->elements());
272 for (int i = 0; i < length; i++) {
273 if (elements->get(i) == *object) {
274 AllowHeapAllocation allow_to_return_error;
275 Handle<Object> error =
276 factory()->NewTypeError(MessageTemplate::kCircularStructure);
277 isolate_->Throw(*error);
282 JSArray::SetLength(stack_, length + 1);
283 FixedArray::cast(stack_->elements())->set(length, *object);
288 void BasicJsonStringifier::StackPop() {
289 int length = Smi::cast(stack_->length())->value();
290 stack_->set_length(Smi::FromInt(length - 1));
294 template <bool deferred_string_key>
295 BasicJsonStringifier::Result BasicJsonStringifier::Serialize_(
296 Handle<Object> object, bool comma, Handle<Object> key) {
297 if (object->IsJSObject()) {
298 ASSIGN_RETURN_ON_EXCEPTION_VALUE(
300 ApplyToJsonFunction(object, key),
304 if (object->IsSmi()) {
305 if (deferred_string_key) SerializeDeferredKey(comma, key);
306 return SerializeSmi(Smi::cast(*object));
309 switch (HeapObject::cast(*object)->map()->instance_type()) {
310 case HEAP_NUMBER_TYPE:
311 case MUTABLE_HEAP_NUMBER_TYPE:
312 if (deferred_string_key) SerializeDeferredKey(comma, key);
313 return SerializeHeapNumber(Handle<HeapNumber>::cast(object));
315 switch (Oddball::cast(*object)->kind()) {
316 case Oddball::kFalse:
317 if (deferred_string_key) SerializeDeferredKey(comma, key);
318 builder_.AppendCString("false");
321 if (deferred_string_key) SerializeDeferredKey(comma, key);
322 builder_.AppendCString("true");
325 if (deferred_string_key) SerializeDeferredKey(comma, key);
326 builder_.AppendCString("null");
332 if (object->IsAccessCheckNeeded()) break;
333 if (deferred_string_key) SerializeDeferredKey(comma, key);
334 return SerializeJSArray(Handle<JSArray>::cast(object));
336 if (deferred_string_key) SerializeDeferredKey(comma, key);
337 return SerializeJSValue(Handle<JSValue>::cast(object));
338 case JS_FUNCTION_TYPE:
341 if (object->IsString()) {
342 if (deferred_string_key) SerializeDeferredKey(comma, key);
343 SerializeString(Handle<String>::cast(object));
345 } else if (object->IsJSObject()) {
346 // Go to slow path for global proxy and objects requiring access checks.
347 if (object->IsAccessCheckNeeded() || object->IsJSGlobalProxy()) break;
348 if (deferred_string_key) SerializeDeferredKey(comma, key);
349 return SerializeJSObject(Handle<JSObject>::cast(object));
353 return SerializeGeneric(object, key, comma, deferred_string_key);
357 BasicJsonStringifier::Result BasicJsonStringifier::SerializeGeneric(
358 Handle<Object> object,
362 Handle<JSFunction> fun = isolate_->json_serialize_adapter();
363 Handle<Object> argv[] = { key, object };
364 Handle<Object> result;
365 ASSIGN_RETURN_ON_EXCEPTION_VALUE(
366 isolate_, result, Execution::Call(isolate_, fun, object, 2, argv),
368 if (result->IsUndefined()) return UNCHANGED;
370 if (key->IsSmi()) key = factory()->NumberToString(key);
371 SerializeDeferredKey(deferred_comma, key);
374 builder_.AppendString(Handle<String>::cast(result));
379 BasicJsonStringifier::Result BasicJsonStringifier::SerializeJSValue(
380 Handle<JSValue> object) {
381 String* class_name = object->class_name();
382 if (class_name == isolate_->heap()->String_string()) {
383 Handle<Object> value;
384 ASSIGN_RETURN_ON_EXCEPTION_VALUE(
385 isolate_, value, Execution::ToString(isolate_, object), EXCEPTION);
386 SerializeString(Handle<String>::cast(value));
387 } else if (class_name == isolate_->heap()->Number_string()) {
388 Handle<Object> value;
389 ASSIGN_RETURN_ON_EXCEPTION_VALUE(
390 isolate_, value, Execution::ToNumber(isolate_, object), EXCEPTION);
391 if (value->IsSmi()) return SerializeSmi(Smi::cast(*value));
392 SerializeHeapNumber(Handle<HeapNumber>::cast(value));
393 } else if (class_name == isolate_->heap()->Boolean_string()) {
394 Object* value = JSValue::cast(*object)->value();
395 DCHECK(value->IsBoolean());
396 builder_.AppendCString(value->IsTrue() ? "true" : "false");
398 // Fail gracefully for special value wrappers.
399 isolate_->ThrowIllegalOperation();
406 BasicJsonStringifier::Result BasicJsonStringifier::SerializeSmi(Smi* object) {
407 static const int kBufferSize = 100;
408 char chars[kBufferSize];
409 Vector<char> buffer(chars, kBufferSize);
410 builder_.AppendCString(IntToCString(object->value(), buffer));
415 BasicJsonStringifier::Result BasicJsonStringifier::SerializeDouble(
417 if (std::isinf(number) || std::isnan(number)) {
418 builder_.AppendCString("null");
421 static const int kBufferSize = 100;
422 char chars[kBufferSize];
423 Vector<char> buffer(chars, kBufferSize);
424 builder_.AppendCString(DoubleToCString(number, buffer));
429 BasicJsonStringifier::Result BasicJsonStringifier::SerializeJSArray(
430 Handle<JSArray> object) {
431 HandleScope handle_scope(isolate_);
432 Result stack_push = StackPush(object);
433 if (stack_push != SUCCESS) return stack_push;
435 CHECK(object->length()->ToArrayLength(&length));
436 builder_.AppendCharacter('[');
437 switch (object->GetElementsKind()) {
438 case FAST_SMI_ELEMENTS: {
439 Handle<FixedArray> elements(
440 FixedArray::cast(object->elements()), isolate_);
441 for (uint32_t i = 0; i < length; i++) {
442 if (i > 0) builder_.AppendCharacter(',');
443 SerializeSmi(Smi::cast(elements->get(i)));
447 case FAST_DOUBLE_ELEMENTS: {
448 // Empty array is FixedArray but not FixedDoubleArray.
449 if (length == 0) break;
450 Handle<FixedDoubleArray> elements(
451 FixedDoubleArray::cast(object->elements()), isolate_);
452 for (uint32_t i = 0; i < length; i++) {
453 if (i > 0) builder_.AppendCharacter(',');
454 SerializeDouble(elements->get_scalar(i));
458 case FAST_ELEMENTS: {
459 Handle<FixedArray> elements(
460 FixedArray::cast(object->elements()), isolate_);
461 for (uint32_t i = 0; i < length; i++) {
462 if (i > 0) builder_.AppendCharacter(',');
464 SerializeElement(isolate_,
465 Handle<Object>(elements->get(i), isolate_),
467 if (result == SUCCESS) continue;
468 if (result == UNCHANGED) {
469 builder_.AppendCString("null");
476 // TODO(yangguo): The FAST_HOLEY_* cases could be handled in a faster way.
477 // They resemble the non-holey cases except that a prototype chain lookup
478 // is necessary for holes.
480 Result result = SerializeJSArraySlow(object, length);
481 if (result != SUCCESS) return result;
485 builder_.AppendCharacter(']');
491 BasicJsonStringifier::Result BasicJsonStringifier::SerializeJSArraySlow(
492 Handle<JSArray> object, uint32_t length) {
493 for (uint32_t i = 0; i < length; i++) {
494 if (i > 0) builder_.AppendCharacter(',');
495 Handle<Object> element;
496 ASSIGN_RETURN_ON_EXCEPTION_VALUE(
498 Object::GetElement(isolate_, object, i),
500 if (element->IsUndefined()) {
501 builder_.AppendCString("null");
503 Result result = SerializeElement(isolate_, element, i);
504 if (result == SUCCESS) continue;
505 if (result == UNCHANGED) {
506 builder_.AppendCString("null");
516 BasicJsonStringifier::Result BasicJsonStringifier::SerializeJSObject(
517 Handle<JSObject> object) {
518 HandleScope handle_scope(isolate_);
519 Result stack_push = StackPush(object);
520 if (stack_push != SUCCESS) return stack_push;
521 DCHECK(!object->IsJSGlobalProxy() && !object->IsGlobalObject());
523 builder_.AppendCharacter('{');
526 if (object->HasFastProperties() &&
527 !object->HasIndexedInterceptor() &&
528 !object->HasNamedInterceptor() &&
529 object->elements()->length() == 0) {
530 Handle<Map> map(object->map());
531 for (int i = 0; i < map->NumberOfOwnDescriptors(); i++) {
532 Handle<Name> name(map->instance_descriptors()->GetKey(i), isolate_);
533 // TODO(rossberg): Should this throw?
534 if (!name->IsString()) continue;
535 Handle<String> key = Handle<String>::cast(name);
536 PropertyDetails details = map->instance_descriptors()->GetDetails(i);
537 if (details.IsDontEnum()) continue;
538 Handle<Object> property;
539 if (details.type() == DATA && *map == object->map()) {
540 FieldIndex field_index = FieldIndex::ForDescriptor(*map, i);
541 Isolate* isolate = object->GetIsolate();
542 if (object->IsUnboxedDoubleField(field_index)) {
543 double value = object->RawFastDoublePropertyAt(field_index);
544 property = isolate->factory()->NewHeapNumber(value);
547 property = handle(object->RawFastPropertyAt(field_index), isolate);
550 ASSIGN_RETURN_ON_EXCEPTION_VALUE(
552 Object::GetPropertyOrElement(object, key),
555 Result result = SerializeProperty(property, comma, key);
556 if (!comma && result == SUCCESS) comma = true;
557 if (result == EXCEPTION) return result;
560 Handle<FixedArray> contents;
561 ASSIGN_RETURN_ON_EXCEPTION_VALUE(
563 JSReceiver::GetKeys(object, JSReceiver::OWN_ONLY),
566 for (int i = 0; i < contents->length(); i++) {
567 Object* key = contents->get(i);
568 Handle<String> key_handle;
569 MaybeHandle<Object> maybe_property;
570 if (key->IsString()) {
571 key_handle = Handle<String>(String::cast(key), isolate_);
572 maybe_property = Object::GetPropertyOrElement(object, key_handle);
574 DCHECK(key->IsNumber());
575 key_handle = factory()->NumberToString(Handle<Object>(key, isolate_));
577 maybe_property = Object::GetElement(
578 isolate_, object, Smi::cast(key)->value());
580 maybe_property = Object::GetPropertyOrElement(object, key_handle);
583 Handle<Object> property;
584 ASSIGN_RETURN_ON_EXCEPTION_VALUE(
585 isolate_, property, maybe_property, EXCEPTION);
586 Result result = SerializeProperty(property, comma, key_handle);
587 if (!comma && result == SUCCESS) comma = true;
588 if (result == EXCEPTION) return result;
592 builder_.AppendCharacter('}');
598 template <typename SrcChar, typename DestChar>
599 void BasicJsonStringifier::SerializeStringUnchecked_(
600 Vector<const SrcChar> src,
601 IncrementalStringBuilder::NoExtend<DestChar>* dest) {
602 // Assert that uc16 character is not truncated down to 8 bit.
603 // The <uc16, char> version of this method must not be called.
604 DCHECK(sizeof(DestChar) >= sizeof(SrcChar));
606 for (int i = 0; i < src.length(); i++) {
608 if (DoNotEscape(c)) {
611 dest->AppendCString(&JsonEscapeTable[c * kJsonEscapeTableEntrySize]);
617 template <typename SrcChar, typename DestChar>
618 void BasicJsonStringifier::SerializeString_(Handle<String> string) {
619 int length = string->length();
620 builder_.Append<uint8_t, DestChar>('"');
621 // We make a rough estimate to find out if the current string can be
622 // serialized without allocating a new string part. The worst case length of
623 // an escaped character is 6. Shifting the remainin string length right by 3
624 // is a more pessimistic estimate, but faster to calculate.
625 int worst_case_length = length << 3;
626 if (builder_.CurrentPartCanFit(worst_case_length)) {
627 DisallowHeapAllocation no_gc;
628 Vector<const SrcChar> vector = string->GetCharVector<SrcChar>();
629 IncrementalStringBuilder::NoExtendBuilder<DestChar> no_extend(
630 &builder_, worst_case_length);
631 SerializeStringUnchecked_(vector, &no_extend);
633 FlatStringReader reader(isolate_, string);
634 for (int i = 0; i < reader.length(); i++) {
635 SrcChar c = reader.Get<SrcChar>(i);
636 if (DoNotEscape(c)) {
637 builder_.Append<SrcChar, DestChar>(c);
639 builder_.AppendCString(&JsonEscapeTable[c * kJsonEscapeTableEntrySize]);
644 builder_.Append<uint8_t, DestChar>('"');
649 bool BasicJsonStringifier::DoNotEscape(uint8_t c) {
650 return c >= '#' && c <= '~' && c != '\\';
655 bool BasicJsonStringifier::DoNotEscape(uint16_t c) {
656 return c >= '#' && c != '\\' && c != 0x7f;
660 void BasicJsonStringifier::SerializeString(Handle<String> object) {
661 object = String::Flatten(object);
662 if (builder_.CurrentEncoding() == String::ONE_BYTE_ENCODING) {
663 if (object->IsOneByteRepresentationUnderneath()) {
664 SerializeString_<uint8_t, uint8_t>(object);
666 builder_.ChangeEncoding();
667 SerializeString(object);
670 if (object->IsOneByteRepresentationUnderneath()) {
671 SerializeString_<uint8_t, uc16>(object);
673 SerializeString_<uc16, uc16>(object);
678 } } // namespace v8::internal
680 #endif // V8_JSON_STRINGIFIER_H_