blob: f6b93b0773cfa15f92ab88b21466ab0314e0ae99 [file] [log] [blame]
Steve Blocka7e24c12009-10-30 11:49:00 +00001// Copyright 2006-2008 the V8 project authors. All rights reserved.
2// Redistribution and use in source and binary forms, with or without
3// modification, are permitted provided that the following conditions are
4// met:
5//
6// * Redistributions of source code must retain the above copyright
7// notice, this list of conditions and the following disclaimer.
8// * Redistributions in binary form must reproduce the above
9// copyright notice, this list of conditions and the following
10// disclaimer in the documentation and/or other materials provided
11// with the distribution.
12// * Neither the name of Google Inc. nor the names of its
13// contributors may be used to endorse or promote products derived
14// from this software without specific prior written permission.
15//
16// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
20// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27
28#include "v8.h"
29
30#include "api.h"
31#include "debug.h"
32#include "execution.h"
33#include "factory.h"
34#include "macro-assembler.h"
35
36namespace v8 {
37namespace internal {
38
39
40Handle<FixedArray> Factory::NewFixedArray(int size, PretenureFlag pretenure) {
41 ASSERT(0 <= size);
42 CALL_HEAP_FUNCTION(Heap::AllocateFixedArray(size, pretenure), FixedArray);
43}
44
45
Steve Block6ded16b2010-05-10 14:33:55 +010046Handle<FixedArray> Factory::NewFixedArrayWithHoles(int size,
47 PretenureFlag pretenure) {
Steve Blocka7e24c12009-10-30 11:49:00 +000048 ASSERT(0 <= size);
Steve Block6ded16b2010-05-10 14:33:55 +010049 CALL_HEAP_FUNCTION(Heap::AllocateFixedArrayWithHoles(size, pretenure),
50 FixedArray);
Steve Blocka7e24c12009-10-30 11:49:00 +000051}
52
53
54Handle<StringDictionary> Factory::NewStringDictionary(int at_least_space_for) {
55 ASSERT(0 <= at_least_space_for);
56 CALL_HEAP_FUNCTION(StringDictionary::Allocate(at_least_space_for),
57 StringDictionary);
58}
59
60
61Handle<NumberDictionary> Factory::NewNumberDictionary(int at_least_space_for) {
62 ASSERT(0 <= at_least_space_for);
63 CALL_HEAP_FUNCTION(NumberDictionary::Allocate(at_least_space_for),
64 NumberDictionary);
65}
66
67
68Handle<DescriptorArray> Factory::NewDescriptorArray(int number_of_descriptors) {
69 ASSERT(0 <= number_of_descriptors);
70 CALL_HEAP_FUNCTION(DescriptorArray::Allocate(number_of_descriptors),
71 DescriptorArray);
72}
73
74
75// Symbols are created in the old generation (data space).
76Handle<String> Factory::LookupSymbol(Vector<const char> string) {
77 CALL_HEAP_FUNCTION(Heap::LookupSymbol(string), String);
78}
79
80
81Handle<String> Factory::NewStringFromAscii(Vector<const char> string,
82 PretenureFlag pretenure) {
83 CALL_HEAP_FUNCTION(Heap::AllocateStringFromAscii(string, pretenure), String);
84}
85
86Handle<String> Factory::NewStringFromUtf8(Vector<const char> string,
87 PretenureFlag pretenure) {
88 CALL_HEAP_FUNCTION(Heap::AllocateStringFromUtf8(string, pretenure), String);
89}
90
91
92Handle<String> Factory::NewStringFromTwoByte(Vector<const uc16> string,
93 PretenureFlag pretenure) {
94 CALL_HEAP_FUNCTION(Heap::AllocateStringFromTwoByte(string, pretenure),
95 String);
96}
97
98
99Handle<String> Factory::NewRawTwoByteString(int length,
100 PretenureFlag pretenure) {
101 CALL_HEAP_FUNCTION(Heap::AllocateRawTwoByteString(length, pretenure), String);
102}
103
104
105Handle<String> Factory::NewConsString(Handle<String> first,
106 Handle<String> second) {
107 CALL_HEAP_FUNCTION(Heap::AllocateConsString(*first, *second), String);
108}
109
110
Steve Blockd0582a62009-12-15 09:54:21 +0000111Handle<String> Factory::NewSubString(Handle<String> str,
112 int begin,
113 int end) {
114 CALL_HEAP_FUNCTION(str->SubString(begin, end), String);
Steve Blocka7e24c12009-10-30 11:49:00 +0000115}
116
117
118Handle<String> Factory::NewExternalStringFromAscii(
119 ExternalAsciiString::Resource* resource) {
120 CALL_HEAP_FUNCTION(Heap::AllocateExternalStringFromAscii(resource), String);
121}
122
123
124Handle<String> Factory::NewExternalStringFromTwoByte(
125 ExternalTwoByteString::Resource* resource) {
126 CALL_HEAP_FUNCTION(Heap::AllocateExternalStringFromTwoByte(resource), String);
127}
128
129
130Handle<Context> Factory::NewGlobalContext() {
131 CALL_HEAP_FUNCTION(Heap::AllocateGlobalContext(), Context);
132}
133
134
135Handle<Context> Factory::NewFunctionContext(int length,
136 Handle<JSFunction> closure) {
137 CALL_HEAP_FUNCTION(Heap::AllocateFunctionContext(length, *closure), Context);
138}
139
140
141Handle<Context> Factory::NewWithContext(Handle<Context> previous,
142 Handle<JSObject> extension,
143 bool is_catch_context) {
144 CALL_HEAP_FUNCTION(Heap::AllocateWithContext(*previous,
145 *extension,
146 is_catch_context),
147 Context);
148}
149
150
151Handle<Struct> Factory::NewStruct(InstanceType type) {
152 CALL_HEAP_FUNCTION(Heap::AllocateStruct(type), Struct);
153}
154
155
156Handle<AccessorInfo> Factory::NewAccessorInfo() {
157 Handle<AccessorInfo> info =
158 Handle<AccessorInfo>::cast(NewStruct(ACCESSOR_INFO_TYPE));
159 info->set_flag(0); // Must clear the flag, it was initialized as undefined.
160 return info;
161}
162
163
164Handle<Script> Factory::NewScript(Handle<String> source) {
165 // Generate id for this script.
166 int id;
167 if (Heap::last_script_id()->IsUndefined()) {
168 // Script ids start from one.
169 id = 1;
170 } else {
171 // Increment id, wrap when positive smi is exhausted.
172 id = Smi::cast(Heap::last_script_id())->value();
173 id++;
174 if (!Smi::IsValid(id)) {
175 id = 0;
176 }
177 }
178 Heap::SetLastScriptId(Smi::FromInt(id));
179
180 // Create and initialize script object.
181 Handle<Proxy> wrapper = Factory::NewProxy(0, TENURED);
182 Handle<Script> script = Handle<Script>::cast(NewStruct(SCRIPT_TYPE));
183 script->set_source(*source);
184 script->set_name(Heap::undefined_value());
185 script->set_id(Heap::last_script_id());
186 script->set_line_offset(Smi::FromInt(0));
187 script->set_column_offset(Smi::FromInt(0));
188 script->set_data(Heap::undefined_value());
189 script->set_context_data(Heap::undefined_value());
190 script->set_type(Smi::FromInt(Script::TYPE_NORMAL));
191 script->set_compilation_type(Smi::FromInt(Script::COMPILATION_TYPE_HOST));
192 script->set_wrapper(*wrapper);
193 script->set_line_ends(Heap::undefined_value());
Steve Blockd0582a62009-12-15 09:54:21 +0000194 script->set_eval_from_shared(Heap::undefined_value());
Steve Blocka7e24c12009-10-30 11:49:00 +0000195 script->set_eval_from_instructions_offset(Smi::FromInt(0));
196
197 return script;
198}
199
200
201Handle<Proxy> Factory::NewProxy(Address addr, PretenureFlag pretenure) {
202 CALL_HEAP_FUNCTION(Heap::AllocateProxy(addr, pretenure), Proxy);
203}
204
205
206Handle<Proxy> Factory::NewProxy(const AccessorDescriptor* desc) {
207 return NewProxy((Address) desc, TENURED);
208}
209
210
211Handle<ByteArray> Factory::NewByteArray(int length, PretenureFlag pretenure) {
212 ASSERT(0 <= length);
213 CALL_HEAP_FUNCTION(Heap::AllocateByteArray(length, pretenure), ByteArray);
214}
215
216
217Handle<PixelArray> Factory::NewPixelArray(int length,
218 uint8_t* external_pointer,
219 PretenureFlag pretenure) {
220 ASSERT(0 <= length);
221 CALL_HEAP_FUNCTION(Heap::AllocatePixelArray(length,
222 external_pointer,
223 pretenure), PixelArray);
224}
225
226
Steve Block3ce2e202009-11-05 08:53:23 +0000227Handle<ExternalArray> Factory::NewExternalArray(int length,
228 ExternalArrayType array_type,
229 void* external_pointer,
230 PretenureFlag pretenure) {
231 ASSERT(0 <= length);
232 CALL_HEAP_FUNCTION(Heap::AllocateExternalArray(length,
233 array_type,
234 external_pointer,
235 pretenure), ExternalArray);
236}
237
238
Steve Blocka7e24c12009-10-30 11:49:00 +0000239Handle<Map> Factory::NewMap(InstanceType type, int instance_size) {
240 CALL_HEAP_FUNCTION(Heap::AllocateMap(type, instance_size), Map);
241}
242
243
244Handle<JSObject> Factory::NewFunctionPrototype(Handle<JSFunction> function) {
245 CALL_HEAP_FUNCTION(Heap::AllocateFunctionPrototype(*function), JSObject);
246}
247
248
249Handle<Map> Factory::CopyMapDropDescriptors(Handle<Map> src) {
250 CALL_HEAP_FUNCTION(src->CopyDropDescriptors(), Map);
251}
252
253
254Handle<Map> Factory::CopyMap(Handle<Map> src,
255 int extra_inobject_properties) {
256 Handle<Map> copy = CopyMapDropDescriptors(src);
257 // Check that we do not overflow the instance size when adding the
258 // extra inobject properties.
259 int instance_size_delta = extra_inobject_properties * kPointerSize;
260 int max_instance_size_delta =
261 JSObject::kMaxInstanceSize - copy->instance_size();
262 if (instance_size_delta > max_instance_size_delta) {
263 // If the instance size overflows, we allocate as many properties
264 // as we can as inobject properties.
265 instance_size_delta = max_instance_size_delta;
266 extra_inobject_properties = max_instance_size_delta >> kPointerSizeLog2;
267 }
268 // Adjust the map with the extra inobject properties.
269 int inobject_properties =
270 copy->inobject_properties() + extra_inobject_properties;
271 copy->set_inobject_properties(inobject_properties);
272 copy->set_unused_property_fields(inobject_properties);
273 copy->set_instance_size(copy->instance_size() + instance_size_delta);
274 return copy;
275}
276
Steve Block8defd9f2010-07-08 12:39:36 +0100277
Steve Blocka7e24c12009-10-30 11:49:00 +0000278Handle<Map> Factory::CopyMapDropTransitions(Handle<Map> src) {
279 CALL_HEAP_FUNCTION(src->CopyDropTransitions(), Map);
280}
281
282
Steve Block8defd9f2010-07-08 12:39:36 +0100283Handle<Map> Factory::GetFastElementsMap(Handle<Map> src) {
284 CALL_HEAP_FUNCTION(src->GetFastElementsMap(), Map);
285}
286
287
288Handle<Map> Factory::GetSlowElementsMap(Handle<Map> src) {
289 CALL_HEAP_FUNCTION(src->GetSlowElementsMap(), Map);
290}
291
292
Steve Blocka7e24c12009-10-30 11:49:00 +0000293Handle<FixedArray> Factory::CopyFixedArray(Handle<FixedArray> array) {
294 CALL_HEAP_FUNCTION(array->Copy(), FixedArray);
295}
296
297
Steve Block6ded16b2010-05-10 14:33:55 +0100298Handle<JSFunction> Factory::BaseNewFunctionFromSharedFunctionInfo(
299 Handle<SharedFunctionInfo> function_info,
Leon Clarkee46be812010-01-19 14:06:41 +0000300 Handle<Map> function_map,
301 PretenureFlag pretenure) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000302 CALL_HEAP_FUNCTION(Heap::AllocateFunction(*function_map,
Steve Block6ded16b2010-05-10 14:33:55 +0100303 *function_info,
Leon Clarkee46be812010-01-19 14:06:41 +0000304 Heap::the_hole_value(),
305 pretenure),
Steve Blocka7e24c12009-10-30 11:49:00 +0000306 JSFunction);
307}
308
309
Steve Block6ded16b2010-05-10 14:33:55 +0100310Handle<JSFunction> Factory::NewFunctionFromSharedFunctionInfo(
311 Handle<SharedFunctionInfo> function_info,
Leon Clarkee46be812010-01-19 14:06:41 +0000312 Handle<Context> context,
313 PretenureFlag pretenure) {
Steve Block6ded16b2010-05-10 14:33:55 +0100314 Handle<JSFunction> result = BaseNewFunctionFromSharedFunctionInfo(
315 function_info, Top::function_map(), pretenure);
Steve Blocka7e24c12009-10-30 11:49:00 +0000316 result->set_context(*context);
Steve Block6ded16b2010-05-10 14:33:55 +0100317 int number_of_literals = function_info->num_literals();
Steve Blocka7e24c12009-10-30 11:49:00 +0000318 Handle<FixedArray> literals =
Leon Clarkee46be812010-01-19 14:06:41 +0000319 Factory::NewFixedArray(number_of_literals, pretenure);
Steve Blocka7e24c12009-10-30 11:49:00 +0000320 if (number_of_literals > 0) {
321 // Store the object, regexp and array functions in the literals
322 // array prefix. These functions will be used when creating
323 // object, regexp and array literals in this function.
324 literals->set(JSFunction::kLiteralGlobalContextIndex,
325 context->global_context());
326 }
327 result->set_literals(*literals);
Steve Blocka7e24c12009-10-30 11:49:00 +0000328 return result;
329}
330
331
332Handle<Object> Factory::NewNumber(double value,
333 PretenureFlag pretenure) {
334 CALL_HEAP_FUNCTION(Heap::NumberFromDouble(value, pretenure), Object);
335}
336
337
338Handle<Object> Factory::NewNumberFromInt(int value) {
339 CALL_HEAP_FUNCTION(Heap::NumberFromInt32(value), Object);
340}
341
342
343Handle<Object> Factory::NewNumberFromUint(uint32_t value) {
344 CALL_HEAP_FUNCTION(Heap::NumberFromUint32(value), Object);
345}
346
347
348Handle<JSObject> Factory::NewNeanderObject() {
349 CALL_HEAP_FUNCTION(Heap::AllocateJSObjectFromMap(Heap::neander_map()),
350 JSObject);
351}
352
353
354Handle<Object> Factory::NewTypeError(const char* type,
355 Vector< Handle<Object> > args) {
356 return NewError("MakeTypeError", type, args);
357}
358
359
360Handle<Object> Factory::NewTypeError(Handle<String> message) {
361 return NewError("$TypeError", message);
362}
363
364
365Handle<Object> Factory::NewRangeError(const char* type,
366 Vector< Handle<Object> > args) {
367 return NewError("MakeRangeError", type, args);
368}
369
370
371Handle<Object> Factory::NewRangeError(Handle<String> message) {
372 return NewError("$RangeError", message);
373}
374
375
376Handle<Object> Factory::NewSyntaxError(const char* type, Handle<JSArray> args) {
377 return NewError("MakeSyntaxError", type, args);
378}
379
380
381Handle<Object> Factory::NewSyntaxError(Handle<String> message) {
382 return NewError("$SyntaxError", message);
383}
384
385
386Handle<Object> Factory::NewReferenceError(const char* type,
387 Vector< Handle<Object> > args) {
388 return NewError("MakeReferenceError", type, args);
389}
390
391
392Handle<Object> Factory::NewReferenceError(Handle<String> message) {
393 return NewError("$ReferenceError", message);
394}
395
396
397Handle<Object> Factory::NewError(const char* maker, const char* type,
398 Vector< Handle<Object> > args) {
399 v8::HandleScope scope; // Instantiate a closeable HandleScope for EscapeFrom.
400 Handle<FixedArray> array = Factory::NewFixedArray(args.length());
401 for (int i = 0; i < args.length(); i++) {
402 array->set(i, *args[i]);
403 }
404 Handle<JSArray> object = Factory::NewJSArrayWithElements(array);
405 Handle<Object> result = NewError(maker, type, object);
406 return result.EscapeFrom(&scope);
407}
408
409
410Handle<Object> Factory::NewEvalError(const char* type,
411 Vector< Handle<Object> > args) {
412 return NewError("MakeEvalError", type, args);
413}
414
415
416Handle<Object> Factory::NewError(const char* type,
417 Vector< Handle<Object> > args) {
418 return NewError("MakeError", type, args);
419}
420
421
422Handle<Object> Factory::NewError(const char* maker,
423 const char* type,
424 Handle<JSArray> args) {
425 Handle<String> make_str = Factory::LookupAsciiSymbol(maker);
426 Handle<Object> fun_obj(Top::builtins()->GetProperty(*make_str));
427 // If the builtins haven't been properly configured yet this error
428 // constructor may not have been defined. Bail out.
429 if (!fun_obj->IsJSFunction())
430 return Factory::undefined_value();
431 Handle<JSFunction> fun = Handle<JSFunction>::cast(fun_obj);
432 Handle<Object> type_obj = Factory::LookupAsciiSymbol(type);
433 Object** argv[2] = { type_obj.location(),
434 Handle<Object>::cast(args).location() };
435
436 // Invoke the JavaScript factory method. If an exception is thrown while
437 // running the factory method, use the exception as the result.
438 bool caught_exception;
439 Handle<Object> result = Execution::TryCall(fun,
440 Top::builtins(),
441 2,
442 argv,
443 &caught_exception);
444 return result;
445}
446
447
448Handle<Object> Factory::NewError(Handle<String> message) {
449 return NewError("$Error", message);
450}
451
452
453Handle<Object> Factory::NewError(const char* constructor,
454 Handle<String> message) {
455 Handle<String> constr = Factory::LookupAsciiSymbol(constructor);
456 Handle<JSFunction> fun =
457 Handle<JSFunction>(
458 JSFunction::cast(
459 Top::builtins()->GetProperty(*constr)));
460 Object** argv[1] = { Handle<Object>::cast(message).location() };
461
462 // Invoke the JavaScript factory method. If an exception is thrown while
463 // running the factory method, use the exception as the result.
464 bool caught_exception;
465 Handle<Object> result = Execution::TryCall(fun,
466 Top::builtins(),
467 1,
468 argv,
469 &caught_exception);
470 return result;
471}
472
473
474Handle<JSFunction> Factory::NewFunction(Handle<String> name,
475 InstanceType type,
476 int instance_size,
477 Handle<Code> code,
478 bool force_initial_map) {
479 // Allocate the function
480 Handle<JSFunction> function = NewFunction(name, the_hole_value());
481 function->set_code(*code);
482
483 if (force_initial_map ||
484 type != JS_OBJECT_TYPE ||
485 instance_size != JSObject::kHeaderSize) {
486 Handle<Map> initial_map = NewMap(type, instance_size);
487 Handle<JSObject> prototype = NewFunctionPrototype(function);
488 initial_map->set_prototype(*prototype);
489 function->set_initial_map(*initial_map);
490 initial_map->set_constructor(*function);
491 } else {
492 ASSERT(!function->has_initial_map());
493 ASSERT(!function->has_prototype());
494 }
495
496 return function;
497}
498
499
Steve Blocka7e24c12009-10-30 11:49:00 +0000500Handle<JSFunction> Factory::NewFunctionWithPrototype(Handle<String> name,
501 InstanceType type,
502 int instance_size,
503 Handle<JSObject> prototype,
504 Handle<Code> code,
505 bool force_initial_map) {
506 // Allocate the function
507 Handle<JSFunction> function = NewFunction(name, prototype);
508
509 function->set_code(*code);
510
511 if (force_initial_map ||
512 type != JS_OBJECT_TYPE ||
513 instance_size != JSObject::kHeaderSize) {
514 Handle<Map> initial_map = NewMap(type, instance_size);
515 function->set_initial_map(*initial_map);
516 initial_map->set_constructor(*function);
517 }
518
519 // Set function.prototype and give the prototype a constructor
520 // property that refers to the function.
521 SetPrototypeProperty(function, prototype);
522 SetProperty(prototype, Factory::constructor_symbol(), function, DONT_ENUM);
523 return function;
524}
525
526
Steve Block6ded16b2010-05-10 14:33:55 +0100527Handle<JSFunction> Factory::NewFunctionWithoutPrototype(Handle<String> name,
528 Handle<Code> code) {
529 Handle<JSFunction> function = NewFunctionWithoutPrototype(name);
530 function->set_code(*code);
531 ASSERT(!function->has_initial_map());
532 ASSERT(!function->has_prototype());
533 return function;
534}
535
536
Steve Blocka7e24c12009-10-30 11:49:00 +0000537Handle<Code> Factory::NewCode(const CodeDesc& desc,
538 ZoneScopeInfo* sinfo,
539 Code::Flags flags,
540 Handle<Object> self_ref) {
541 CALL_HEAP_FUNCTION(Heap::CreateCode(desc, sinfo, flags, self_ref), Code);
542}
543
544
545Handle<Code> Factory::CopyCode(Handle<Code> code) {
546 CALL_HEAP_FUNCTION(Heap::CopyCode(*code), Code);
547}
548
549
Steve Block6ded16b2010-05-10 14:33:55 +0100550Handle<Code> Factory::CopyCode(Handle<Code> code, Vector<byte> reloc_info) {
551 CALL_HEAP_FUNCTION(Heap::CopyCode(*code, reloc_info), Code);
552}
553
554
Steve Blocka7e24c12009-10-30 11:49:00 +0000555static inline Object* DoCopyInsert(DescriptorArray* array,
556 String* key,
557 Object* value,
558 PropertyAttributes attributes) {
559 CallbacksDescriptor desc(key, value, attributes);
560 Object* obj = array->CopyInsert(&desc, REMOVE_TRANSITIONS);
561 return obj;
562}
563
564
565// Allocate the new array.
566Handle<DescriptorArray> Factory::CopyAppendProxyDescriptor(
567 Handle<DescriptorArray> array,
568 Handle<String> key,
569 Handle<Object> value,
570 PropertyAttributes attributes) {
571 CALL_HEAP_FUNCTION(DoCopyInsert(*array, *key, *value, attributes),
572 DescriptorArray);
573}
574
575
576Handle<String> Factory::SymbolFromString(Handle<String> value) {
577 CALL_HEAP_FUNCTION(Heap::LookupSymbol(*value), String);
578}
579
580
581Handle<DescriptorArray> Factory::CopyAppendCallbackDescriptors(
582 Handle<DescriptorArray> array,
583 Handle<Object> descriptors) {
584 v8::NeanderArray callbacks(descriptors);
585 int nof_callbacks = callbacks.length();
586 Handle<DescriptorArray> result =
587 NewDescriptorArray(array->number_of_descriptors() + nof_callbacks);
588
589 // Number of descriptors added to the result so far.
590 int descriptor_count = 0;
591
592 // Copy the descriptors from the array.
593 for (int i = 0; i < array->number_of_descriptors(); i++) {
594 if (array->GetType(i) != NULL_DESCRIPTOR) {
595 result->CopyFrom(descriptor_count++, *array, i);
596 }
597 }
598
599 // Number of duplicates detected.
600 int duplicates = 0;
601
602 // Fill in new callback descriptors. Process the callbacks from
603 // back to front so that the last callback with a given name takes
604 // precedence over previously added callbacks with that name.
605 for (int i = nof_callbacks - 1; i >= 0; i--) {
606 Handle<AccessorInfo> entry =
607 Handle<AccessorInfo>(AccessorInfo::cast(callbacks.get(i)));
608 // Ensure the key is a symbol before writing into the instance descriptor.
609 Handle<String> key =
610 SymbolFromString(Handle<String>(String::cast(entry->name())));
611 // Check if a descriptor with this name already exists before writing.
612 if (result->LinearSearch(*key, descriptor_count) ==
613 DescriptorArray::kNotFound) {
614 CallbacksDescriptor desc(*key, *entry, entry->property_attributes());
615 result->Set(descriptor_count, &desc);
616 descriptor_count++;
617 } else {
618 duplicates++;
619 }
620 }
621
622 // If duplicates were detected, allocate a result of the right size
623 // and transfer the elements.
624 if (duplicates > 0) {
625 int number_of_descriptors = result->number_of_descriptors() - duplicates;
626 Handle<DescriptorArray> new_result =
627 NewDescriptorArray(number_of_descriptors);
628 for (int i = 0; i < number_of_descriptors; i++) {
629 new_result->CopyFrom(i, *result, i);
630 }
631 result = new_result;
632 }
633
634 // Sort the result before returning.
635 result->Sort();
636 return result;
637}
638
639
640Handle<JSObject> Factory::NewJSObject(Handle<JSFunction> constructor,
641 PretenureFlag pretenure) {
642 CALL_HEAP_FUNCTION(Heap::AllocateJSObject(*constructor, pretenure), JSObject);
643}
644
645
646Handle<GlobalObject> Factory::NewGlobalObject(
647 Handle<JSFunction> constructor) {
648 CALL_HEAP_FUNCTION(Heap::AllocateGlobalObject(*constructor),
649 GlobalObject);
650}
651
652
653
654Handle<JSObject> Factory::NewJSObjectFromMap(Handle<Map> map) {
655 CALL_HEAP_FUNCTION(Heap::AllocateJSObjectFromMap(*map, NOT_TENURED),
656 JSObject);
657}
658
659
660Handle<JSArray> Factory::NewJSArray(int length,
661 PretenureFlag pretenure) {
662 Handle<JSObject> obj = NewJSObject(Top::array_function(), pretenure);
663 CALL_HEAP_FUNCTION(Handle<JSArray>::cast(obj)->Initialize(length), JSArray);
664}
665
666
667Handle<JSArray> Factory::NewJSArrayWithElements(Handle<FixedArray> elements,
668 PretenureFlag pretenure) {
669 Handle<JSArray> result =
670 Handle<JSArray>::cast(NewJSObject(Top::array_function(), pretenure));
671 result->SetContent(*elements);
672 return result;
673}
674
675
Steve Block6ded16b2010-05-10 14:33:55 +0100676Handle<SharedFunctionInfo> Factory::NewSharedFunctionInfo(
677 Handle<String> name, int number_of_literals, Handle<Code> code) {
678 Handle<SharedFunctionInfo> shared = NewSharedFunctionInfo(name);
679 shared->set_code(*code);
680 int literals_array_size = number_of_literals;
681 // If the function contains object, regexp or array literals,
682 // allocate extra space for a literals array prefix containing the
683 // context.
684 if (number_of_literals > 0) {
685 literals_array_size += JSFunction::kLiteralsPrefixSize;
686 }
687 shared->set_num_literals(literals_array_size);
688 return shared;
689}
690
691
Steve Blocka7e24c12009-10-30 11:49:00 +0000692Handle<SharedFunctionInfo> Factory::NewSharedFunctionInfo(Handle<String> name) {
693 CALL_HEAP_FUNCTION(Heap::AllocateSharedFunctionInfo(*name),
694 SharedFunctionInfo);
695}
696
697
698Handle<String> Factory::NumberToString(Handle<Object> number) {
699 CALL_HEAP_FUNCTION(Heap::NumberToString(*number), String);
700}
701
702
703Handle<NumberDictionary> Factory::DictionaryAtNumberPut(
704 Handle<NumberDictionary> dictionary,
705 uint32_t key,
706 Handle<Object> value) {
707 CALL_HEAP_FUNCTION(dictionary->AtNumberPut(key, *value), NumberDictionary);
708}
709
710
711Handle<JSFunction> Factory::NewFunctionHelper(Handle<String> name,
712 Handle<Object> prototype) {
713 Handle<SharedFunctionInfo> function_share = NewSharedFunctionInfo(name);
714 CALL_HEAP_FUNCTION(Heap::AllocateFunction(*Top::function_map(),
715 *function_share,
716 *prototype),
717 JSFunction);
718}
719
720
721Handle<JSFunction> Factory::NewFunction(Handle<String> name,
722 Handle<Object> prototype) {
723 Handle<JSFunction> fun = NewFunctionHelper(name, prototype);
724 fun->set_context(Top::context()->global_context());
725 return fun;
726}
727
728
Steve Block6ded16b2010-05-10 14:33:55 +0100729Handle<JSFunction> Factory::NewFunctionWithoutPrototypeHelper(
730 Handle<String> name) {
731 Handle<SharedFunctionInfo> function_share = NewSharedFunctionInfo(name);
732 CALL_HEAP_FUNCTION(Heap::AllocateFunction(
733 *Top::function_without_prototype_map(),
734 *function_share,
735 *the_hole_value()),
736 JSFunction);
737}
738
739
740Handle<JSFunction> Factory::NewFunctionWithoutPrototype(Handle<String> name) {
741 Handle<JSFunction> fun = NewFunctionWithoutPrototypeHelper(name);
742 fun->set_context(Top::context()->global_context());
743 return fun;
744}
745
746
Leon Clarkee46be812010-01-19 14:06:41 +0000747Handle<Object> Factory::ToObject(Handle<Object> object) {
748 CALL_HEAP_FUNCTION(object->ToObject(), Object);
749}
750
751
Steve Blocka7e24c12009-10-30 11:49:00 +0000752Handle<Object> Factory::ToObject(Handle<Object> object,
753 Handle<Context> global_context) {
754 CALL_HEAP_FUNCTION(object->ToObject(*global_context), Object);
755}
756
757
758#ifdef ENABLE_DEBUGGER_SUPPORT
759Handle<DebugInfo> Factory::NewDebugInfo(Handle<SharedFunctionInfo> shared) {
760 // Get the original code of the function.
761 Handle<Code> code(shared->code());
762
763 // Create a copy of the code before allocating the debug info object to avoid
764 // allocation while setting up the debug info object.
765 Handle<Code> original_code(*Factory::CopyCode(code));
766
767 // Allocate initial fixed array for active break points before allocating the
768 // debug info object to avoid allocation while setting up the debug info
769 // object.
770 Handle<FixedArray> break_points(
771 Factory::NewFixedArray(Debug::kEstimatedNofBreakPointsInFunction));
772
773 // Create and set up the debug info object. Debug info contains function, a
774 // copy of the original code, the executing code and initial fixed array for
775 // active break points.
776 Handle<DebugInfo> debug_info =
777 Handle<DebugInfo>::cast(Factory::NewStruct(DEBUG_INFO_TYPE));
778 debug_info->set_shared(*shared);
779 debug_info->set_original_code(*original_code);
780 debug_info->set_code(*code);
781 debug_info->set_break_points(*break_points);
782
783 // Link debug info to function.
784 shared->set_debug_info(*debug_info);
785
786 return debug_info;
787}
788#endif
789
790
791Handle<JSObject> Factory::NewArgumentsObject(Handle<Object> callee,
792 int length) {
793 CALL_HEAP_FUNCTION(Heap::AllocateArgumentsObject(*callee, length), JSObject);
794}
795
796
797Handle<JSFunction> Factory::CreateApiFunction(
798 Handle<FunctionTemplateInfo> obj, ApiInstanceType instance_type) {
799 Handle<Code> code = Handle<Code>(Builtins::builtin(Builtins::HandleApiCall));
Leon Clarkee46be812010-01-19 14:06:41 +0000800 Handle<Code> construct_stub =
801 Handle<Code>(Builtins::builtin(Builtins::JSConstructStubApi));
Steve Blocka7e24c12009-10-30 11:49:00 +0000802
803 int internal_field_count = 0;
804 if (!obj->instance_template()->IsUndefined()) {
805 Handle<ObjectTemplateInfo> instance_template =
806 Handle<ObjectTemplateInfo>(
807 ObjectTemplateInfo::cast(obj->instance_template()));
808 internal_field_count =
809 Smi::cast(instance_template->internal_field_count())->value();
810 }
811
812 int instance_size = kPointerSize * internal_field_count;
813 InstanceType type = INVALID_TYPE;
814 switch (instance_type) {
815 case JavaScriptObject:
816 type = JS_OBJECT_TYPE;
817 instance_size += JSObject::kHeaderSize;
818 break;
819 case InnerGlobalObject:
820 type = JS_GLOBAL_OBJECT_TYPE;
821 instance_size += JSGlobalObject::kSize;
822 break;
823 case OuterGlobalObject:
824 type = JS_GLOBAL_PROXY_TYPE;
825 instance_size += JSGlobalProxy::kSize;
826 break;
827 default:
828 break;
829 }
830 ASSERT(type != INVALID_TYPE);
831
832 Handle<JSFunction> result =
833 Factory::NewFunction(Factory::empty_symbol(),
834 type,
835 instance_size,
836 code,
837 true);
838 // Set class name.
839 Handle<Object> class_name = Handle<Object>(obj->class_name());
840 if (class_name->IsString()) {
841 result->shared()->set_instance_class_name(*class_name);
842 result->shared()->set_name(*class_name);
843 }
844
845 Handle<Map> map = Handle<Map>(result->initial_map());
846
847 // Mark as undetectable if needed.
848 if (obj->undetectable()) {
849 map->set_is_undetectable();
850 }
851
852 // Mark as hidden for the __proto__ accessor if needed.
853 if (obj->hidden_prototype()) {
854 map->set_is_hidden_prototype();
855 }
856
857 // Mark as needs_access_check if needed.
858 if (obj->needs_access_check()) {
859 map->set_is_access_check_needed(true);
860 }
861
862 // Set interceptor information in the map.
863 if (!obj->named_property_handler()->IsUndefined()) {
864 map->set_has_named_interceptor();
865 }
866 if (!obj->indexed_property_handler()->IsUndefined()) {
867 map->set_has_indexed_interceptor();
868 }
869
870 // Set instance call-as-function information in the map.
871 if (!obj->instance_call_handler()->IsUndefined()) {
872 map->set_has_instance_call_handler();
873 }
874
875 result->shared()->set_function_data(*obj);
Leon Clarkee46be812010-01-19 14:06:41 +0000876 result->shared()->set_construct_stub(*construct_stub);
Steve Blocka7e24c12009-10-30 11:49:00 +0000877 result->shared()->DontAdaptArguments();
878
879 // Recursively copy parent templates' accessors, 'data' may be modified.
880 Handle<DescriptorArray> array =
881 Handle<DescriptorArray>(map->instance_descriptors());
882 while (true) {
883 Handle<Object> props = Handle<Object>(obj->property_accessors());
884 if (!props->IsUndefined()) {
885 array = Factory::CopyAppendCallbackDescriptors(array, props);
886 }
887 Handle<Object> parent = Handle<Object>(obj->parent_template());
888 if (parent->IsUndefined()) break;
889 obj = Handle<FunctionTemplateInfo>::cast(parent);
890 }
891 if (!array->IsEmpty()) {
892 map->set_instance_descriptors(*array);
893 }
894
Steve Block6ded16b2010-05-10 14:33:55 +0100895 ASSERT(result->shared()->IsApiFunction());
Steve Blocka7e24c12009-10-30 11:49:00 +0000896 return result;
897}
898
899
900Handle<MapCache> Factory::NewMapCache(int at_least_space_for) {
901 CALL_HEAP_FUNCTION(MapCache::Allocate(at_least_space_for), MapCache);
902}
903
904
905static Object* UpdateMapCacheWith(Context* context,
906 FixedArray* keys,
907 Map* map) {
908 Object* result = MapCache::cast(context->map_cache())->Put(keys, map);
909 if (!result->IsFailure()) context->set_map_cache(MapCache::cast(result));
910 return result;
911}
912
913
914Handle<MapCache> Factory::AddToMapCache(Handle<Context> context,
915 Handle<FixedArray> keys,
916 Handle<Map> map) {
917 CALL_HEAP_FUNCTION(UpdateMapCacheWith(*context, *keys, *map), MapCache);
918}
919
920
921Handle<Map> Factory::ObjectLiteralMapFromCache(Handle<Context> context,
922 Handle<FixedArray> keys) {
923 if (context->map_cache()->IsUndefined()) {
924 // Allocate the new map cache for the global context.
925 Handle<MapCache> new_cache = NewMapCache(24);
926 context->set_map_cache(*new_cache);
927 }
928 // Check to see whether there is a matching element in the cache.
929 Handle<MapCache> cache =
930 Handle<MapCache>(MapCache::cast(context->map_cache()));
931 Handle<Object> result = Handle<Object>(cache->Lookup(*keys));
932 if (result->IsMap()) return Handle<Map>::cast(result);
933 // Create a new map and add it to the cache.
934 Handle<Map> map =
935 CopyMap(Handle<Map>(context->object_function()->initial_map()),
936 keys->length());
937 AddToMapCache(context, keys, map);
938 return Handle<Map>(map);
939}
940
941
942void Factory::SetRegExpAtomData(Handle<JSRegExp> regexp,
943 JSRegExp::Type type,
944 Handle<String> source,
945 JSRegExp::Flags flags,
946 Handle<Object> data) {
947 Handle<FixedArray> store = NewFixedArray(JSRegExp::kAtomDataSize);
948
949 store->set(JSRegExp::kTagIndex, Smi::FromInt(type));
950 store->set(JSRegExp::kSourceIndex, *source);
951 store->set(JSRegExp::kFlagsIndex, Smi::FromInt(flags.value()));
952 store->set(JSRegExp::kAtomPatternIndex, *data);
953 regexp->set_data(*store);
954}
955
956void Factory::SetRegExpIrregexpData(Handle<JSRegExp> regexp,
957 JSRegExp::Type type,
958 Handle<String> source,
959 JSRegExp::Flags flags,
960 int capture_count) {
961 Handle<FixedArray> store = NewFixedArray(JSRegExp::kIrregexpDataSize);
962
963 store->set(JSRegExp::kTagIndex, Smi::FromInt(type));
964 store->set(JSRegExp::kSourceIndex, *source);
965 store->set(JSRegExp::kFlagsIndex, Smi::FromInt(flags.value()));
966 store->set(JSRegExp::kIrregexpASCIICodeIndex, Heap::the_hole_value());
967 store->set(JSRegExp::kIrregexpUC16CodeIndex, Heap::the_hole_value());
968 store->set(JSRegExp::kIrregexpMaxRegisterCountIndex, Smi::FromInt(0));
969 store->set(JSRegExp::kIrregexpCaptureCountIndex,
970 Smi::FromInt(capture_count));
971 regexp->set_data(*store);
972}
973
974
975
976void Factory::ConfigureInstance(Handle<FunctionTemplateInfo> desc,
977 Handle<JSObject> instance,
978 bool* pending_exception) {
979 // Configure the instance by adding the properties specified by the
980 // instance template.
981 Handle<Object> instance_template = Handle<Object>(desc->instance_template());
982 if (!instance_template->IsUndefined()) {
983 Execution::ConfigureInstance(instance,
984 instance_template,
985 pending_exception);
986 } else {
987 *pending_exception = false;
988 }
989}
990
991
992} } // namespace v8::internal