[es6] Implement spec compliant ToPrimitive in the runtime.
[platform/upstream/v8.git] / src / contexts.h
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.
4
5 #ifndef V8_CONTEXTS_H_
6 #define V8_CONTEXTS_H_
7
8 #include "src/heap/heap.h"
9 #include "src/objects.h"
10
11 namespace v8 {
12 namespace internal {
13
14
15 enum ContextLookupFlags {
16   FOLLOW_CONTEXT_CHAIN = 1,
17   FOLLOW_PROTOTYPE_CHAIN = 2,
18
19   DONT_FOLLOW_CHAINS = 0,
20   FOLLOW_CHAINS = FOLLOW_CONTEXT_CHAIN | FOLLOW_PROTOTYPE_CHAIN
21 };
22
23
24 // ES5 10.2 defines lexical environments with mutable and immutable bindings.
25 // Immutable bindings have two states, initialized and uninitialized, and
26 // their state is changed by the InitializeImmutableBinding method. The
27 // BindingFlags enum represents information if a binding has definitely been
28 // initialized. A mutable binding does not need to be checked and thus has
29 // the BindingFlag MUTABLE_IS_INITIALIZED.
30 //
31 // There are two possibilities for immutable bindings
32 //  * 'const' declared variables. They are initialized when evaluating the
33 //    corresponding declaration statement. They need to be checked for being
34 //    initialized and thus get the flag IMMUTABLE_CHECK_INITIALIZED.
35 //  * The function name of a named function literal. The binding is immediately
36 //    initialized when entering the function and thus does not need to be
37 //    checked. it gets the BindingFlag IMMUTABLE_IS_INITIALIZED.
38 // Accessing an uninitialized binding produces the undefined value.
39 //
40 // The harmony proposal for block scoped bindings also introduces the
41 // uninitialized state for mutable bindings.
42 //  * A 'let' declared variable. They are initialized when evaluating the
43 //    corresponding declaration statement. They need to be checked for being
44 //    initialized and thus get the flag MUTABLE_CHECK_INITIALIZED.
45 //  * A 'var' declared variable. It is initialized immediately upon creation
46 //    and thus doesn't need to be checked. It gets the flag
47 //    MUTABLE_IS_INITIALIZED.
48 //  * Catch bound variables, function parameters and variables introduced by
49 //    function declarations are initialized immediately and do not need to be
50 //    checked. Thus they get the flag MUTABLE_IS_INITIALIZED.
51 // Immutable bindings in harmony mode get the _HARMONY flag variants. Accessing
52 // an uninitialized binding produces a reference error.
53 //
54 // In V8 uninitialized bindings are set to the hole value upon creation and set
55 // to a different value upon initialization.
56 enum BindingFlags {
57   MUTABLE_IS_INITIALIZED,
58   MUTABLE_CHECK_INITIALIZED,
59   IMMUTABLE_IS_INITIALIZED,
60   IMMUTABLE_CHECK_INITIALIZED,
61   IMMUTABLE_IS_INITIALIZED_HARMONY,
62   IMMUTABLE_CHECK_INITIALIZED_HARMONY,
63   MISSING_BINDING
64 };
65
66
67 // Heap-allocated activation contexts.
68 //
69 // Contexts are implemented as FixedArray objects; the Context
70 // class is a convenience interface casted on a FixedArray object.
71 //
72 // Note: Context must have no virtual functions and Context objects
73 // must always be allocated via Heap::AllocateContext() or
74 // Factory::NewContext.
75
76 #define NATIVE_CONTEXT_INTRINSIC_FUNCTIONS(V)                             \
77   V(CONCAT_ITERABLE_TO_ARRAY_INDEX, JSFunction, concat_iterable_to_array) \
78   V(GET_TEMPLATE_CALL_SITE_INDEX, JSFunction, get_template_call_site)     \
79   V(MAKE_RANGE_ERROR_INDEX, JSFunction, make_range_error)                 \
80   V(MAKE_TYPE_ERROR_INDEX, JSFunction, make_type_error)                   \
81   V(NON_NUMBER_TO_NUMBER_INDEX, JSFunction, non_number_to_number)         \
82   V(NON_STRING_TO_STRING_INDEX, JSFunction, non_string_to_string)         \
83   V(REFLECT_APPLY_INDEX, JSFunction, reflect_apply)                       \
84   V(REFLECT_CONSTRUCT_INDEX, JSFunction, reflect_construct)               \
85   V(SPREAD_ARGUMENTS_INDEX, JSFunction, spread_arguments)                 \
86   V(SPREAD_ITERABLE_INDEX, JSFunction, spread_iterable)                   \
87   V(TO_LENGTH_FUN_INDEX, JSFunction, to_length_fun)                       \
88   V(TO_NAME_INDEX, JSFunction, to_name)                                   \
89   V(TO_NUMBER_FUN_INDEX, JSFunction, to_number_fun)                       \
90   V(TO_PRIMITIVE_INDEX, JSFunction, to_primitive)                         \
91   V(TO_STRING_FUN_INDEX, JSFunction, to_string_fun)
92
93
94 #define NATIVE_CONTEXT_JS_BUILTINS(V)                                       \
95   V(ADD_BUILTIN_INDEX, JSFunction, add_builtin)                             \
96   V(ADD_STRONG_BUILTIN_INDEX, JSFunction, add_strong_builtin)               \
97   V(APPLY_PREPARE_BUILTIN_INDEX, JSFunction, apply_prepare_builtin)         \
98   V(BIT_AND_BUILTIN_INDEX, JSFunction, bit_and_builtin)                     \
99   V(BIT_AND_STRONG_BUILTIN_INDEX, JSFunction, bit_and_strong_builtin)       \
100   V(BIT_OR_BUILTIN_INDEX, JSFunction, bit_or_builtin)                       \
101   V(BIT_OR_STRONG_BUILTIN_INDEX, JSFunction, bit_or_strong_builtin)         \
102   V(BIT_XOR_BUILTIN_INDEX, JSFunction, bit_xor_builtin)                     \
103   V(BIT_XOR_STRONG_BUILTIN_INDEX, JSFunction, bit_xor_strong_builtin)       \
104   V(CALL_FUNCTION_PROXY_AS_CONSTRUCTOR_BUILTIN_INDEX, JSFunction,           \
105     call_function_proxy_as_constructor_builtin)                             \
106   V(CALL_FUNCTION_PROXY_BUILTIN_INDEX, JSFunction,                          \
107     call_function_proxy_builtin)                                            \
108   V(CALL_NON_FUNCTION_AS_CONSTRUCTOR_BUILTIN_INDEX, JSFunction,             \
109     call_non_function_as_constructor_builtin)                               \
110   V(CALL_NON_FUNCTION_BUILTIN_INDEX, JSFunction, call_non_function_builtin) \
111   V(COMPARE_BUILTIN_INDEX, JSFunction, compare_builtin)                     \
112   V(COMPARE_STRONG_BUILTIN_INDEX, JSFunction, compare_strong_builtin)       \
113   V(CONCAT_ITERABLE_TO_ARRAY_BUILTIN_INDEX, JSFunction,                     \
114     concat_iterable_to_array_builtin)                                       \
115   V(DIV_BUILTIN_INDEX, JSFunction, div_builtin)                             \
116   V(DIV_STRONG_BUILTIN_INDEX, JSFunction, div_strong_builtin)               \
117   V(EQUALS_BUILTIN_INDEX, JSFunction, equals_builtin)                       \
118   V(IN_BUILTIN_INDEX, JSFunction, in_builtin)                               \
119   V(MOD_BUILTIN_INDEX, JSFunction, mod_builtin)                             \
120   V(MOD_STRONG_BUILTIN_INDEX, JSFunction, mod_strong_builtin)               \
121   V(MUL_BUILTIN_INDEX, JSFunction, mul_builtin)                             \
122   V(MUL_STRONG_BUILTIN_INDEX, JSFunction, mul_strong_builtin)               \
123   V(REFLECT_APPLY_PREPARE_BUILTIN_INDEX, JSFunction,                        \
124     reflect_apply_prepare_builtin)                                          \
125   V(REFLECT_CONSTRUCT_PREPARE_BUILTIN_INDEX, JSFunction,                    \
126     reflect_construct_prepare_builtin)                                      \
127   V(SAR_BUILTIN_INDEX, JSFunction, sar_builtin)                             \
128   V(SAR_STRONG_BUILTIN_INDEX, JSFunction, sar_strong_builtin)               \
129   V(SHL_BUILTIN_INDEX, JSFunction, shl_builtin)                             \
130   V(SHL_STRONG_BUILTIN_INDEX, JSFunction, shl_strong_builtin)               \
131   V(SHR_BUILTIN_INDEX, JSFunction, shr_builtin)                             \
132   V(SHR_STRONG_BUILTIN_INDEX, JSFunction, shr_strong_builtin)               \
133   V(STACK_OVERFLOW_BUILTIN_INDEX, JSFunction, stack_overflow_builtin)       \
134   V(STRING_ADD_LEFT_BUILTIN_INDEX, JSFunction, string_add_left_builtin)     \
135   V(STRING_ADD_RIGHT_BUILTIN_INDEX, JSFunction, string_add_right_builtin)   \
136   V(SUB_BUILTIN_INDEX, JSFunction, sub_builtin)                             \
137   V(SUB_STRONG_BUILTIN_INDEX, JSFunction, sub_strong_builtin)               \
138   V(TO_NAME_BUILTIN_INDEX, JSFunction, to_name_builtin)                     \
139   V(TO_STRING_BUILTIN_INDEX, JSFunction, to_string_builtin)
140
141
142 #define NATIVE_CONTEXT_IMPORTED_FIELDS(V)                                     \
143   V(ARRAY_CONCAT_INDEX, JSFunction, array_concat)                             \
144   V(ARRAY_POP_INDEX, JSFunction, array_pop)                                   \
145   V(ARRAY_PUSH_INDEX, JSFunction, array_push)                                 \
146   V(ARRAY_SHIFT_INDEX, JSFunction, array_shift)                               \
147   V(ARRAY_SPLICE_INDEX, JSFunction, array_splice)                             \
148   V(ARRAY_SLICE_INDEX, JSFunction, array_slice)                               \
149   V(ARRAY_UNSHIFT_INDEX, JSFunction, array_unshift)                           \
150   V(ARRAY_VALUES_ITERATOR_INDEX, JSFunction, array_values_iterator)           \
151   V(CREATE_DATE_FUN_INDEX, JSFunction, create_date_fun)                       \
152   V(DERIVED_GET_TRAP_INDEX, JSFunction, derived_get_trap)                     \
153   V(DERIVED_HAS_TRAP_INDEX, JSFunction, derived_has_trap)                     \
154   V(DERIVED_SET_TRAP_INDEX, JSFunction, derived_set_trap)                     \
155   V(ERROR_FUNCTION_INDEX, JSFunction, error_function)                         \
156   V(EVAL_ERROR_FUNCTION_INDEX, JSFunction, eval_error_function)               \
157   V(GET_STACK_TRACE_LINE_INDEX, JSFunction, get_stack_trace_line_fun)         \
158   V(GLOBAL_EVAL_FUN_INDEX, JSFunction, global_eval_fun)                       \
159   V(JSON_SERIALIZE_ADAPTER_INDEX, JSFunction, json_serialize_adapter)         \
160   V(MAKE_ERROR_FUNCTION_INDEX, JSFunction, make_error_function)               \
161   V(MAP_DELETE_METHOD_INDEX, JSFunction, map_delete)                          \
162   V(MAP_FROM_ARRAY_INDEX, JSFunction, map_from_array)                         \
163   V(MAP_GET_METHOD_INDEX, JSFunction, map_get)                                \
164   V(MAP_HAS_METHOD_INDEX, JSFunction, map_has)                                \
165   V(MAP_SET_METHOD_INDEX, JSFunction, map_set)                                \
166   V(MESSAGE_GET_COLUMN_NUMBER_INDEX, JSFunction, message_get_column_number)   \
167   V(MESSAGE_GET_LINE_NUMBER_INDEX, JSFunction, message_get_line_number)       \
168   V(MESSAGE_GET_SOURCE_LINE_INDEX, JSFunction, message_get_source_line)       \
169   V(NATIVE_OBJECT_GET_NOTIFIER_INDEX, JSFunction, native_object_get_notifier) \
170   V(NATIVE_OBJECT_NOTIFIER_PERFORM_CHANGE, JSFunction,                        \
171     native_object_notifier_perform_change)                                    \
172   V(NATIVE_OBJECT_OBSERVE_INDEX, JSFunction, native_object_observe)           \
173   V(NO_SIDE_EFFECT_TO_STRING_FUN_INDEX, JSFunction,                           \
174     no_side_effect_to_string_fun)                                             \
175   V(OBJECT_DEFINE_OWN_PROPERTY_INDEX, JSFunction, object_define_own_property) \
176   V(OBJECT_GET_OWN_PROPERTY_DESCROPTOR_INDEX, JSFunction,                     \
177     object_get_own_property_descriptor)                                       \
178   V(OBSERVERS_BEGIN_SPLICE_INDEX, JSFunction, observers_begin_perform_splice) \
179   V(OBSERVERS_END_SPLICE_INDEX, JSFunction, observers_end_perform_splice)     \
180   V(OBSERVERS_ENQUEUE_SPLICE_INDEX, JSFunction, observers_enqueue_splice)     \
181   V(OBSERVERS_NOTIFY_CHANGE_INDEX, JSFunction, observers_notify_change)       \
182   V(PROMISE_CATCH_INDEX, JSFunction, promise_catch)                           \
183   V(PROMISE_CHAIN_INDEX, JSFunction, promise_chain)                           \
184   V(PROMISE_CREATE_INDEX, JSFunction, promise_create)                         \
185   V(PROMISE_HAS_USER_DEFINED_REJECT_HANDLER_INDEX, JSFunction,                \
186     promise_has_user_defined_reject_handler)                                  \
187   V(PROMISE_REJECT_INDEX, JSFunction, promise_reject)                         \
188   V(PROMISE_RESOLVE_INDEX, JSFunction, promise_resolve)                       \
189   V(PROMISE_THEN_INDEX, JSFunction, promise_then)                             \
190   V(PROXY_ENUMERATE_INDEX, JSFunction, proxy_enumerate)                       \
191   V(RANGE_ERROR_FUNCTION_INDEX, JSFunction, range_error_function)             \
192   V(REFERENCE_ERROR_FUNCTION_INDEX, JSFunction, reference_error_function)     \
193   V(SET_ADD_METHOD_INDEX, JSFunction, set_add)                                \
194   V(SET_DELETE_METHOD_INDEX, JSFunction, set_delete)                          \
195   V(SET_FROM_ARRAY_INDEX, JSFunction, set_from_array)                         \
196   V(SET_HAS_METHOD_INDEX, JSFunction, set_has)                                \
197   V(STACK_OVERFLOW_BOILERPLATE_INDEX, JSObject, stack_overflow_boilerplate)   \
198   V(SYNTAX_ERROR_FUNCTION_INDEX, JSFunction, syntax_error_function)           \
199   V(TO_COMPLETE_PROPERTY_DESCRIPTOR_INDEX, JSFunction,                        \
200     to_complete_property_descriptor)                                          \
201   V(TO_DETAIL_STRING_FUN_INDEX, JSFunction, to_detail_string_fun)             \
202   V(TO_INTEGER_FUN_INDEX, JSFunction, to_integer_fun)                         \
203   V(TYPE_ERROR_FUNCTION_INDEX, JSFunction, type_error_function)               \
204   V(URI_ERROR_FUNCTION_INDEX, JSFunction, uri_error_function)                 \
205   NATIVE_CONTEXT_JS_BUILTINS(V)
206
207 #define NATIVE_CONTEXT_FIELDS(V)                                               \
208   V(GLOBAL_PROXY_INDEX, JSObject, global_proxy_object)                         \
209   V(EMBEDDER_DATA_INDEX, FixedArray, embedder_data)                            \
210   /* Below is alpha-sorted */                                                  \
211   V(ALLOW_CODE_GEN_FROM_STRINGS_INDEX, Object, allow_code_gen_from_strings)    \
212   V(ARRAY_BUFFER_FUN_INDEX, JSFunction, array_buffer_fun)                      \
213   V(ARRAY_BUFFER_MAP_INDEX, Map, array_buffer_map)                             \
214   V(ARRAY_FUNCTION_INDEX, JSFunction, array_function)                          \
215   V(BOOL16X8_FUNCTION_INDEX, JSFunction, bool16x8_function)                    \
216   V(BOOL32X4_FUNCTION_INDEX, JSFunction, bool32x4_function)                    \
217   V(BOOL8X16_FUNCTION_INDEX, JSFunction, bool8x16_function)                    \
218   V(BOOLEAN_FUNCTION_INDEX, JSFunction, boolean_function)                      \
219   V(BOUND_FUNCTION_MAP_INDEX, Map, bound_function_map)                         \
220   V(CALL_AS_CONSTRUCTOR_DELEGATE_INDEX, JSFunction,                            \
221     call_as_constructor_delegate)                                              \
222   V(CALL_AS_FUNCTION_DELEGATE_INDEX, JSFunction, call_as_function_delegate)    \
223   V(CONTEXT_EXTENSION_FUNCTION_INDEX, JSFunction, context_extension_function)  \
224   V(DATA_VIEW_FUN_INDEX, JSFunction, data_view_fun)                            \
225   V(ERROR_MESSAGE_FOR_CODE_GEN_FROM_STRINGS_INDEX, Object,                     \
226     error_message_for_code_gen_from_strings)                                   \
227   V(EXTRAS_EXPORTS_OBJECT_INDEX, JSObject, extras_binding_object)              \
228   V(FAST_ALIASED_ARGUMENTS_MAP_INDEX, Map, fast_aliased_arguments_map)         \
229   V(FLOAT32_ARRAY_FUN_INDEX, JSFunction, float32_array_fun)                    \
230   V(FLOAT32X4_FUNCTION_INDEX, JSFunction, float32x4_function)                  \
231   V(FLOAT64_ARRAY_FUN_INDEX, JSFunction, float64_array_fun)                    \
232   V(FUNCTION_CACHE_INDEX, ObjectHashTable, function_cache)                     \
233   V(GENERATOR_OBJECT_PROTOTYPE_MAP_INDEX, Map, generator_object_prototype_map) \
234   V(INITIAL_ARRAY_PROTOTYPE_INDEX, JSObject, initial_array_prototype)          \
235   V(INITIAL_OBJECT_PROTOTYPE_INDEX, JSObject, initial_object_prototype)        \
236   V(INT16_ARRAY_FUN_INDEX, JSFunction, int16_array_fun)                        \
237   V(INT16X8_FUNCTION_INDEX, JSFunction, int16x8_function)                      \
238   V(INT32_ARRAY_FUN_INDEX, JSFunction, int32_array_fun)                        \
239   V(INT32X4_FUNCTION_INDEX, JSFunction, int32x4_function)                      \
240   V(INT8_ARRAY_FUN_INDEX, JSFunction, int8_array_fun)                          \
241   V(INT8X16_FUNCTION_INDEX, JSFunction, int8x16_function)                      \
242   V(INTERNAL_ARRAY_FUNCTION_INDEX, JSFunction, internal_array_function)        \
243   V(ITERATOR_RESULT_MAP_INDEX, Map, iterator_result_map)                       \
244   V(JS_ARRAY_MAPS_INDEX, Object, js_array_maps)                                \
245   V(JS_ARRAY_STRONG_MAPS_INDEX, Object, js_array_strong_maps)                  \
246   V(JS_MAP_FUN_INDEX, JSFunction, js_map_fun)                                  \
247   V(JS_MAP_MAP_INDEX, Map, js_map_map)                                         \
248   V(JS_OBJECT_STRONG_MAP_INDEX, Map, js_object_strong_map)                     \
249   V(JS_SET_FUN_INDEX, JSFunction, js_set_fun)                                  \
250   V(JS_SET_MAP_INDEX, Map, js_set_map)                                         \
251   V(MAP_CACHE_INDEX, Object, map_cache)                                        \
252   V(MAP_ITERATOR_MAP_INDEX, Map, map_iterator_map)                             \
253   V(MESSAGE_LISTENERS_INDEX, JSObject, message_listeners)                      \
254   V(NATIVES_UTILS_OBJECT_INDEX, Object, natives_utils_object)                  \
255   V(NORMALIZED_MAP_CACHE_INDEX, Object, normalized_map_cache)                  \
256   V(NUMBER_FUNCTION_INDEX, JSFunction, number_function)                        \
257   V(OBJECT_FUNCTION_INDEX, JSFunction, object_function)                        \
258   V(OPAQUE_REFERENCE_FUNCTION_INDEX, JSFunction, opaque_reference_function)    \
259   V(REGEXP_FUNCTION_INDEX, JSFunction, regexp_function)                        \
260   V(REGEXP_RESULT_MAP_INDEX, Map, regexp_result_map)                           \
261   V(RUNTIME_CONTEXT_INDEX, Context, runtime_context)                           \
262   V(SCRIPT_CONTEXT_TABLE_INDEX, ScriptContextTable, script_context_table)      \
263   V(SCRIPT_FUNCTION_INDEX, JSFunction, script_function)                        \
264   V(SECURITY_TOKEN_INDEX, Object, security_token)                              \
265   V(SET_ITERATOR_MAP_INDEX, Map, set_iterator_map)                             \
266   V(SHARED_ARRAY_BUFFER_FUN_INDEX, JSFunction, shared_array_buffer_fun)        \
267   V(SLOPPY_ARGUMENTS_MAP_INDEX, Map, sloppy_arguments_map)                     \
268   V(SLOPPY_FUNCTION_MAP_INDEX, Map, sloppy_function_map)                       \
269   V(SLOPPY_FUNCTION_WITHOUT_PROTOTYPE_MAP_INDEX, Map,                          \
270     sloppy_function_without_prototype_map)                                     \
271   V(SLOPPY_FUNCTION_WITH_READONLY_PROTOTYPE_MAP_INDEX, Map,                    \
272     sloppy_function_with_readonly_prototype_map)                               \
273   V(SLOPPY_GENERATOR_FUNCTION_MAP_INDEX, Map, sloppy_generator_function_map)   \
274   V(SLOW_ALIASED_ARGUMENTS_MAP_INDEX, Map, slow_aliased_arguments_map)         \
275   V(STRICT_ARGUMENTS_MAP_INDEX, Map, strict_arguments_map)                     \
276   V(STRICT_FUNCTION_MAP_INDEX, Map, strict_function_map)                       \
277   V(STRICT_FUNCTION_WITHOUT_PROTOTYPE_MAP_INDEX, Map,                          \
278     strict_function_without_prototype_map)                                     \
279   V(STRICT_GENERATOR_FUNCTION_MAP_INDEX, Map, strict_generator_function_map)   \
280   V(STRING_FUNCTION_INDEX, JSFunction, string_function)                        \
281   V(STRING_FUNCTION_PROTOTYPE_MAP_INDEX, Map, string_function_prototype_map)   \
282   V(STRONG_CONSTRUCTOR_MAP_INDEX, Map, strong_constructor_map)                 \
283   V(STRONG_FUNCTION_MAP_INDEX, Map, strong_function_map)                       \
284   V(STRONG_GENERATOR_FUNCTION_MAP_INDEX, Map, strong_generator_function_map)   \
285   V(STRONG_MAP_CACHE_INDEX, Object, strong_map_cache)                          \
286   V(SYMBOL_FUNCTION_INDEX, JSFunction, symbol_function)                        \
287   V(UINT16_ARRAY_FUN_INDEX, JSFunction, uint16_array_fun)                      \
288   V(UINT16X8_FUNCTION_INDEX, JSFunction, uint16x8_function)                    \
289   V(UINT32_ARRAY_FUN_INDEX, JSFunction, uint32_array_fun)                      \
290   V(UINT32X4_FUNCTION_INDEX, JSFunction, uint32x4_function)                    \
291   V(UINT8_ARRAY_FUN_INDEX, JSFunction, uint8_array_fun)                        \
292   V(UINT8_CLAMPED_ARRAY_FUN_INDEX, JSFunction, uint8_clamped_array_fun)        \
293   V(UINT8X16_FUNCTION_INDEX, JSFunction, uint8x16_function)                    \
294   NATIVE_CONTEXT_INTRINSIC_FUNCTIONS(V)                                        \
295   NATIVE_CONTEXT_IMPORTED_FIELDS(V)
296
297 // A table of all script contexts. Every loaded top-level script with top-level
298 // lexical declarations contributes its ScriptContext into this table.
299 //
300 // The table is a fixed array, its first slot is the current used count and
301 // the subsequent slots 1..used contain ScriptContexts.
302 class ScriptContextTable : public FixedArray {
303  public:
304   // Conversions.
305   static ScriptContextTable* cast(Object* context) {
306     DCHECK(context->IsScriptContextTable());
307     return reinterpret_cast<ScriptContextTable*>(context);
308   }
309
310   struct LookupResult {
311     int context_index;
312     int slot_index;
313     VariableMode mode;
314     VariableLocation location;
315     InitializationFlag init_flag;
316     MaybeAssignedFlag maybe_assigned_flag;
317   };
318
319   int used() const { return Smi::cast(get(kUsedSlot))->value(); }
320
321   void set_used(int used) { set(kUsedSlot, Smi::FromInt(used)); }
322
323   static Handle<Context> GetContext(Handle<ScriptContextTable> table, int i) {
324     DCHECK(i < table->used());
325     return Handle<Context>::cast(FixedArray::get(table, i + 1));
326   }
327
328   // Lookup a variable `name` in a ScriptContextTable.
329   // If it returns true, the variable is found and `result` contains
330   // valid information about its location.
331   // If it returns false, `result` is untouched.
332   MUST_USE_RESULT
333   static bool Lookup(Handle<ScriptContextTable> table, Handle<String> name,
334                      LookupResult* result);
335
336   MUST_USE_RESULT
337   static Handle<ScriptContextTable> Extend(Handle<ScriptContextTable> table,
338                                            Handle<Context> script_context);
339
340   static int GetContextOffset(int context_index) {
341     return kFirstContextOffset + context_index * kPointerSize;
342   }
343
344  private:
345   static const int kUsedSlot = 0;
346   static const int kFirstContextOffset =
347       FixedArray::kHeaderSize + (kUsedSlot + 1) * kPointerSize;
348
349   DISALLOW_IMPLICIT_CONSTRUCTORS(ScriptContextTable);
350 };
351
352 // JSFunctions are pairs (context, function code), sometimes also called
353 // closures. A Context object is used to represent function contexts and
354 // dynamically pushed 'with' contexts (or 'scopes' in ECMA-262 speak).
355 //
356 // At runtime, the contexts build a stack in parallel to the execution
357 // stack, with the top-most context being the current context. All contexts
358 // have the following slots:
359 //
360 // [ closure   ]  This is the current function. It is the same for all
361 //                contexts inside a function. It provides access to the
362 //                incoming context (i.e., the outer context, which may
363 //                or may not become the current function's context), and
364 //                it provides access to the functions code and thus it's
365 //                scope information, which in turn contains the names of
366 //                statically allocated context slots. The names are needed
367 //                for dynamic lookups in the presence of 'with' or 'eval'.
368 //
369 // [ previous  ]  A pointer to the previous context. It is NULL for
370 //                function contexts, and non-NULL for 'with' contexts.
371 //                Used to implement the 'with' statement.
372 //
373 // [ extension ]  A pointer to an extension JSObject, or NULL. Used to
374 //                implement 'with' statements and dynamic declarations
375 //                (through 'eval'). The object in a 'with' statement is
376 //                stored in the extension slot of a 'with' context.
377 //                Dynamically declared variables/functions are also added
378 //                to lazily allocated extension object. Context::Lookup
379 //                searches the extension object for properties.
380 //                For script and block contexts, contains the respective
381 //                ScopeInfo. For block contexts representing sloppy declaration
382 //                block scopes, it may also be a struct being a
383 //                SloppyBlockWithEvalContextExtension, pairing the ScopeInfo
384 //                with an extension object.
385 //                For module contexts, points back to the respective JSModule.
386 //
387 // [ global_object ]  A pointer to the global object. Provided for quick
388 //                access to the global object from inside the code (since
389 //                we always have a context pointer).
390 //
391 // In addition, function contexts may have statically allocated context slots
392 // to store local variables/functions that are accessed from inner functions
393 // (via static context addresses) or through 'eval' (dynamic context lookups).
394 // The native context contains additional slots for fast access to native
395 // properties.
396 //
397 // Finally, with Harmony scoping, the JSFunction representing a top level
398 // script will have the ScriptContext rather than a FunctionContext.
399 // Script contexts from all top-level scripts are gathered in
400 // ScriptContextTable.
401
402 class Context: public FixedArray {
403  public:
404   // Conversions.
405   static Context* cast(Object* context) {
406     DCHECK(context->IsContext());
407     return reinterpret_cast<Context*>(context);
408   }
409
410   // The default context slot layout; indices are FixedArray slot indices.
411   enum {
412     // These slots are in all contexts.
413     CLOSURE_INDEX,
414     PREVIOUS_INDEX,
415     // The extension slot is used for either the global object (in global
416     // contexts), eval extension object (function contexts), subject of with
417     // (with contexts), or the variable name (catch contexts), the serialized
418     // scope info (block contexts), or the module instance (module contexts).
419     EXTENSION_INDEX,
420     GLOBAL_OBJECT_INDEX,
421
422     // These slots are only in native contexts.
423 #define NATIVE_CONTEXT_SLOT(index, type, name) index,
424     NATIVE_CONTEXT_FIELDS(NATIVE_CONTEXT_SLOT)
425 #undef NATIVE_CONTEXT_SLOT
426
427     // Properties from here are treated as weak references by the full GC.
428     // Scavenge treats them as strong references.
429     OPTIMIZED_FUNCTIONS_LIST,  // Weak.
430     OPTIMIZED_CODE_LIST,       // Weak.
431     DEOPTIMIZED_CODE_LIST,     // Weak.
432     NEXT_CONTEXT_LINK,         // Weak.
433
434     // Total number of slots.
435     NATIVE_CONTEXT_SLOTS,
436     FIRST_WEAK_SLOT = OPTIMIZED_FUNCTIONS_LIST,
437
438     MIN_CONTEXT_SLOTS = GLOBAL_PROXY_INDEX,
439     // This slot holds the thrown value in catch contexts.
440     THROWN_OBJECT_INDEX = MIN_CONTEXT_SLOTS,
441   };
442
443   // Direct slot access.
444   JSFunction* closure() { return JSFunction::cast(get(CLOSURE_INDEX)); }
445   void set_closure(JSFunction* closure) { set(CLOSURE_INDEX, closure); }
446
447   Context* previous() {
448     Object* result = unchecked_previous();
449     DCHECK(IsBootstrappingOrValidParentContext(result, this));
450     return reinterpret_cast<Context*>(result);
451   }
452   void set_previous(Context* context) { set(PREVIOUS_INDEX, context); }
453
454   bool has_extension() { return extension() != nullptr; }
455   Object* extension() { return get(EXTENSION_INDEX); }
456   void set_extension(Object* object) { set(EXTENSION_INDEX, object); }
457   JSObject* extension_object();
458   JSReceiver* extension_receiver();
459   ScopeInfo* scope_info();
460   String* catch_name();
461
462   JSModule* module() { return JSModule::cast(get(EXTENSION_INDEX)); }
463   void set_module(JSModule* module) { set(EXTENSION_INDEX, module); }
464
465   // Get the context where var declarations will be hoisted to, which
466   // may be the context itself.
467   Context* declaration_context();
468   bool is_declaration_context();
469
470   GlobalObject* global_object() {
471     Object* result = get(GLOBAL_OBJECT_INDEX);
472     DCHECK(IsBootstrappingOrGlobalObject(this->GetIsolate(), result));
473     return reinterpret_cast<GlobalObject*>(result);
474   }
475   void set_global_object(GlobalObject* object) {
476     set(GLOBAL_OBJECT_INDEX, object);
477   }
478
479   // Returns a JSGlobalProxy object or null.
480   JSObject* global_proxy();
481   void set_global_proxy(JSObject* global);
482
483   // The builtins object.
484   JSBuiltinsObject* builtins();
485
486   // Get the script context by traversing the context chain.
487   Context* script_context();
488
489   // Compute the native context by traversing the context chain.
490   Context* native_context();
491
492   // Predicates for context types.  IsNativeContext is also defined on Object
493   // because we frequently have to know if arbitrary objects are natives
494   // contexts.
495   bool IsNativeContext() {
496     Map* map = this->map();
497     return map == map->GetHeap()->native_context_map();
498   }
499   bool IsFunctionContext() {
500     Map* map = this->map();
501     return map == map->GetHeap()->function_context_map();
502   }
503   bool IsCatchContext() {
504     Map* map = this->map();
505     return map == map->GetHeap()->catch_context_map();
506   }
507   bool IsWithContext() {
508     Map* map = this->map();
509     return map == map->GetHeap()->with_context_map();
510   }
511   bool IsBlockContext() {
512     Map* map = this->map();
513     return map == map->GetHeap()->block_context_map();
514   }
515   bool IsModuleContext() {
516     Map* map = this->map();
517     return map == map->GetHeap()->module_context_map();
518   }
519   bool IsScriptContext() {
520     Map* map = this->map();
521     return map == map->GetHeap()->script_context_map();
522   }
523
524   bool HasSameSecurityTokenAs(Context* that) {
525     return this->global_object()->native_context()->security_token() ==
526         that->global_object()->native_context()->security_token();
527   }
528
529   // Initializes global variable bindings in given script context.
530   void InitializeGlobalSlots();
531
532   // A native context holds a list of all functions with optimized code.
533   void AddOptimizedFunction(JSFunction* function);
534   void RemoveOptimizedFunction(JSFunction* function);
535   void SetOptimizedFunctionsListHead(Object* head);
536   Object* OptimizedFunctionsListHead();
537
538   // The native context also stores a list of all optimized code and a
539   // list of all deoptimized code, which are needed by the deoptimizer.
540   void AddOptimizedCode(Code* code);
541   void SetOptimizedCodeListHead(Object* head);
542   Object* OptimizedCodeListHead();
543   void SetDeoptimizedCodeListHead(Object* head);
544   Object* DeoptimizedCodeListHead();
545
546   Handle<Object> ErrorMessageForCodeGenerationFromStrings();
547
548   static int ImportedFieldIndexForName(Handle<String> name);
549   static int IntrinsicIndexForName(Handle<String> name);
550
551   static bool IsJSBuiltin(Handle<Context> native_context,
552                           Handle<JSFunction> function);
553
554 #define NATIVE_CONTEXT_FIELD_ACCESSORS(index, type, name) \
555   void  set_##name(type* value) {                         \
556     DCHECK(IsNativeContext());                            \
557     set(index, value);                                    \
558   }                                                       \
559   bool is_##name(type* value) {                           \
560     DCHECK(IsNativeContext());                            \
561     return type::cast(get(index)) == value;               \
562   }                                                       \
563   type* name() {                                          \
564     DCHECK(IsNativeContext());                            \
565     return type::cast(get(index));                        \
566   }
567   NATIVE_CONTEXT_FIELDS(NATIVE_CONTEXT_FIELD_ACCESSORS)
568 #undef NATIVE_CONTEXT_FIELD_ACCESSORS
569
570   // Lookup the slot called name, starting with the current context.
571   // There are three possibilities:
572   //
573   // 1) result->IsContext():
574   //    The binding was found in a context.  *index is always the
575   //    non-negative slot index.  *attributes is NONE for var and let
576   //    declarations, READ_ONLY for const declarations (never ABSENT).
577   //
578   // 2) result->IsJSObject():
579   //    The binding was found as a named property in a context extension
580   //    object (i.e., was introduced via eval), as a property on the subject
581   //    of with, or as a property of the global object.  *index is -1 and
582   //    *attributes is not ABSENT.
583   //
584   // 3) result.is_null():
585   //    There was no binding found, *index is always -1 and *attributes is
586   //    always ABSENT.
587   Handle<Object> Lookup(Handle<String> name,
588                         ContextLookupFlags flags,
589                         int* index,
590                         PropertyAttributes* attributes,
591                         BindingFlags* binding_flags);
592
593   // Code generation support.
594   static int SlotOffset(int index) {
595     return kHeaderSize + index * kPointerSize - kHeapObjectTag;
596   }
597
598   static int FunctionMapIndex(LanguageMode language_mode, FunctionKind kind) {
599     if (IsGeneratorFunction(kind)) {
600       return is_strong(language_mode) ? STRONG_GENERATOR_FUNCTION_MAP_INDEX :
601              is_strict(language_mode) ? STRICT_GENERATOR_FUNCTION_MAP_INDEX
602                                       : SLOPPY_GENERATOR_FUNCTION_MAP_INDEX;
603     }
604
605     if (IsConstructor(kind)) {
606       // Use strict function map (no own "caller" / "arguments")
607       return is_strong(language_mode) ? STRONG_CONSTRUCTOR_MAP_INDEX
608                                       : STRICT_FUNCTION_MAP_INDEX;
609     }
610
611     if (IsArrowFunction(kind) || IsConciseMethod(kind) ||
612         IsAccessorFunction(kind)) {
613       return is_strong(language_mode)
614                  ? STRONG_FUNCTION_MAP_INDEX
615                  : STRICT_FUNCTION_WITHOUT_PROTOTYPE_MAP_INDEX;
616     }
617
618     return is_strong(language_mode) ? STRONG_FUNCTION_MAP_INDEX :
619            is_strict(language_mode) ? STRICT_FUNCTION_MAP_INDEX
620                                     : SLOPPY_FUNCTION_MAP_INDEX;
621   }
622
623   static const int kSize = kHeaderSize + NATIVE_CONTEXT_SLOTS * kPointerSize;
624   static const int kNotFound = -1;
625
626   // GC support.
627   typedef FixedBodyDescriptor<
628       kHeaderSize, kSize, kSize> ScavengeBodyDescriptor;
629
630   typedef FixedBodyDescriptor<
631       kHeaderSize,
632       kHeaderSize + FIRST_WEAK_SLOT * kPointerSize,
633       kSize> MarkCompactBodyDescriptor;
634
635  private:
636   // Unchecked access to the slots.
637   Object* unchecked_previous() { return get(PREVIOUS_INDEX); }
638
639 #ifdef DEBUG
640   // Bootstrapping-aware type checks.
641   static bool IsBootstrappingOrValidParentContext(Object* object, Context* kid);
642   static bool IsBootstrappingOrGlobalObject(Isolate* isolate, Object* object);
643 #endif
644
645   STATIC_ASSERT(kHeaderSize == Internals::kContextHeaderSize);
646   STATIC_ASSERT(EMBEDDER_DATA_INDEX == Internals::kContextEmbedderDataIndex);
647 };
648
649 } }  // namespace v8::internal
650
651 #endif  // V8_CONTEXTS_H_