/*
 *  Copyright (C) 2007 Eric Seidel <eric@webkit.org>
 *  Copyright (C) 2007, 2008, 2009 Apple Inc. All rights reserved.
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Library General Public
 *  License as published by the Free Software Foundation; either
 *  version 2 of the License, or (at your option) any later version.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Library General Public License for more details.
 *
 *  You should have received a copy of the GNU Library General Public License
 *  along with this library; see the file COPYING.LIB.  If not, write to
 *  the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 *  Boston, MA 02110-1301, USA.
 *
 */

#ifndef JSGlobalObject_h
#define JSGlobalObject_h

#include "ArrayAllocationProfile.h"
#include "InternalFunction.h"
#include "JSArray.h"
#include "JSArrayBufferPrototype.h"
#include "JSClassRef.h"
#include "JSGlobalLexicalEnvironment.h"
#include "JSProxy.h"
#include "JSSegmentedVariableObject.h"
#include "JSWeakObjectMapRefInternal.h"
#include "NumberPrototype.h"
#include "ObjectPropertyChangeAdaptiveWatchpoint.h"
#include "SpecialPointer.h"
#include "StringPrototype.h"
#include "StructureChain.h"
#include "StructureRareDataInlines.h"
#include "SymbolPrototype.h"
#include "TemplateRegistry.h"
#include "VM.h"
#include "VariableEnvironment.h"
#include "Watchpoint.h"
#include <wtf/HashSet.h>
#include <wtf/OwnPtr.h>
#include <wtf/PassRefPtr.h>
#include <wtf/RandomNumber.h>

struct OpaqueJSClass;
struct OpaqueJSClassContextData;

namespace JSC {

class ArrayConstructor;
class ArrayPrototype;
class BooleanPrototype;
class BuiltinExecutables;
class Debugger;
class ErrorConstructor;
class ErrorPrototype;
class FunctionPrototype;
class GeneratorPrototype;
class GeneratorFunctionPrototype;
class GetterSetter;
class GlobalCodeBlock;
class JSPromise;
class JSPromiseConstructor;
class JSPromisePrototype;
class JSInternalPromise;
class LLIntOffsetsExtractor;
class Microtask;
class ModuleLoaderObject;
class NativeErrorConstructor;
class ObjectConstructor;
class ProgramCodeBlock;
class RegExpConstructor;
class RegExpPrototype;
class JSStack;
class NullGetterFunction;
class NullSetterFunction;

struct ActivationStackNode;
struct HashTable;

#define DEFINE_STANDARD_BUILTIN(macro, upperName, lowerName) macro(upperName, lowerName, lowerName, JS ## upperName, upperName)

#define FOR_EACH_SIMPLE_BUILTIN_TYPE_WITH_CONSTRUCTOR(macro) \
    macro(Set, set, set, JSSet, Set) \
    macro(Map, map, map, JSMap, Map) \
    macro(Date, date, date, DateInstance, Date) \
    macro(String, string, stringObject, StringObject, String) \
    macro(Symbol, symbol, symbolObject, SymbolObject, Symbol) \
    macro(Boolean, boolean, booleanObject, BooleanObject, Boolean) \
    macro(Number, number, numberObject, NumberObject, Number) \
    macro(Error, error, error, ErrorInstance, Error) \
    macro(JSPromise, promise, promise, JSPromise, Promise) \
    macro(JSArrayBuffer, arrayBuffer, arrayBuffer, JSArrayBuffer, ArrayBuffer) \
    DEFINE_STANDARD_BUILTIN(macro, WeakMap, weakMap) \
    DEFINE_STANDARD_BUILTIN(macro, WeakSet, weakSet) \

#define FOR_EACH_BUILTIN_DERIVED_ITERATOR_TYPE(macro) \
    DEFINE_STANDARD_BUILTIN(macro, ArrayIterator, arrayIterator) \
    DEFINE_STANDARD_BUILTIN(macro, MapIterator, mapIterator) \
    DEFINE_STANDARD_BUILTIN(macro, SetIterator, setIterator) \
    DEFINE_STANDARD_BUILTIN(macro, StringIterator, stringIterator) \

#define FOR_EACH_BUILTIN_ITERATOR_TYPE(macro) \
    DEFINE_STANDARD_BUILTIN(macro, Iterator, iterator) \
    FOR_EACH_BUILTIN_DERIVED_ITERATOR_TYPE(macro) \

#define FOR_EACH_SIMPLE_BUILTIN_TYPE(macro) \
    FOR_EACH_SIMPLE_BUILTIN_TYPE_WITH_CONSTRUCTOR(macro) \
    macro(JSInternalPromise, internalPromise, internalPromise, JSInternalPromise, InternalPromise) \

#define DECLARE_SIMPLE_BUILTIN_TYPE(capitalName, lowerName, properName, instanceType, jsName) \
    class JS ## capitalName; \
    class capitalName ## Prototype; \
    class capitalName ## Constructor;

class IteratorPrototype;
FOR_EACH_SIMPLE_BUILTIN_TYPE(DECLARE_SIMPLE_BUILTIN_TYPE)
FOR_EACH_BUILTIN_DERIVED_ITERATOR_TYPE(DECLARE_SIMPLE_BUILTIN_TYPE)

#undef DECLARE_SIMPLE_BUILTIN_TYPE

typedef Vector<ExecState*, 16> ExecStateStack;

struct GlobalObjectMethodTable {
	typedef bool (*SupportsProfilingFunctionPtr)(const JSGlobalObject*);
	SupportsProfilingFunctionPtr supportsProfiling;

	typedef bool (*SupportsRichSourceInfoFunctionPtr)(const JSGlobalObject*);
	SupportsRichSourceInfoFunctionPtr supportsRichSourceInfo;

	typedef bool (*ShouldInterruptScriptFunctionPtr)(const JSGlobalObject*);
	ShouldInterruptScriptFunctionPtr shouldInterruptScript;

	typedef bool (*JavaScriptExperimentsEnabledFunctionPtr)(const JSGlobalObject*);
	JavaScriptExperimentsEnabledFunctionPtr javaScriptExperimentsEnabled;

    typedef void (*QueueTaskToEventLoopFunctionPtr)(const JSGlobalObject*, PassRefPtr<Microtask>);
    QueueTaskToEventLoopFunctionPtr queueTaskToEventLoop;

    typedef JSInternalPromise* (*ModuleLoaderResolvePtr)(JSGlobalObject*, ExecState*, JSValue, JSValue);
    ModuleLoaderResolvePtr moduleLoaderResolve;

    typedef JSInternalPromise* (*ModuleLoaderFetchPtr)(JSGlobalObject*, ExecState*, JSValue);
    ModuleLoaderFetchPtr moduleLoaderFetch;

    typedef JSInternalPromise* (*ModuleLoaderTranslatePtr)(JSGlobalObject*, ExecState*, JSValue, JSValue);
    ModuleLoaderTranslatePtr moduleLoaderTranslate;

    typedef JSInternalPromise* (*ModuleLoaderInstantiatePtr)(JSGlobalObject*, ExecState*, JSValue, JSValue);
    ModuleLoaderInstantiatePtr moduleLoaderInstantiate;

    typedef JSValue (*ModuleLoaderEvaluatePtr)(JSGlobalObject*, ExecState*, JSValue, JSValue);
    ModuleLoaderEvaluatePtr moduleLoaderEvaluate;
};

class JSGlobalObject : public JSSegmentedVariableObject {
private:
	typedef HashSet<RefPtr<OpaqueJSWeakObjectMap> > WeakMapSet;
	typedef HashMap<OpaqueJSClass*, OwnPtr<OpaqueJSClassContextData> > OpaqueJSClassDataMap;

	struct JSGlobalObjectRareData {
		WTF_MAKE_FAST_ALLOCATED;
	public:
		JSGlobalObjectRareData()
			: profileGroup(0)
		{
		}

		WeakMapSet weakMaps;
		unsigned profileGroup;

        OpaqueJSClassDataMap opaqueJSClassData;
	};

// Our hashtable code-generator tries to access these properties, so we make them public.
// However, we'd like it better if they could be protected.
public:
    Register m_globalCallFrame[JSStack::CallFrameHeaderSize];

	WriteBarrier<JSObject> m_globalThis;

    WriteBarrier<JSGlobalLexicalEnvironment> m_globalLexicalEnvironment;
    WriteBarrier<JSObject> m_globalCallee;
	WriteBarrier<RegExpConstructor> m_regExpConstructor;
	WriteBarrier<ErrorConstructor> m_errorConstructor;
	WriteBarrier<NativeErrorConstructor> m_evalErrorConstructor;
	WriteBarrier<NativeErrorConstructor> m_rangeErrorConstructor;
	WriteBarrier<NativeErrorConstructor> m_referenceErrorConstructor;
	WriteBarrier<NativeErrorConstructor> m_syntaxErrorConstructor;
	WriteBarrier<NativeErrorConstructor> m_typeErrorConstructor;
	WriteBarrier<NativeErrorConstructor> m_URIErrorConstructor;
    WriteBarrier<ObjectConstructor> m_objectConstructor;
    WriteBarrier<ArrayConstructor> m_arrayConstructor;
    WriteBarrier<JSPromiseConstructor> m_promiseConstructor;
    WriteBarrier<JSInternalPromiseConstructor> m_internalPromiseConstructor;
    WriteBarrier<Structure> m_proxyObjectStructure;
    WriteBarrier<Structure> m_callableProxyObjectStructure;
    WriteBarrier<Structure> m_proxyRevokeStructure;

    WriteBarrier<JSFunction> m_parseIntFunction;

    WriteBarrier<NullGetterFunction> m_nullGetterFunction;
    WriteBarrier<NullSetterFunction> m_nullSetterFunction;

	WriteBarrier<JSFunction> m_evalFunction;
	WriteBarrier<JSFunction> m_callFunction;
	WriteBarrier<JSFunction> m_applyFunction;
    WriteBarrier<JSFunction> m_definePropertyFunction;
    WriteBarrier<JSFunction> m_arrayProtoToStringFunction;
    WriteBarrier<JSFunction> m_arrayProtoValuesFunction;
    WriteBarrier<JSFunction> m_initializePromiseFunction;
    WriteBarrier<JSFunction> m_numberProtoToStringFunction;
    WriteBarrier<JSFunction> m_newPromiseCapabilityFunction;
    WriteBarrier<JSFunction> m_functionProtoHasInstanceSymbolFunction;
	WriteBarrier<GetterSetter> m_throwTypeErrorGetterSetter;
    WriteBarrier<GetterSetter> m_throwTypeErrorArgumentsAndCallerGetterSetter;

    WriteBarrier<ModuleLoaderObject> m_moduleLoader;

	WriteBarrier<ObjectPrototype> m_objectPrototype;
	WriteBarrier<FunctionPrototype> m_functionPrototype;
	WriteBarrier<ArrayPrototype> m_arrayPrototype;
	WriteBarrier<RegExpPrototype> m_regExpPrototype;
    WriteBarrier<IteratorPrototype> m_iteratorPrototype;
    WriteBarrier<GeneratorFunctionPrototype> m_generatorFunctionPrototype;
    WriteBarrier<GeneratorPrototype> m_generatorPrototype;

	WriteBarrier<Structure> m_withScopeStructure;
	WriteBarrier<Structure> m_strictEvalActivationStructure;
	WriteBarrier<Structure> m_lexicalEnvironmentStructure;
    WriteBarrier<Structure> m_moduleEnvironmentStructure;
    WriteBarrier<Structure> m_directArgumentsStructure;
    WriteBarrier<Structure> m_scopedArgumentsStructure;
    WriteBarrier<Structure> m_clonedArgumentsStructure;

    WriteBarrier<Structure> m_objectStructureForObjectConstructor;

	// Lists the actual structures used for having these particular indexing shapes.
	WriteBarrier<Structure> m_originalArrayStructureForIndexingShape[NumberOfIndexingShapes];
	// Lists the structures we should use during allocation for these particular indexing shapes.
	// These structures will differ from the originals list above when we are having a bad time.
	WriteBarrier<Structure> m_arrayStructureForIndexingShapeDuringAllocation[NumberOfIndexingShapes];

	WriteBarrier<Structure> m_callbackConstructorStructure;
	WriteBarrier<Structure> m_callbackFunctionStructure;
	WriteBarrier<Structure> m_callbackObjectStructure;
    WriteBarrier<Structure> m_propertyNameIteratorStructure;
	WriteBarrier<Structure> m_nullPrototypeObjectStructure;
    WriteBarrier<Structure> m_calleeStructure;
	WriteBarrier<Structure> m_functionStructure;
	WriteBarrier<Structure> m_boundFunctionStructure;
    WriteBarrier<Structure> m_customGetterSetterFunctionStructure;
	WriteBarrier<Structure> m_namedFunctionStructure;
	PropertyOffset m_functionNameOffset;
	WriteBarrier<Structure> m_privateNameStructure;
	WriteBarrier<Structure> m_regExpStructure;
    WriteBarrier<Structure> m_generatorFunctionStructure;
	WriteBarrier<Structure> m_internalFunctionStructure;
    WriteBarrier<Structure> m_moduleRecordStructure;

    WriteBarrier<Structure> m_iteratorResultObjectStructure;

    WriteBarrier<Structure> m_regExpMatchesArrayStructure;

#define DEFINE_STORAGE_FOR_SIMPLE_TYPE(capitalName, lowerName, properName, instanceType, jsName) \
    WriteBarrier<capitalName ## Prototype> m_ ## lowerName ## Prototype; \
    WriteBarrier<Structure> m_ ## properName ## Structure;

    FOR_EACH_SIMPLE_BUILTIN_TYPE(DEFINE_STORAGE_FOR_SIMPLE_TYPE)
    FOR_EACH_BUILTIN_DERIVED_ITERATOR_TYPE(DEFINE_STORAGE_FOR_SIMPLE_TYPE)

#undef DEFINE_STORAGE_FOR_SIMPLE_TYPE

    WriteBarrier<GetterSetter> m_speciesGetterSetter;

    struct TypedArrayData {
        WriteBarrier<JSObject> prototype;
        WriteBarrier<InternalFunction> constructor;
        WriteBarrier<Structure> structure;
    };

    FixedArray<TypedArrayData, NUMBER_OF_TYPED_ARRAY_TYPES> m_typedArrays;

    JSCell* m_specialPointers[Special::TableSize]; // Special pointers used by the LLInt and JIT.
    JSCell* m_linkTimeConstants[LinkTimeConstantCount];

	Debugger* m_debugger;

    VM& m_vm;

#if ENABLE(INTL)
    HashSet<String> m_intlCollatorAvailableLocales;
    HashSet<String> m_intlDateTimeFormatAvailableLocales;
    HashSet<String> m_intlNumberFormatAvailableLocales;
#endif // ENABLE(INTL)

	RefPtr<WatchpointSet> m_masqueradesAsUndefinedWatchpoint;
	RefPtr<WatchpointSet> m_havingABadTimeWatchpoint;
    RefPtr<WatchpointSet> m_varInjectionWatchpoint;

	OwnPtr<JSGlobalObjectRareData> m_rareData;

    OwnPtr<BuiltinExecutables> m_builtinExecutables;

	WeakRandom m_weakRandom;

	InlineWatchpointSet& arrayIteratorProtocolWatchpoint() { return m_arrayIteratorProtocolWatchpoint; }
	const InlineWatchpointSet& arrayIteratorProtocolWatchpoint() const { return m_arrayIteratorProtocolWatchpoint; }
	InlineWatchpointSet& numberToStringWatchpoint() { return m_numberToStringWatchpoint; }
	const InlineWatchpointSet& numberToStringWatchpoint() const { return m_numberToStringWatchpoint; }
	// If this hasn't been invalidated, it means the array iterator protocol
	// is not observable to user code yet.
	InlineWatchpointSet m_arrayIteratorProtocolWatchpoint;
    InlineWatchpointSet m_numberToStringWatchpoint;

    OwnPtr<ObjectPropertyChangeAdaptiveWatchpoint<InlineWatchpointSet>> m_numberPrototypeToStringWatchpoint;

    TemplateRegistry m_templateRegistry;

    bool isArrayPrototypeIndexedAccessFastAndNonObservable() const;
    bool isArrayPrototypeIteratorProtocolFastAndNonObservable() const;

	bool m_evalEnabled;
	unsigned m_globalLexicalBindingEpoch;
    String m_evalDisabledErrorMessage;
	bool m_experimentsEnabled;

	static JS_EXPORTDATA const GlobalObjectMethodTable s_globalObjectMethodTable;
	const GlobalObjectMethodTable* m_globalObjectMethodTable;

	void createRareDataIfNeeded()
	{
		if (m_rareData)
			return;
		m_rareData = adoptPtr(new JSGlobalObjectRareData);
	}

public:
	typedef JSSegmentedVariableObject Base;

	static JSGlobalObject* create(JSGlobalData& globalData, Structure* structure)
	{
		JSGlobalObject* globalObject = new (NotNull, allocateCell<JSGlobalObject>(globalData.heap)) JSGlobalObject(globalData, structure);
		globalObject->finishCreation(globalData);
		globalData.heap.addFinalizer(globalObject, destroy);
		return globalObject;
	}

	DECLARE_EXPORT_INFO;

    bool hasDebugger() const { return m_debugger; }
    bool hasProfiler() const { return globalObjectMethodTable()->supportsProfiling(this); }

protected:
	JS_EXPORT_PRIVATE explicit JSGlobalObject(JSGlobalData&, Structure*, const GlobalObjectMethodTable* = 0);

	void finishCreation(JSGlobalData& vm)
	{
		Base::finishCreation(vm);
		structure()->setGlobalObject(vm, this);
		m_experimentsEnabled = m_globalObjectMethodTable->javaScriptExperimentsEnabled(this);
		init(vm);
		setGlobalThis(vm, JSProxy::create(vm, JSProxy::createStructure(vm, this, getPrototypeDirect(), PureForwardingProxyType), this));
	}

	void finishCreation(JSGlobalData& vm, JSObject* thisValue)
	{
		Base::finishCreation(vm);
		structure()->setGlobalObject(vm, this);
		m_experimentsEnabled = m_globalObjectMethodTable->javaScriptExperimentsEnabled(this);
		init(vm);
        setGlobalThis(vm, thisValue);
	}

    void addGlobalVar(const Identifier&);

public:
	JS_EXPORT_PRIVATE ~JSGlobalObject();
	JS_EXPORT_PRIVATE static void destroy(JSCell*);
	// We don't need a destructor because we use a finalizer instead.
	static const bool needsDestruction = false;

	JS_EXPORT_PRIVATE static void visitChildren(JSCell*, SlotVisitor&);

	JS_EXPORT_PRIVATE static bool getOwnPropertySlot(JSObject*, ExecState*, PropertyName, PropertySlot&);
	JS_EXPORT_PRIVATE static bool put(JSCell*, ExecState*, PropertyName, JSValue, PutPropertySlot&);

	JS_EXPORT_PRIVATE static void defineGetter(JSObject*, ExecState*, PropertyName, JSObject* getterFunc, unsigned attributes);
	JS_EXPORT_PRIVATE static void defineSetter(JSObject*, ExecState*, PropertyName, JSObject* setterFunc, unsigned attributes);
	JS_EXPORT_PRIVATE static bool defineOwnProperty(JSObject*, ExecState*, PropertyName, const PropertyDescriptor&, bool shouldThrow);

    void addVar(ExecState* exec, const Identifier& propertyName)
    {
        if (!hasOwnProperty(exec, propertyName))
            addGlobalVar(propertyName);
    }
    void addFunction(ExecState*, const Identifier&);

    JSScope* globalScope() { return m_globalLexicalEnvironment.get(); }
    JSGlobalLexicalEnvironment* globalLexicalEnvironment() { return m_globalLexicalEnvironment.get(); }

	// The following accessors return pristine values, even if a script
	// replaces the global object's associated property.

    GetterSetter* speciesGetterSetter() const { return m_speciesGetterSetter.get(); }

	RegExpConstructor* regExpConstructor() const { return m_regExpConstructor.get(); }

	ErrorConstructor* errorConstructor() const { return m_errorConstructor.get(); }
	ArrayConstructor* arrayConstructor() const { return m_arrayConstructor.get(); }
	ObjectConstructor* objectConstructor() const { return m_objectConstructor.get(); }
	JSPromiseConstructor* promiseConstructor() const { return m_promiseConstructor.get(); }
	JSInternalPromiseConstructor* internalPromiseConstructor() const { return m_internalPromiseConstructor.get(); }
	NativeErrorConstructor* evalErrorConstructor() const { return m_evalErrorConstructor.get(); }
	NativeErrorConstructor* rangeErrorConstructor() const { return m_rangeErrorConstructor.get(); }
	NativeErrorConstructor* referenceErrorConstructor() const { return m_referenceErrorConstructor.get(); }
	NativeErrorConstructor* syntaxErrorConstructor() const { return m_syntaxErrorConstructor.get(); }
	NativeErrorConstructor* typeErrorConstructor() const { return m_typeErrorConstructor.get(); }
	NativeErrorConstructor* URIErrorConstructor() const { return m_URIErrorConstructor.get(); }

    JSFunction* parseIntFunction() const { return m_parseIntFunction.get(); }

    NullGetterFunction* nullGetterFunction() const { return m_nullGetterFunction.get(); }
    NullSetterFunction* nullSetterFunction() const { return m_nullSetterFunction.get(); }

	JSFunction* evalFunction() const { return m_evalFunction.get(); }
	JSFunction* callFunction() const { return m_callFunction.get(); }
	JSFunction* applyFunction() const { return m_applyFunction.get(); }
	JSFunction* definePropertyFunction() const { return m_definePropertyFunction.get(); }
	JSFunction* arrayProtoToStringFunction() const { return m_arrayProtoToStringFunction.get(); }
	JSFunction* arrayProtoValuesFunction() const { return m_arrayProtoValuesFunction.get(); }
	JSFunction* initializePromiseFunction() const { return m_initializePromiseFunction.get(); }
	JSFunction* numberProtoToStringFunction() const { return m_numberProtoToStringFunction.get(); }
	JSFunction* newPromiseCapabilityFunction() const { return m_newPromiseCapabilityFunction.get(); }
	JSFunction* functionProtoHasInstanceSymbolFunction() const { return m_functionProtoHasInstanceSymbolFunction.get(); }
	GetterSetter* throwTypeErrorGetterSetter(JSGlobalData& vm)
	{
		if (!m_throwTypeErrorGetterSetter)
			createThrowTypeError(vm);
		return m_throwTypeErrorGetterSetter.get();
	}

    GetterSetter* throwTypeErrorArgumentsAndCallerGetterSetter(VM& vm)
    {
        if (!m_throwTypeErrorArgumentsAndCallerGetterSetter)
            createThrowTypeErrorArgumentsAndCaller(vm);
        return m_throwTypeErrorArgumentsAndCallerGetterSetter.get();
    }

    ModuleLoaderObject* moduleLoader() const { return m_moduleLoader.get(); }

	ObjectPrototype* objectPrototype() const { return m_objectPrototype.get(); }
	FunctionPrototype* functionPrototype() const { return m_functionPrototype.get(); }
	ArrayPrototype* arrayPrototype() const { return m_arrayPrototype.get(); }
	BooleanPrototype* booleanPrototype() const { return m_booleanPrototype.get(); }
	StringPrototype* stringPrototype() const { return m_stringPrototype.get(); }
    SymbolPrototype* symbolPrototype() const { return m_symbolPrototype.get(); }
	NumberPrototype* numberPrototype() const { return m_numberPrototype.get(); }
	DatePrototype* datePrototype() const { return m_datePrototype.get(); }
	RegExpPrototype* regExpPrototype() const { return m_regExpPrototype.get(); }
	ErrorPrototype* errorPrototype() const { return m_errorPrototype.get(); }
	IteratorPrototype* iteratorPrototype() const { return m_iteratorPrototype.get(); }
	GeneratorFunctionPrototype* generatorFunctionPrototype() const { return m_generatorFunctionPrototype.get(); }
	GeneratorPrototype* generatorPrototype() const { return m_generatorPrototype.get(); }

	Structure* withScopeStructure() const { return m_withScopeStructure.get(); }
	Structure* strictEvalActivationStructure() const { return m_strictEvalActivationStructure.get(); }
	Structure* activationStructure() const { return m_lexicalEnvironmentStructure.get(); }
	Structure* moduleEnvironmentStructure() const { return m_moduleEnvironmentStructure.get(); }
	Structure* directArgumentsStructure() const { return m_directArgumentsStructure.get(); }
	Structure* scopedArgumentsStructure() const { return m_scopedArgumentsStructure.get(); }
	Structure* clonedArgumentsStructure() const { return m_clonedArgumentsStructure.get(); }
	Structure* objectStructureForObjectConstructor() const { return m_objectStructureForObjectConstructor.get(); }
	Structure* originalArrayStructureForIndexingType(IndexingType indexingType) const
	{
		ASSERT(indexingType & IsArray);
		return m_originalArrayStructureForIndexingShape[(indexingType & IndexingShapeMask) >> IndexingShapeShift].get();
	}
	Structure* arrayStructureForIndexingTypeDuringAllocation(IndexingType indexingType) const
	{
		ASSERT(indexingType & IsArray);
		return m_arrayStructureForIndexingShapeDuringAllocation[(indexingType & IndexingShapeMask) >> IndexingShapeShift].get();
	}
    Structure* arrayStructureForIndexingTypeDuringAllocation(ExecState* exec, IndexingType indexingType, JSValue newTarget) const
    {
        return InternalFunction::createSubclassStructure(exec, newTarget, arrayStructureForIndexingTypeDuringAllocation(indexingType));
    }
    Structure* arrayStructureForProfileDuringAllocation(ExecState* exec, ArrayAllocationProfile* profile, JSValue newTarget) const
    {
        return arrayStructureForIndexingTypeDuringAllocation(exec, ArrayAllocationProfile::selectIndexingTypeFor(profile), newTarget);
    }

	bool isOriginalArrayStructure(Structure* structure)
	{
		return originalArrayStructureForIndexingType(structure->indexingType() | IsArray) == structure;
	}

	Structure* booleanObjectStructure() const { return m_booleanObjectStructure.get(); }
	Structure* callbackConstructorStructure() const { return m_callbackConstructorStructure.get(); }
	Structure* callbackFunctionStructure() const { return m_callbackFunctionStructure.get(); }
	Structure* callbackObjectStructure() const { return m_callbackObjectStructure.get(); }
	Structure* propertyNameIteratorStructure() const { return m_propertyNameIteratorStructure.get(); }
	Structure* dateStructure() const { return m_dateStructure.get(); }
	Structure* nullPrototypeObjectStructure() const { return m_nullPrototypeObjectStructure.get(); }
	Structure* errorStructure() const { return m_errorStructure.get(); }
    Structure* calleeStructure() const { return m_calleeStructure.get(); }
	Structure* functionStructure() const { return m_functionStructure.get(); }
	Structure* boundFunctionStructure() const { return m_boundFunctionStructure.get(); }
	Structure* customGetterSetterFunctionStructure() const { return m_customGetterSetterFunctionStructure.get(); }
	Structure* namedFunctionStructure() const { return m_namedFunctionStructure.get(); }
	PropertyOffset functionNameOffset() const { return m_functionNameOffset; }
	Structure* numberObjectStructure() const { return m_numberObjectStructure.get(); }
	Structure* privateNameStructure() const { return m_privateNameStructure.get(); }
	Structure* internalFunctionStructure() const { return m_internalFunctionStructure.get(); }
	Structure* mapStructure() const { return m_mapStructure.get(); }
	Structure* regExpStructure() const { return m_regExpStructure.get(); }
	Structure* generatorFunctionStructure() const { return m_generatorFunctionStructure.get(); }
	Structure* stringObjectStructure() const { return m_stringObjectStructure.get(); }
	Structure* symbolObjectStructure() const { return m_symbolObjectStructure.get(); }
	Structure* iteratorResultObjectStructure() const { return m_iteratorResultObjectStructure.get(); }
	Structure* regExpMatchesArrayStructure() const { return m_regExpMatchesArrayStructure.get(); }
	Structure* proxyObjectStructure() const { return m_proxyObjectStructure.get(); }
	Structure* callableProxyObjectStructure() const { return m_callableProxyObjectStructure.get(); }
    Structure* proxyRevokeStructure() const { return m_proxyRevokeStructure.get(); }
	Structure* moduleRecordStructure() const { return m_moduleRecordStructure.get(); }

#if ENABLE(INTL)
    const HashSet<String>& intlCollatorAvailableLocales();
    const HashSet<String>& intlDateTimeFormatAvailableLocales();
    const HashSet<String>& intlNumberFormatAvailableLocales();
#endif // ENABLE(INTL)

    JSArrayBufferPrototype* arrayBufferPrototype() const { return m_arrayBufferPrototype.get(); }

#define DEFINE_ACCESSORS_FOR_SIMPLE_TYPE(capitalName, lowerName, properName, instanceType, jsName) \
    Structure* properName ## Structure() { return m_ ## properName ## Structure.get(); }

    FOR_EACH_SIMPLE_BUILTIN_TYPE(DEFINE_ACCESSORS_FOR_SIMPLE_TYPE)
    FOR_EACH_BUILTIN_DERIVED_ITERATOR_TYPE(DEFINE_ACCESSORS_FOR_SIMPLE_TYPE)

#undef DEFINE_ACCESSORS_FOR_SIMPLE_TYPE

    Structure* typedArrayStructure(TypedArrayType type) const
    {
        return m_typedArrays[toIndex(type)].structure.get();
    }

    bool isOriginalTypedArrayStructure(Structure* structure)
    {
        TypedArrayType type = structure->classInfo()->typedArrayStorageType;
        if (type == NotTypedArray)
            return false;
        return typedArrayStructure(type) == structure;
    }

    JSObject* typedArrayConstructor(TypedArrayType type) const
    {
        return m_typedArrays[toIndex(type)].constructor.get();
    }

    JSCell* actualPointerFor(Special::Pointer pointer)
    {
        ASSERT(pointer < Special::TableSize);
        return m_specialPointers[pointer];
    }
    JSCell* jsCellForLinkTimeConstant(LinkTimeConstant type)
    {
        unsigned index = static_cast<unsigned>(type);
        ASSERT(index < LinkTimeConstantCount);
        return m_linkTimeConstants[index];
    }

	WatchpointSet* masqueradesAsUndefinedWatchpoint() { return m_masqueradesAsUndefinedWatchpoint.get(); }
	WatchpointSet* havingABadTimeWatchpoint() { return m_havingABadTimeWatchpoint.get(); }
	WatchpointSet* varInjectionWatchpoint() { return m_varInjectionWatchpoint.get(); }

	bool isHavingABadTime() const
	{
		return m_havingABadTimeWatchpoint->hasBeenInvalidated();
	}

	void haveABadTime(JSGlobalData&);

    bool objectPrototypeIsSane() const;
    bool arrayPrototypeChainIsSane() const;
    bool stringPrototypeChainIsSane() const;

	void setProfileGroup(unsigned value) { createRareDataIfNeeded(); m_rareData->profileGroup = value; }
	unsigned profileGroup() const
	{
		if (!m_rareData)
			return 0;
		return m_rareData->profileGroup;
	}

	Debugger* debugger() const { return m_debugger; }
	void setDebugger(Debugger* debugger) { m_debugger = debugger; }

	const GlobalObjectMethodTable* globalObjectMethodTable() const { return m_globalObjectMethodTable; }

	static bool supportsProfiling(const JSGlobalObject*) { return false; }
	static bool supportsRichSourceInfo(const JSGlobalObject*) { return true; }

	JS_EXPORT_PRIVATE ExecState* globalExec();

	static bool shouldInterruptScript(const JSGlobalObject*) { return true; }
	static bool javaScriptExperimentsEnabled(const JSGlobalObject*) { return false; }

    void queueMicrotask(PassRefPtr<Microtask>);

    bool evalEnabled() const { return m_evalEnabled; }
    const String& evalDisabledErrorMessage() const { return m_evalDisabledErrorMessage; }
    void setEvalEnabled(bool enabled, const String& errorMessage = String())
    {
        m_evalEnabled = enabled;
        m_evalDisabledErrorMessage = errorMessage;
    }

	void resetPrototype(JSGlobalData&, JSValue prototype);

	JSGlobalData& globalData() const { return m_vm; }
	JSGlobalData& vm() const { return m_vm; }
	JSObject* globalThis() const;

	static Structure* createStructure(JSGlobalData& globalData, JSValue prototype)
	{
		Structure* result = Structure::create(globalData, 0, prototype, TypeInfo(GlobalObjectType, StructureFlags), info());
		result->setTransitionWatchpointIsLikelyToBeFired(true);
		return result;
	}

	void registerWeakMap(OpaqueJSWeakObjectMap* map)
	{
		createRareDataIfNeeded();
		m_rareData->weakMaps.add(map);
	}

	void unregisterWeakMap(OpaqueJSWeakObjectMap* map)
	{
		if (m_rareData)
			m_rareData->weakMaps.remove(map);
	}

    OpaqueJSClassDataMap& opaqueJSClassData()
    {
        createRareDataIfNeeded();
        return m_rareData->opaqueJSClassData;
    }

    TemplateRegistry& templateRegistry() { return m_templateRegistry; }

    static ptrdiff_t weakRandomOffset() { return OBJECT_OFFSETOF(JSGlobalObject, m_weakRandom); }
	double weakRandomNumber() { return m_weakRandom.get(); }
	unsigned weakRandomInteger() { return m_weakRandom.getUint32(); }

    BuiltinExecutables* builtinExecutables() { return m_builtinExecutables.get(); }

    bool needsSiteSpecificQuirks() const { return m_needsSiteSpecificQuirks; }

protected:

	static const unsigned StructureFlags = Base::StructureFlags | HasStaticPropertyTable | OverridesGetOwnPropertySlot | OverridesGetPropertyNames | OverridesToThis | IsImmutablePrototypeExoticObject;

	struct GlobalPropertyInfo {
		GlobalPropertyInfo(const Identifier& i, JSValue v, unsigned a)
			: identifier(i)
			, value(v)
			, attributes(a)
		{
		}

		const Identifier identifier;
		JSValue value;
		unsigned attributes;
	};
	JS_EXPORT_PRIVATE void addStaticGlobals(GlobalPropertyInfo*, int count);

    JS_EXPORT_PRIVATE static JSC::JSValue toThis(JSC::JSCell*, JSC::ExecState*, ECMAMode);

    void setNeedsSiteSpecificQuirks(bool needQuirks) { m_needsSiteSpecificQuirks = needQuirks; }

private:
	friend class LLIntOffsetsExtractor;

    void fireWatchpointAndMakeAllArrayStructuresSlowPut(VM&);
    JS_EXPORT_PRIVATE void setGlobalThis(VM&, JSObject* globalThis);

	// FIXME: Fold reset into init.
	JS_EXPORT_PRIVATE void init(JSGlobalData&);
	void reset(JSValue prototype);

	void createThrowTypeError(VM&);
    void createThrowTypeErrorArgumentsAndCaller(VM&);

	JS_EXPORT_PRIVATE static void clearRareData(JSCell*);

    bool m_needsSiteSpecificQuirks;
};

JSGlobalObject* asGlobalObject(JSValue);

ALWAYS_INLINE JSGlobalObject* asGlobalObject(JSValue value)
{
	ASSERT(asObject(value)->isGlobalObject());
	return jsCast<JSGlobalObject*>(asObject(value));
}

inline JSGlobalObject* ExecState::dynamicGlobalObject()
{
	if (this == lexicalGlobalObject()->globalExec())
		return lexicalGlobalObject();

	// For any ExecState that's not a globalExec, the
	// dynamic global object must be set since code is running
	ASSERT(globalData().dynamicGlobalObject);
	return globalData().dynamicGlobalObject;
}

inline JSArray* constructEmptyArray(ExecState* exec, ArrayAllocationProfile* profile, JSGlobalObject* globalObject, unsigned initialLength = 0, JSValue newTarget = JSValue())
{
	VM& vm = globalObject->vm();
    Structure* structure;
    if (initialLength >= MIN_ARRAY_STORAGE_CONSTRUCTION_LENGTH)
        structure = globalObject->arrayStructureForIndexingTypeDuringAllocation(exec, ArrayWithArrayStorage, newTarget);
    else
        structure = globalObject->arrayStructureForProfileDuringAllocation(exec, profile, newTarget);
	RETURN_IF_EXCEPTION(vm, 0);

    return ArrayAllocationProfile::updateLastAllocationFor(profile, JSArray::create(vm, structure, initialLength));
}

inline JSArray* constructEmptyArray(ExecState* exec, ArrayAllocationProfile* profile, unsigned initialLength = 0, JSValue newTarget = JSValue())
{
    return constructEmptyArray(exec, profile, exec->lexicalGlobalObject(), initialLength, newTarget);
}

inline JSArray* constructArray(ExecState* exec, ArrayAllocationProfile* profile, JSGlobalObject* globalObject, const ArgList& values, JSValue newTarget = JSValue())
{
	VM& vm = globalObject->vm();
	Structure* structure = globalObject->arrayStructureForProfileDuringAllocation(exec, profile, newTarget);
	RETURN_IF_EXCEPTION(vm, 0);
    return ArrayAllocationProfile::updateLastAllocationFor(profile, constructArray(vm, structure, values));
}

inline JSArray* constructArray(ExecState* exec, ArrayAllocationProfile* profile, const ArgList& values, JSValue newTarget = JSValue())
{
    return constructArray(exec, profile, exec->lexicalGlobalObject(), values, newTarget);
}

inline JSArray* constructArray(ExecState* exec, ArrayAllocationProfile* profile, JSGlobalObject* globalObject, const JSValue* values, unsigned length, JSValue newTarget = JSValue())
{
	VM& vm = globalObject->vm();
	Structure* structure = globalObject->arrayStructureForProfileDuringAllocation(exec, profile, newTarget);
	RETURN_IF_EXCEPTION(vm, 0);
    return ArrayAllocationProfile::updateLastAllocationFor(profile, constructArray(vm, structure, values, length));
}

inline JSArray* constructArray(ExecState* exec, ArrayAllocationProfile* profile, const JSValue* values, unsigned length, JSValue newTarget = JSValue())
{
    return constructArray(exec, profile, exec->lexicalGlobalObject(), values, length, newTarget);
}

inline JSArray* constructArrayNegativeIndexed(ExecState* exec, ArrayAllocationProfile* profile, JSGlobalObject* globalObject, const JSValue* values, unsigned length, JSValue newTarget = JSValue())
{
	VM& vm = globalObject->vm();
	Structure* structure = globalObject->arrayStructureForProfileDuringAllocation(exec, profile, newTarget);
	RETURN_IF_EXCEPTION(vm, 0);
    return ArrayAllocationProfile::updateLastAllocationFor(profile, constructArrayNegativeIndexed(vm, structure, values, length));
}

inline JSArray* constructArrayNegativeIndexed(ExecState* exec, ArrayAllocationProfile* profile, const JSValue* values, unsigned length, JSValue newTarget = JSValue())
{
    return constructArrayNegativeIndexed(exec, profile, exec->lexicalGlobalObject(), values, length, newTarget);
}

class DynamicGlobalObjectScope {
	WTF_MAKE_NONCOPYABLE(DynamicGlobalObjectScope);
public:
	JS_EXPORT_PRIVATE DynamicGlobalObjectScope(JSGlobalData&, JSGlobalObject*);

	~DynamicGlobalObjectScope()
	{
		m_dynamicGlobalObjectSlot = m_savedDynamicGlobalObject;
	}

private:
	JSGlobalObject*& m_dynamicGlobalObjectSlot;
	JSGlobalObject* m_savedDynamicGlobalObject;
};

ALWAYS_INLINE JSObject* ExecState::globalThisValue() const
{
    return lexicalGlobalObject()->globalThis();
}

ALWAYS_INLINE JSObject* JSScope::globalThis()
{
	return globalObject()->globalThis();
}

ALWAYS_INLINE JSObject* JSGlobalObject::globalThis() const
{
	return m_globalThis.get();
}

ALWAYS_INLINE bool JSGlobalObject::isArrayPrototypeIndexedAccessFastAndNonObservable() const
{
    // We're fast if we don't have any indexed properties on the prototype.
    return !isHavingABadTime() && arrayPrototypeChainIsSane();
}

ALWAYS_INLINE bool JSGlobalObject::isArrayPrototypeIteratorProtocolFastAndNonObservable() const
{
    // We're fast if we don't have any indexed properties on the prototype.
    // We're non-observable if the iteration protocol hasn't changed.
    //
    // Note: it only makes sense to call this from the main thread. If you're
    // trying to prove this behavior on the compiler thread, you'll want to
    // carefully set up watchpoints to have correct ordering while JS code is
    // executing concurrently.

    return arrayIteratorProtocolWatchpoint().isStillValid() && isArrayPrototypeIndexedAccessFastAndNonObservable();
}

} // namespace JSC

#endif // JSGlobalObject_h
