drop script and declarative components aswell as tray support

Signed-off-by: Ivailo Monev <xakepa10@gmail.com>
This commit is contained in:
Ivailo Monev 2023-10-19 15:24:41 +03:00
parent c52e34c91e
commit 770f63fa3b
851 changed files with 83 additions and 244922 deletions

View file

@ -98,14 +98,13 @@ endif()
set(KATIE_TYPE SHARED CACHE STRING "Build type")
# components and tools that will be build, changed depending on the requirements availability
set(KATIE_COMPONENTS "Core Gui Declarative Network Svg Xml Script Test UiTools")
set(KATIE_TOOLS "moc uic qscript")
set(KATIE_COMPONENTS "Core Gui Network Svg Xml Test UiTools")
set(KATIE_TOOLS "moc uic")
set(KATIE_HEADERS_PATH "${CMAKE_INSTALL_FULL_INCLUDEDIR}/katie" CACHE PATH "Headers installation path")
set(KATIE_LIBRARIES_PATH "${CMAKE_INSTALL_FULL_LIBDIR}" CACHE PATH "Libraries installation path")
set(KATIE_BINARIES_PATH "${CMAKE_INSTALL_FULL_BINDIR}" CACHE PATH "Binaries installation path")
set(KATIE_PLUGINS_PATH "${KATIE_LIBRARIES_PATH}/katie/plugins" CACHE PATH "Plugins installation path")
set(KATIE_IMPORTS_PATH "${KATIE_LIBRARIES_PATH}/katie/imports" CACHE PATH "Declarative imports installation path")
set(KATIE_TRANSLATIONS_PATH "${CMAKE_INSTALL_FULL_DATADIR}/translations" CACHE PATH "Translations installation path")
set(KATIE_CMAKE_PATH "${KATIE_LIBRARIES_PATH}/cmake/Katie" CACHE PATH "CMake aware modules installation path")
set(KATIE_LDCONF_PATH "${CMAKE_INSTALL_FULL_SYSCONFDIR}/ld.so.conf.d" CACHE PATH "Run-time linker/loader configs installation path")
@ -317,22 +316,18 @@ if(NSL_LIBRARY)
)
endif()
# used in components, tests and JavaScriptCore
# used in components and tests
katie_check_header("cxxabi.h")
katie_check_function(posix_memalign "stdlib.h")
katie_check_function(getprogname "stdlib.h")
katie_check_function(arc4random_uniform "stdlib.h")
katie_check_function(get_current_dir_name "unistd.h")
katie_check_function(prctl "sys/prctl.h")
katie_check_function(feenableexcept "fenv.h")
katie_check_function(madvise "sys/mman.h")
katie_check_function(timegm "time.h")
katie_check_function(pipe2 "unistd.h")
katie_check_function(getdomainname "unistd.h")
katie_check_function(renameat2 "stdio.h")
katie_check_function(program_invocation_short_name "errno.h")
katie_check_function(flock "sys/file.h")
katie_check_struct(tm tm_gmtoff "time.h")
katie_check_struct(tm tm_zone "time.h")
katie_check_struct(dirent d_type "dirent.h")
@ -437,12 +432,9 @@ add_subdirectory(src/xml)
if(WITH_DBUS AND DBUS_FOUND)
add_subdirectory(src/dbus)
endif()
add_subdirectory(src/declarative)
add_subdirectory(src/gui)
add_subdirectory(src/imports)
add_subdirectory(src/network)
add_subdirectory(src/plugins)
add_subdirectory(src/script)
add_subdirectory(src/svg)
add_subdirectory(src/test)
add_subdirectory(src/uitools)

3
README
View file

@ -8,7 +8,8 @@ There are several things you should be aware before considering Katie:
- QMake, Linguist, Assistant, checksdk, macdeployqt, pixeltool, qconfig,
qdoc, qev, qvfb, runonphone, designer and other non-essential
- Qt3Support, QtWebKit, QtHelp, QtXmlPatterns, QtOpenGL, ActiveQt, Phonon,
QtMultimedia, QtSql, QtDesigner, QtDesignerComponents and QtScriptTtools
QtMultimedia, QtSql, QtDesigner, QtDesignerComponents, QtScriptTtools,
QtScript and QtDeclarative
- some things have changed:
- QMake build system replaced with CMake

View file

@ -29,7 +29,6 @@ if(NOT KATIE_FOUND)
set(KATIE_LIBRARIES_PATH "@KATIE_LIBRARIES_PATH@")
set(KATIE_BINARIES_PATH "@KATIE_BINARIES_PATH@")
set(KATIE_PLUGINS_PATH "@KATIE_PLUGINS_PATH@")
set(KATIE_IMPORTS_PATH "@KATIE_IMPORTS_PATH@")
set(KATIE_TRANSLATIONS_PATH "@KATIE_TRANSLATIONS_PATH@")
set(KATIE_LDCONF_PATH "@KATIE_LDCONF_PATH@")
set(KATIE_PROFILE_PATH "@KATIE_PROFILE_PATH@")
@ -98,7 +97,6 @@ if(NOT KATIE_FOUND)
set(QT_LIBRARY_DIR ${KATIE_LIBRARIES_PATH})
set(QT_BINARY_DIR ${KATIE_BINARIES_PATH})
set(QT_PLUGINS_DIR ${KATIE_PLUGINS_PATH})
set(QT_IMPORTS_DIR ${KATIE_IMPORTS_PATH})
set(QT_TRANSLATIONS_DIR ${KATIE_TRANSLATIONS_PATH})
# those are exceptions because they have "q" prefix which the macros from Qt4Macros do not expect

View file

@ -35,9 +35,7 @@ set(unifdef_arguments
-UKtNetwork_EXPORTS
-UKtSvg_EXPORTS
-UKtTest_EXPORTS
-UKtDeclarative_EXPORTS
-UKtXml_EXPORTS
-UKtScript_EXPORTS
-UKtDBus_EXPORTS
-UKtUiTools_EXPORTS
)

View file

@ -31,8 +31,8 @@ Description: C++ toolkit derived from the Qt 4.8 framework
clean it up, fix some bugs and backport some features from Qt5. It is based
on the latest Git revision of Qt v4.8.
.
This package includes designer, moc, qdbus, qdbuscpp2xml, qdbusviewer,
qdbusxml2cpp, qscript, trc, rcc, and uic
This package includes moc, qdbus, qdbuscpp2xml, qdbusxml2cpp, qdbusviewer,
trc, rcc, and uic
Package: katie-dev
Architecture: amd64 arm64 armel armhf i386 mips mips64el mipsel ppc64el s390x hurd-i386

View file

@ -3,7 +3,6 @@ bin/qdbus-katie
bin/qdbuscpp2xml-katie
bin/qdbusviewer-katie
bin/qdbusxml2cpp-katie
bin/qscript-katie
bin/trc-katie
bin/uic-katie
include/katie/QtCore/QAbstractEventDispatcher
@ -297,49 +296,6 @@ include/katie/QtDBus/qdbusreply.h
include/katie/QtDBus/qdbusserver.h
include/katie/QtDBus/qdbusservicewatcher.h
include/katie/QtDBus/qdbusunixfiledescriptor.h
include/katie/QtDeclarative/QDeclarativeAttachedPropertiesFunc
include/katie/QtDeclarative/QDeclarativeComponent
include/katie/QtDeclarative/QDeclarativeContext
include/katie/QtDeclarative/QDeclarativeEngine
include/katie/QtDeclarative/QDeclarativeError
include/katie/QtDeclarative/QDeclarativeExpression
include/katie/QtDeclarative/QDeclarativeExtensionInterface
include/katie/QtDeclarative/QDeclarativeExtensionPlugin
include/katie/QtDeclarative/QDeclarativeImageProvider
include/katie/QtDeclarative/QDeclarativeInfo
include/katie/QtDeclarative/QDeclarativeItem
include/katie/QtDeclarative/QDeclarativeListProperty
include/katie/QtDeclarative/QDeclarativeListReference
include/katie/QtDeclarative/QDeclarativeParserStatus
include/katie/QtDeclarative/QDeclarativeProperties
include/katie/QtDeclarative/QDeclarativeProperty
include/katie/QtDeclarative/QDeclarativePropertyMap
include/katie/QtDeclarative/QDeclarativePropertyValueInterceptor
include/katie/QtDeclarative/QDeclarativePropertyValueSource
include/katie/QtDeclarative/QDeclarativeScriptString
include/katie/QtDeclarative/QDeclarativeTypeInfo
include/katie/QtDeclarative/QDeclarativeView
include/katie/QtDeclarative/QtDeclarative
include/katie/QtDeclarative/qdeclarative.h
include/katie/QtDeclarative/qdeclarativecomponent.h
include/katie/QtDeclarative/qdeclarativecontext.h
include/katie/QtDeclarative/qdeclarativeengine.h
include/katie/QtDeclarative/qdeclarativeerror.h
include/katie/QtDeclarative/qdeclarativeexpression.h
include/katie/QtDeclarative/qdeclarativeextensioninterface.h
include/katie/QtDeclarative/qdeclarativeextensionplugin.h
include/katie/QtDeclarative/qdeclarativeimageprovider.h
include/katie/QtDeclarative/qdeclarativeinfo.h
include/katie/QtDeclarative/qdeclarativeitem.h
include/katie/QtDeclarative/qdeclarativelist.h
include/katie/QtDeclarative/qdeclarativeparserstatus.h
include/katie/QtDeclarative/qdeclarativeprivate.h
include/katie/QtDeclarative/qdeclarativeproperty.h
include/katie/QtDeclarative/qdeclarativepropertymap.h
include/katie/QtDeclarative/qdeclarativepropertyvalueinterceptor.h
include/katie/QtDeclarative/qdeclarativepropertyvaluesource.h
include/katie/QtDeclarative/qdeclarativescriptstring.h
include/katie/QtDeclarative/qdeclarativeview.h
include/katie/QtGui/QAbstractAnimation
include/katie/QtGui/QAbstractButton
include/katie/QtGui/QAbstractGraphicsShapeItem
@ -606,7 +562,6 @@ include/katie/QtGui/QStylePainter
include/katie/QtGui/QStylePlugin
include/katie/QtGui/QStyledItemDelegate
include/katie/QtGui/QSyntaxHighlighter
include/katie/QtGui/QSystemTrayIcon
include/katie/QtGui/QTabBar
include/katie/QtGui/QTabWidget
include/katie/QtGui/QTableView
@ -836,7 +791,6 @@ include/katie/QtGui/qstyleoption.h
include/katie/QtGui/qstylepainter.h
include/katie/QtGui/qstyleplugin.h
include/katie/QtGui/qsyntaxhighlighter.h
include/katie/QtGui/qsystemtrayicon.h
include/katie/QtGui/qtabbar.h
include/katie/QtGui/qtableview.h
include/katie/QtGui/qtablewidget.h
@ -901,36 +855,6 @@ include/katie/QtNetwork/qnetworkinterface.h
include/katie/QtNetwork/qtcpserver.h
include/katie/QtNetwork/qtcpsocket.h
include/katie/QtNetwork/qudpsocket.h
include/katie/QtScript/QScriptClass
include/katie/QtScript/QScriptClassPropertyIterator
include/katie/QtScript/QScriptContext
include/katie/QtScript/QScriptContextInfo
include/katie/QtScript/QScriptContextInfoList
include/katie/QtScript/QScriptEngine
include/katie/QtScript/QScriptEngineAgent
include/katie/QtScript/QScriptExtensionInterface
include/katie/QtScript/QScriptExtensionPlugin
include/katie/QtScript/QScriptProgram
include/katie/QtScript/QScriptString
include/katie/QtScript/QScriptSyntaxCheckResult
include/katie/QtScript/QScriptValue
include/katie/QtScript/QScriptValueIterator
include/katie/QtScript/QScriptValueList
include/katie/QtScript/QScriptable
include/katie/QtScript/QtScript
include/katie/QtScript/qscriptable.h
include/katie/QtScript/qscriptclass.h
include/katie/QtScript/qscriptclasspropertyiterator.h
include/katie/QtScript/qscriptcontext.h
include/katie/QtScript/qscriptcontextinfo.h
include/katie/QtScript/qscriptengine.h
include/katie/QtScript/qscriptengineagent.h
include/katie/QtScript/qscriptextensioninterface.h
include/katie/QtScript/qscriptextensionplugin.h
include/katie/QtScript/qscriptprogram.h
include/katie/QtScript/qscriptstring.h
include/katie/QtScript/qscriptvalue.h
include/katie/QtScript/qscriptvalueiterator.h
include/katie/QtSvg/QSvgRenderer
include/katie/QtSvg/QtSvg
include/katie/QtSvg/qsvgrenderer.h
@ -1036,31 +960,19 @@ lib/cmake/Katie/KatieConfigVersion.cmake
lib/cmake/Katie/KatieTargets-%%CMAKE_BUILD_TYPE%%.cmake
lib/cmake/Katie/KatieTargets.cmake
lib/cmake/Katie/Qt4UseFile.cmake
lib/katie/imports/Qt/labs/folderlistmodel/libqmlfolderlistmodelplugin.so
lib/katie/imports/Qt/labs/folderlistmodel/qmldir
lib/katie/imports/Qt/labs/particles/libqmlparticlesplugin.so
lib/katie/imports/Qt/labs/particles/qmldir
lib/katie/plugins/designer/qdeclarativeview.so
lib/katie/plugins/imageformats/svg.so
lib/katie/plugins/script/qtscriptdbus.so
lib/libKtCore.so
lib/libKtCore.so.4.14
lib/libKtCore.so.4.14.0
lib/libKtDBus.so
lib/libKtDBus.so.4.14
lib/libKtDBus.so.4.14.0
lib/libKtDeclarative.so
lib/libKtDeclarative.so.4.14
lib/libKtDeclarative.so.4.14.0
lib/libKtGui.so
lib/libKtGui.so.4.14
lib/libKtGui.so.4.14.0
lib/libKtNetwork.so
lib/libKtNetwork.so.4.14
lib/libKtNetwork.so.4.14.0
lib/libKtScript.so
lib/libKtScript.so.4.14
lib/libKtScript.so.4.14.0
lib/libKtSvg.so
lib/libKtSvg.so.4.14
lib/libKtSvg.so.4.14.0
@ -1075,10 +987,8 @@ lib/libKtXml.so.4.14
lib/libKtXml.so.4.14.0
libdata/pkgconfig/KtCore.pc
libdata/pkgconfig/KtDBus.pc
libdata/pkgconfig/KtDeclarative.pc
libdata/pkgconfig/KtGui.pc
libdata/pkgconfig/KtNetwork.pc
libdata/pkgconfig/KtScript.pc
libdata/pkgconfig/KtSvg.pc
libdata/pkgconfig/KtTest.pc
libdata/pkgconfig/KtUiTools.pc
@ -1088,7 +998,6 @@ share/man/man1/moc-katie.1.gz
share/man/man1/qdbus-katie.1.gz
share/man/man1/qdbuscpp2xml-katie.1.gz
share/man/man1/qdbusxml2cpp-katie.1.gz
share/man/man1/qscript-katie.1.gz
share/man/man1/trc-katie.1.gz
share/man/man1/uic-katie.1.gz
share/pixmaps/qdbusviewer-katie.png

View file

@ -7,11 +7,9 @@ components = {
'Core': 'Q_CORE_EXPORT',
'Gui': 'Q_GUI_EXPORT',
'DBus': 'Q_DBUS_EXPORT',
'Declarative': 'Q_DECLARATIVE_EXPORT',
'Network': 'Q_NETWORK_EXPORT',
'Svg': 'Q_SVG_EXPORT',
'Xml': 'Q_XML_EXPORT',
'Script': 'Q_SCRIPT_EXPORT',
'Test': 'Q_TEST_EXPORT',
'UiTools': 'Q_UITOOLS_EXPORT',
}

View file

@ -100,13 +100,6 @@ incmap = {
'QDBusSignature': 'qdbusextratypes.h',
'QDBusVariant': 'qdbusextratypes.h',
},
'QtDeclarative': {
'QDeclarativeAttachedPropertiesFunc': 'qdeclarativeprivate.h',
'QDeclarativeListProperty': 'qdeclarativelist.h',
'QDeclarativeListReference': 'qdeclarativelist.h',
'QDeclarativeProperties': 'qdeclarativeproperty.h',
'QDeclarativeTypeInfo': 'qdeclarativeprivate.h',
},
'QtGui': {
'QAbstractGraphicsShapeItem': 'qgraphicsitem.h',
'QAbstractUndoItem': 'qtextdocument.h',

View file

@ -94,28 +94,6 @@ classlist = [
"QDateTime",
"QDateTimeEdit",
"QDebug",
"QDeclarativeAttachedPropertiesFunc",
"QDeclarativeComponent",
"QDeclarativeContext",
"QDeclarativeEngine",
"QDeclarativeError",
"QDeclarativeExpression",
"QDeclarativeExtensionInterface",
"QDeclarativeExtensionPlugin",
"QDeclarativeImageProvider",
"QDeclarativeInfo",
"QDeclarativeItem",
"QDeclarativeListProperty",
"QDeclarativeListReference",
"QDeclarativeParserStatus",
"QDeclarativeProperties",
"QDeclarativeProperty",
"QDeclarativePropertyMap",
"QDeclarativePropertyValueInterceptor",
"QDeclarativePropertyValueSource",
"QDeclarativeScriptString",
"QDeclarativeTypeInfo",
"QDeclarativeView",
"QDesktopWidget",
"QDial",
"QDialog",
@ -381,22 +359,6 @@ classlist = [
"QScopedPointer",
"QScopedPointerPodDeleter",
"QScopedValueRollback",
"QScriptClass",
"QScriptClassPropertyIterator",
"QScriptContext",
"QScriptContextInfo",
"QScriptContextInfoList",
"QScriptEngine",
"QScriptEngineAgent",
"QScriptExtensionInterface",
"QScriptExtensionPlugin",
"QScriptProgram",
"QScriptString",
"QScriptSyntaxCheckResult",
"QScriptValue",
"QScriptValueIterator",
"QScriptValueList",
"QScriptable",
"QScrollArea",
"QScrollBar",
"QSemaphore",
@ -487,7 +449,6 @@ classlist = [
"QStyledItemDelegate",
"QSvgRenderer",
"QSyntaxHighlighter",
"QSystemTrayIcon",
"QTabBar",
"QTabWidget",
"QTableView",
@ -645,7 +606,6 @@ classlist = [
"QtCore",
"QtDBus",
"QtDebug",
"QtDeclarative",
"QtEndian",
"QtEvents",
"QtGlobal",
@ -654,7 +614,6 @@ classlist = [
"QtNetwork",
"QtPlugin",
"QtPluginInstanceFunction",
"QtScript",
"QtSvg",
"QtTest",
"QtTestGui",

View file

@ -2,8 +2,7 @@
import os, glob, subprocess
components = ('core', 'dbus', 'declarative', 'gui', 'network', 'plugins',
'script', 'scripttools', 'svg', 'test', 'uitools', 'xml')
components = ('core', 'dbus', 'gui', 'network', 'plugins', 'svg', 'test', 'uitools', 'xml')
cfiles = []
tfiles = []

4
src/3rdparty/README vendored
View file

@ -7,5 +7,5 @@ are irrelevant to Katie may not be included here. Typically, those are
the standalone library configuration and make files, tools, test
files, contribs, documentation, and similar.
javascriptcore and easing are maintained as part of Katie now with a
lot of changes specific to it.
easing is maintained as part of Katie now with a lot of changes specific
to it.

View file

@ -1,155 +0,0 @@
/*
* Copyright (C) 2006 Apple Computer, Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef APICast_h
#define APICast_h
#include "JSAPIValueWrapper.h"
#include "JSGlobalObject.h"
#include "JSValue.h"
#include <wtf/Platform.h>
namespace JSC {
class ExecState;
class PropertyNameArray;
class JSGlobalData;
class JSObject;
class JSValue;
}
typedef const struct OpaqueJSContextGroup* JSContextGroupRef;
typedef const struct OpaqueJSContext* JSContextRef;
typedef struct OpaqueJSContext* JSGlobalContextRef;
typedef struct OpaqueJSPropertyNameAccumulator* JSPropertyNameAccumulatorRef;
typedef const struct OpaqueJSValue* JSValueRef;
typedef struct OpaqueJSValue* JSObjectRef;
/* Opaque typing convenience methods */
inline JSC::ExecState* toJS(JSContextRef c)
{
Q_ASSERT(c);
return reinterpret_cast<JSC::ExecState*>(const_cast<OpaqueJSContext*>(c));
}
inline JSC::ExecState* toJS(JSGlobalContextRef c)
{
Q_ASSERT(c);
return reinterpret_cast<JSC::ExecState*>(c);
}
inline JSC::JSValue toJS(JSC::ExecState* exec, JSValueRef v)
{
Q_UNUSED(exec);
Q_ASSERT(exec);
Q_ASSERT(v);
#if USE(JSVALUE32_64)
JSC::JSCell* jsCell = reinterpret_cast<JSC::JSCell*>(const_cast<OpaqueJSValue*>(v));
if (!jsCell)
return JSC::JSValue();
if (jsCell->isAPIValueWrapper())
return static_cast<JSC::JSAPIValueWrapper*>(jsCell)->value();
return jsCell;
#else
return JSC::JSValue::decode(reinterpret_cast<JSC::EncodedJSValue>(const_cast<OpaqueJSValue*>(v)));
#endif
}
inline JSC::JSValue toJSForGC(JSC::ExecState* exec, JSValueRef v)
{
Q_UNUSED(exec);
Q_ASSERT(exec);
Q_ASSERT(v);
#if USE(JSVALUE32_64)
JSC::JSCell* jsCell = reinterpret_cast<JSC::JSCell*>(const_cast<OpaqueJSValue*>(v));
if (!jsCell)
return JSC::JSValue();
return jsCell;
#else
return JSC::JSValue::decode(reinterpret_cast<JSC::EncodedJSValue>(const_cast<OpaqueJSValue*>(v)));
#endif
}
inline JSC::JSObject* toJS(JSObjectRef o)
{
return reinterpret_cast<JSC::JSObject*>(o);
}
inline JSC::PropertyNameArray* toJS(JSPropertyNameAccumulatorRef a)
{
return reinterpret_cast<JSC::PropertyNameArray*>(a);
}
inline JSC::JSGlobalData* toJS(JSContextGroupRef g)
{
return reinterpret_cast<JSC::JSGlobalData*>(const_cast<OpaqueJSContextGroup*>(g));
}
inline JSValueRef toRef(JSC::ExecState* exec, JSC::JSValue v)
{
#if USE(JSVALUE32_64)
if (!v)
return 0;
if (!v.isCell())
return reinterpret_cast<JSValueRef>(JSC::jsAPIValueWrapper(exec, v).asCell());
return reinterpret_cast<JSValueRef>(v.asCell());
#else
Q_UNUSED(exec);
return reinterpret_cast<JSValueRef>(JSC::JSValue::encode(v));
#endif
}
inline JSObjectRef toRef(JSC::JSObject* o)
{
return reinterpret_cast<JSObjectRef>(o);
}
inline JSObjectRef toRef(const JSC::JSObject* o)
{
return reinterpret_cast<JSObjectRef>(const_cast<JSC::JSObject*>(o));
}
inline JSContextRef toRef(JSC::ExecState* e)
{
return reinterpret_cast<JSContextRef>(e);
}
inline JSGlobalContextRef toGlobalRef(JSC::ExecState* e)
{
Q_ASSERT(e == e->lexicalGlobalObject()->globalExec());
return reinterpret_cast<JSGlobalContextRef>(e);
}
inline JSPropertyNameAccumulatorRef toRef(JSC::PropertyNameArray* l)
{
return reinterpret_cast<JSPropertyNameAccumulatorRef>(l);
}
inline JSContextGroupRef toRef(JSC::JSGlobalData* g)
{
return reinterpret_cast<JSContextGroupRef>(g);
}
#endif // APICast_h

View file

@ -1,82 +0,0 @@
/*
* Copyright (C) 2009 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef APIShims_h
#define APIShims_h
#include "CallFrame.h"
namespace JSC {
class APIEntryShim {
public:
// Normal API entry
APIEntryShim(ExecState* exec)
: m_globalData(&exec->globalData())
, m_entryIdentifierTable(setCurrentIdentifierTable(m_globalData->identifierTable))
{
m_globalData->timeoutChecker->start();
}
// JSPropertyNameAccumulator only has a globalData.
APIEntryShim(JSGlobalData* globalData)
: m_globalData(globalData)
, m_entryIdentifierTable(setCurrentIdentifierTable(globalData->identifierTable))
{
}
~APIEntryShim()
{
m_globalData->timeoutChecker->stop();
setCurrentIdentifierTable(m_entryIdentifierTable);
}
private:
JSGlobalData* m_globalData;
IdentifierTable* m_entryIdentifierTable;
};
class APICallbackShim {
public:
APICallbackShim(ExecState* exec)
: m_globalData(&exec->globalData())
{
resetCurrentIdentifierTable();
m_globalData->timeoutChecker->start();
}
~APICallbackShim()
{
m_globalData->timeoutChecker->stop();
setCurrentIdentifierTable(m_globalData->identifierTable);
}
private:
JSGlobalData* m_globalData;
};
}
#endif

View file

@ -1,66 +0,0 @@
/*
* Copyright (C) 2006 Apple Computer, Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef JSBase_h
#define JSBase_h
/* JavaScript engine interface */
/*! @typedef JSContextGroupRef A group that associates JavaScript contexts with one another. Contexts in the same group may share and exchange JavaScript objects. */
typedef const struct OpaqueJSContextGroup* JSContextGroupRef;
/*! @typedef JSContextRef A JavaScript execution context. Holds the global object and other execution state. */
typedef const struct OpaqueJSContext* JSContextRef;
/*! @typedef JSGlobalContextRef A global JavaScript execution context. A JSGlobalContext is a JSContext. */
typedef struct OpaqueJSContext* JSGlobalContextRef;
/*! @typedef JSStringRef A UTF16 character buffer. The fundamental string representation in JavaScript. */
typedef struct OpaqueJSString* JSStringRef;
/*! @typedef JSClassRef A JavaScript class. Used with JSObjectMake to construct objects with custom behavior. */
typedef struct OpaqueJSClass* JSClassRef;
/*! @typedef JSPropertyNameArrayRef An array of JavaScript property names. */
typedef struct OpaqueJSPropertyNameArray* JSPropertyNameArrayRef;
/*! @typedef JSPropertyNameAccumulatorRef An ordered set used to collect the names of a JavaScript object's properties. */
typedef struct OpaqueJSPropertyNameAccumulator* JSPropertyNameAccumulatorRef;
/* JavaScript data types */
/*! @typedef JSValueRef A JavaScript value. The base type for all JavaScript values, and polymorphic functions on them. */
typedef const struct OpaqueJSValue* JSValueRef;
/*! @typedef JSObjectRef A JavaScript object. A JSObject is a JSValue. */
typedef struct OpaqueJSValue* JSObjectRef;
/* JavaScript symbol are not exported */
#undef JS_EXPORT
#define JS_EXPORT
#endif /* JSBase_h */

View file

@ -1,86 +0,0 @@
/*
* Copyright (C) 2006, 2007, 2008 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "Platform.h"
#include "JSCallbackConstructor.h"
#include "APIShims.h"
#include "APICast.h"
#include <runtime/JSGlobalObject.h>
#include <runtime/ObjectPrototype.h>
#include <wtf/Vector.h>
namespace JSC {
const ClassInfo JSCallbackConstructor::info = { "CallbackConstructor", 0, 0 };
JSCallbackConstructor::JSCallbackConstructor(NonNullPassRefPtr<Structure> structure, JSClassRef jsClass, JSObjectCallAsConstructorCallback callback)
: JSObject(structure)
, m_class(jsClass)
, m_callback(callback)
{
if (m_class)
JSClassRetain(jsClass);
}
JSCallbackConstructor::~JSCallbackConstructor()
{
if (m_class)
JSClassRelease(m_class);
}
static JSObject* constructJSCallback(ExecState* exec, JSObject* constructor, const ArgList& args)
{
JSContextRef ctx = toRef(exec);
JSObjectRef constructorRef = toRef(constructor);
JSObjectCallAsConstructorCallback callback = static_cast<JSCallbackConstructor*>(constructor)->callback();
if (callback) {
int argumentCount = static_cast<int>(args.size());
Vector<JSValueRef, 16> arguments(argumentCount);
for (int i = 0; i < argumentCount; i++)
arguments[i] = toRef(exec, args.at(i));
JSValueRef exception = 0;
JSObjectRef result;
{
APICallbackShim callbackShim(exec);
result = callback(ctx, constructorRef, argumentCount, arguments.data(), &exception);
}
if (exception)
exec->setException(toJS(exec, exception));
return toJS(result);
}
return toJS(JSObjectMake(ctx, static_cast<JSCallbackConstructor*>(constructor)->classRef(), 0));
}
ConstructType JSCallbackConstructor::getConstructData(ConstructData& constructData)
{
constructData.native.function = constructJSCallback;
return ConstructTypeHost;
}
} // namespace JSC

View file

@ -1,60 +0,0 @@
/*
* Copyright (C) 2006, 2008 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef JSCallbackConstructor_h
#define JSCallbackConstructor_h
#include "JSObjectRef.h"
#include <runtime/JSObject.h>
namespace JSC {
class JSCallbackConstructor : public JSObject {
public:
JSCallbackConstructor(NonNullPassRefPtr<Structure>, JSClassRef, JSObjectCallAsConstructorCallback);
virtual ~JSCallbackConstructor();
JSClassRef classRef() const { return m_class; }
JSObjectCallAsConstructorCallback callback() const { return m_callback; }
static const ClassInfo info;
static PassRefPtr<Structure> createStructure(JSValue proto)
{
return Structure::create(proto, TypeInfo(ObjectType, StructureFlags));
}
protected:
static const unsigned StructureFlags = ImplementsHasInstance | JSObject::StructureFlags;
private:
virtual ConstructType getConstructData(ConstructData&);
virtual const ClassInfo* classInfo() const { return &info; }
JSClassRef m_class;
JSObjectCallAsConstructorCallback m_callback;
};
} // namespace JSC
#endif // JSCallbackConstructor_h

View file

@ -1,79 +0,0 @@
/*
* Copyright (C) 2006, 2008 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "Platform.h"
#include <wtf/Platform.h>
#include "JSCallbackFunction.h"
#include "APIShims.h"
#include "APICast.h"
#include "CodeBlock.h"
#include "JSFunction.h"
#include "FunctionPrototype.h"
#include <runtime/JSGlobalObject.h>
#include <wtf/Vector.h>
namespace JSC {
ASSERT_CLASS_FITS_IN_CELL(JSCallbackFunction);
const ClassInfo JSCallbackFunction::info = { "CallbackFunction", &InternalFunction::info, 0 };
JSCallbackFunction::JSCallbackFunction(ExecState* exec, JSObjectCallAsFunctionCallback callback, const Identifier& name)
: InternalFunction(&exec->globalData(), exec->lexicalGlobalObject()->callbackFunctionStructure(), name)
, m_callback(callback)
{
}
JSValue JSCallbackFunction::call(ExecState* exec, JSObject* functionObject, JSValue thisValue, const ArgList& args)
{
JSContextRef execRef = toRef(exec);
JSObjectRef functionRef = toRef(functionObject);
JSObjectRef thisObjRef = toRef(thisValue.toThisObject(exec));
int argumentCount = static_cast<int>(args.size());
Vector<JSValueRef, 16> arguments(argumentCount);
for (int i = 0; i < argumentCount; i++)
arguments[i] = toRef(exec, args.at(i));
JSValueRef exception = 0;
JSValueRef result;
{
APICallbackShim callbackShim(exec);
result = static_cast<JSCallbackFunction*>(functionObject)->m_callback(execRef, functionRef, thisObjRef, argumentCount, arguments.data(), &exception);
}
if (exception)
exec->setException(toJS(exec, exception));
return toJS(exec, result);
}
CallType JSCallbackFunction::getCallData(CallData& callData)
{
callData.native.function = call;
return CallTypeHost;
}
} // namespace JSC

View file

@ -1,58 +0,0 @@
/*
* Copyright (C) 2006, 2008 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef JSCallbackFunction_h
#define JSCallbackFunction_h
#include "InternalFunction.h"
#include "JSObjectRef.h"
namespace JSC {
class JSCallbackFunction : public InternalFunction {
public:
JSCallbackFunction(ExecState*, JSObjectCallAsFunctionCallback, const Identifier& name);
static const ClassInfo info;
// InternalFunction mish-mashes constructor and function behavior -- we should
// refactor the code so this override isn't necessary
static PassRefPtr<Structure> createStructure(JSValue proto)
{
return Structure::create(proto, TypeInfo(ObjectType, StructureFlags));
}
private:
virtual CallType getCallData(CallData&);
virtual const ClassInfo* classInfo() const { return &info; }
static JSValue QT_FASTCALL call(ExecState*, JSObject*, JSValue, const ArgList&);
JSObjectCallAsFunctionCallback m_callback;
};
} // namespace JSC
#endif // JSCallbackFunction_h

View file

@ -1,37 +0,0 @@
/*
* Copyright (C) 2006 Apple Computer, Inc. All rights reserved.
* Copyright (C) 2007 Eric Seidel <eric@webkit.org>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "Platform.h"
#include "JSCallbackObject.h"
#include "Collector.h"
namespace JSC {
ASSERT_CLASS_FITS_IN_CELL(JSCallbackObject<JSObject>);
ASSERT_CLASS_FITS_IN_CELL(JSCallbackObject<JSGlobalObject>);
} // namespace JSC

View file

@ -1,116 +0,0 @@
/*
* Copyright (C) 2006, 2007, 2008 Apple Inc. All rights reserved.
* Copyright (C) 2007 Eric Seidel <eric@webkit.org>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef JSCallbackObject_h
#define JSCallbackObject_h
#include "JSObjectRef.h"
#include "JSValueRef.h"
#include "JSObject.h"
namespace JSC {
template <class Base>
class JSCallbackObject : public Base {
public:
JSCallbackObject(ExecState*, NonNullPassRefPtr<Structure>, JSClassRef, void* data);
JSCallbackObject(JSClassRef);
virtual ~JSCallbackObject();
void setPrivate(void* data);
void* getPrivate();
JSClassRef classRef() const { return m_callbackObjectData->jsClass; }
bool inherits(JSClassRef) const;
static PassRefPtr<Structure> createStructure(JSValue proto)
{
return Structure::create(proto, TypeInfo(ObjectType, StructureFlags));
}
protected:
static const unsigned StructureFlags = OverridesGetOwnPropertySlot | ImplementsHasInstance | OverridesHasInstance | OverridesMarkChildren | OverridesGetPropertyNames | Base::StructureFlags;
private:
virtual UString className() const;
virtual bool getOwnPropertySlot(ExecState*, const Identifier&, PropertySlot&);
virtual bool getOwnPropertySlot(ExecState*, unsigned, PropertySlot&);
virtual bool getOwnPropertyDescriptor(ExecState*, const Identifier&, PropertyDescriptor&);
virtual void put(ExecState*, const Identifier&, JSValue, PutPropertySlot&);
virtual bool deleteProperty(ExecState*, const Identifier&);
virtual bool deleteProperty(ExecState*, unsigned);
virtual bool hasInstance(ExecState* exec, JSValue value, JSValue proto);
virtual void getOwnPropertyNames(ExecState*, PropertyNameArray&, EnumerationMode mode = ExcludeDontEnumProperties);
virtual double toNumber(ExecState*) const;
virtual UString toString(ExecState*) const;
virtual ConstructType getConstructData(ConstructData&);
virtual CallType getCallData(CallData&);
virtual const ClassInfo* classInfo() const { return &Base::info; }
void init(ExecState*);
static JSCallbackObject* asCallbackObject(JSValue);
static JSValue QT_FASTCALL call(ExecState*, JSObject* functionObject, JSValue thisValue, const ArgList&);
static JSObject* construct(ExecState*, JSObject* constructor, const ArgList&);
static JSValue staticValueGetter(ExecState*, const Identifier&, const PropertySlot&);
static JSValue staticFunctionGetter(ExecState*, const Identifier&, const PropertySlot&);
static JSValue callbackGetter(ExecState*, const Identifier&, const PropertySlot&);
struct JSCallbackObjectData {
JSCallbackObjectData(void* privateData, JSClassRef jsClass)
: privateData(privateData)
, jsClass(jsClass)
{
JSClassRetain(jsClass);
}
~JSCallbackObjectData()
{
JSClassRelease(jsClass);
}
void* privateData;
JSClassRef jsClass;
};
OwnPtr<JSCallbackObjectData> m_callbackObjectData;
};
} // namespace JSC
// include the actual template class implementation
#include "JSCallbackObjectFunctions.h"
#endif // JSCallbackObject_h

View file

@ -1,603 +0,0 @@
/*
* Copyright (C) 2006, 2008 Apple Inc. All rights reserved.
* Copyright (C) 2007 Eric Seidel <eric@webkit.org>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "APIShims.h"
#include "APICast.h"
#include "Error.h"
#include "JSCallbackFunction.h"
#include "JSClassRef.h"
#include "JSGlobalObject.h"
#include "JSObjectRef.h"
#include "JSString.h"
#include "JSStringRef.h"
#include "OpaqueJSString.h"
#include "PropertyNameArray.h"
#include <wtf/Vector.h>
namespace JSC {
template <class Base>
inline JSCallbackObject<Base>* JSCallbackObject<Base>::asCallbackObject(JSValue value)
{
Q_ASSERT(asObject(value)->inherits(&Base::info));
return static_cast<JSCallbackObject*>(asObject(value));
}
template <class Base>
JSCallbackObject<Base>::JSCallbackObject(ExecState* exec, NonNullPassRefPtr<Structure> structure, JSClassRef jsClass, void* data)
: Base(structure)
, m_callbackObjectData(new JSCallbackObjectData(data, jsClass))
{
init(exec);
}
// Global object constructor.
// FIXME: Move this into a separate JSGlobalCallbackObject class derived from this one.
template <class Base>
JSCallbackObject<Base>::JSCallbackObject(JSClassRef jsClass)
: Base()
, m_callbackObjectData(new JSCallbackObjectData(0, jsClass))
{
Q_ASSERT(Base::isGlobalObject());
init(static_cast<JSGlobalObject*>(this)->globalExec());
}
template <class Base>
void JSCallbackObject<Base>::init(ExecState* exec)
{
Q_ASSERT(exec);
Vector<JSObjectInitializeCallback, 16> initRoutines;
JSClassRef jsClass = classRef();
do {
if (JSObjectInitializeCallback initialize = jsClass->initialize)
initRoutines.append(initialize);
} while ((jsClass = jsClass->parentClass));
// initialize from base to derived
for (int i = static_cast<int>(initRoutines.size()) - 1; i >= 0; i--) {
APICallbackShim callbackShim(exec);
JSObjectInitializeCallback initialize = initRoutines[i];
initialize(toRef(exec), toRef(this));
}
}
template <class Base>
JSCallbackObject<Base>::~JSCallbackObject()
{
JSObjectRef thisRef = toRef(this);
for (JSClassRef jsClass = classRef(); jsClass; jsClass = jsClass->parentClass)
if (JSObjectFinalizeCallback finalize = jsClass->finalize)
finalize(thisRef);
}
template <class Base>
UString JSCallbackObject<Base>::className() const
{
UString thisClassName = classRef()->className();
if (!thisClassName.isEmpty())
return thisClassName;
return Base::className();
}
template <class Base>
bool JSCallbackObject<Base>::getOwnPropertySlot(ExecState* exec, const Identifier& propertyName, PropertySlot& slot)
{
JSContextRef ctx = toRef(exec);
JSObjectRef thisRef = toRef(this);
RefPtr<OpaqueJSString> propertyNameRef;
for (JSClassRef jsClass = classRef(); jsClass; jsClass = jsClass->parentClass) {
// optional optimization to bypass getProperty in cases when we only need to know if the property exists
if (JSObjectHasPropertyCallback hasProperty = jsClass->hasProperty) {
if (!propertyNameRef)
propertyNameRef = OpaqueJSString::create(propertyName.ustring());
APICallbackShim callbackShim(exec);
if (hasProperty(ctx, thisRef, propertyNameRef.get())) {
slot.setCustom(this, callbackGetter);
return true;
}
} else if (JSObjectGetPropertyCallback getProperty = jsClass->getProperty) {
if (!propertyNameRef)
propertyNameRef = OpaqueJSString::create(propertyName.ustring());
JSValueRef exception = 0;
JSValueRef value;
{
APICallbackShim callbackShim(exec);
value = getProperty(ctx, thisRef, propertyNameRef.get(), &exception);
}
if (exception) {
exec->setException(toJS(exec, exception));
slot.setValue(jsUndefined());
return true;
}
if (value) {
slot.setValue(toJS(exec, value));
return true;
}
}
if (OpaqueJSClassStaticValuesTable* staticValues = jsClass->staticValues(exec)) {
if (staticValues->contains(propertyName.ustring().rep())) {
slot.setCustom(this, staticValueGetter);
return true;
}
}
if (OpaqueJSClassStaticFunctionsTable* staticFunctions = jsClass->staticFunctions(exec)) {
if (staticFunctions->contains(propertyName.ustring().rep())) {
slot.setCustom(this, staticFunctionGetter);
return true;
}
}
}
return Base::getOwnPropertySlot(exec, propertyName, slot);
}
template <class Base>
bool JSCallbackObject<Base>::getOwnPropertySlot(ExecState* exec, unsigned propertyName, PropertySlot& slot)
{
return getOwnPropertySlot(exec, Identifier::from(exec, propertyName), slot);
}
template <class Base>
bool JSCallbackObject<Base>::getOwnPropertyDescriptor(ExecState* exec, const Identifier& propertyName, PropertyDescriptor& descriptor)
{
PropertySlot slot;
if (getOwnPropertySlot(exec, propertyName, slot)) {
// Ideally we should return an access descriptor, but returning a value descriptor is better than nothing.
JSValue value = slot.getValue(exec, propertyName);
if (!exec->hadException())
descriptor.setValue(value);
// We don't know whether the property is configurable, but assume it is.
descriptor.setConfigurable(true);
// We don't know whether the property is enumerable (we could call getOwnPropertyNames() to find out), but assume it isn't.
descriptor.setEnumerable(false);
return true;
}
return Base::getOwnPropertyDescriptor(exec, propertyName, descriptor);
}
template <class Base>
void JSCallbackObject<Base>::put(ExecState* exec, const Identifier& propertyName, JSValue value, PutPropertySlot& slot)
{
JSContextRef ctx = toRef(exec);
JSObjectRef thisRef = toRef(this);
RefPtr<OpaqueJSString> propertyNameRef;
JSValueRef valueRef = toRef(exec, value);
for (JSClassRef jsClass = classRef(); jsClass; jsClass = jsClass->parentClass) {
if (JSObjectSetPropertyCallback setProperty = jsClass->setProperty) {
if (!propertyNameRef)
propertyNameRef = OpaqueJSString::create(propertyName.ustring());
JSValueRef exception = 0;
bool result;
{
APICallbackShim callbackShim(exec);
result = setProperty(ctx, thisRef, propertyNameRef.get(), valueRef, &exception);
}
if (exception)
exec->setException(toJS(exec, exception));
if (result || exception)
return;
}
if (OpaqueJSClassStaticValuesTable* staticValues = jsClass->staticValues(exec)) {
if (StaticValueEntry* entry = staticValues->get(propertyName.ustring().rep())) {
if (entry->attributes & kJSPropertyAttributeReadOnly)
return;
if (JSObjectSetPropertyCallback setProperty = entry->setProperty) {
if (!propertyNameRef)
propertyNameRef = OpaqueJSString::create(propertyName.ustring());
JSValueRef exception = 0;
bool result;
{
APICallbackShim callbackShim(exec);
result = setProperty(ctx, thisRef, propertyNameRef.get(), valueRef, &exception);
}
if (exception)
exec->setException(toJS(exec, exception));
if (result || exception)
return;
} else
throwError(exec, ReferenceError, "Attempt to set a property that is not settable.");
}
}
if (OpaqueJSClassStaticFunctionsTable* staticFunctions = jsClass->staticFunctions(exec)) {
if (StaticFunctionEntry* entry = staticFunctions->get(propertyName.ustring().rep())) {
if (entry->attributes & kJSPropertyAttributeReadOnly)
return;
JSCallbackObject<Base>::putDirect(propertyName, value); // put as override property
return;
}
}
}
return Base::put(exec, propertyName, value, slot);
}
template <class Base>
bool JSCallbackObject<Base>::deleteProperty(ExecState* exec, const Identifier& propertyName)
{
JSContextRef ctx = toRef(exec);
JSObjectRef thisRef = toRef(this);
RefPtr<OpaqueJSString> propertyNameRef;
for (JSClassRef jsClass = classRef(); jsClass; jsClass = jsClass->parentClass) {
if (JSObjectDeletePropertyCallback deleteProperty = jsClass->deleteProperty) {
if (!propertyNameRef)
propertyNameRef = OpaqueJSString::create(propertyName.ustring());
JSValueRef exception = 0;
bool result;
{
APICallbackShim callbackShim(exec);
result = deleteProperty(ctx, thisRef, propertyNameRef.get(), &exception);
}
if (exception)
exec->setException(toJS(exec, exception));
if (result || exception)
return true;
}
if (OpaqueJSClassStaticValuesTable* staticValues = jsClass->staticValues(exec)) {
if (StaticValueEntry* entry = staticValues->get(propertyName.ustring().rep())) {
if (entry->attributes & kJSPropertyAttributeDontDelete)
return false;
return true;
}
}
if (OpaqueJSClassStaticFunctionsTable* staticFunctions = jsClass->staticFunctions(exec)) {
if (StaticFunctionEntry* entry = staticFunctions->get(propertyName.ustring().rep())) {
if (entry->attributes & kJSPropertyAttributeDontDelete)
return false;
return true;
}
}
}
return Base::deleteProperty(exec, propertyName);
}
template <class Base>
bool JSCallbackObject<Base>::deleteProperty(ExecState* exec, unsigned propertyName)
{
return deleteProperty(exec, Identifier::from(exec, propertyName));
}
template <class Base>
ConstructType JSCallbackObject<Base>::getConstructData(ConstructData& constructData)
{
for (JSClassRef jsClass = classRef(); jsClass; jsClass = jsClass->parentClass) {
if (jsClass->callAsConstructor) {
constructData.native.function = construct;
return ConstructTypeHost;
}
}
return ConstructTypeNone;
}
template <class Base>
JSObject* JSCallbackObject<Base>::construct(ExecState* exec, JSObject* constructor, const ArgList& args)
{
JSContextRef execRef = toRef(exec);
JSObjectRef constructorRef = toRef(constructor);
for (JSClassRef jsClass = static_cast<JSCallbackObject<Base>*>(constructor)->classRef(); jsClass; jsClass = jsClass->parentClass) {
if (JSObjectCallAsConstructorCallback callAsConstructor = jsClass->callAsConstructor) {
int argumentCount = static_cast<int>(args.size());
Vector<JSValueRef, 16> arguments(argumentCount);
for (int i = 0; i < argumentCount; i++)
arguments[i] = toRef(exec, args.at(i));
JSValueRef exception = 0;
JSObject* result;
{
APICallbackShim callbackShim(exec);
result = toJS(callAsConstructor(execRef, constructorRef, argumentCount, arguments.data(), &exception));
}
if (exception)
exec->setException(toJS(exec, exception));
return result;
}
}
Q_UNREACHABLE(); // getConstructData should prevent us from reaching here
return 0;
}
template <class Base>
bool JSCallbackObject<Base>::hasInstance(ExecState* exec, JSValue value, JSValue)
{
JSContextRef execRef = toRef(exec);
JSObjectRef thisRef = toRef(this);
for (JSClassRef jsClass = classRef(); jsClass; jsClass = jsClass->parentClass) {
if (JSObjectHasInstanceCallback hasInstance = jsClass->hasInstance) {
JSValueRef valueRef = toRef(exec, value);
JSValueRef exception = 0;
bool result;
{
APICallbackShim callbackShim(exec);
result = hasInstance(execRef, thisRef, valueRef, &exception);
}
if (exception)
exec->setException(toJS(exec, exception));
return result;
}
}
return false;
}
template <class Base>
CallType JSCallbackObject<Base>::getCallData(CallData& callData)
{
for (JSClassRef jsClass = classRef(); jsClass; jsClass = jsClass->parentClass) {
if (jsClass->callAsFunction) {
callData.native.function = call;
return CallTypeHost;
}
}
return CallTypeNone;
}
template <class Base>
JSValue JSCallbackObject<Base>::call(ExecState* exec, JSObject* functionObject, JSValue thisValue, const ArgList& args)
{
JSContextRef execRef = toRef(exec);
JSObjectRef functionRef = toRef(functionObject);
JSObjectRef thisObjRef = toRef(thisValue.toThisObject(exec));
for (JSClassRef jsClass = static_cast<JSCallbackObject<Base>*>(functionObject)->classRef(); jsClass; jsClass = jsClass->parentClass) {
if (JSObjectCallAsFunctionCallback callAsFunction = jsClass->callAsFunction) {
int argumentCount = static_cast<int>(args.size());
Vector<JSValueRef, 16> arguments(argumentCount);
for (int i = 0; i < argumentCount; i++)
arguments[i] = toRef(exec, args.at(i));
JSValueRef exception = 0;
JSValue result;
{
APICallbackShim callbackShim(exec);
result = toJS(exec, callAsFunction(execRef, functionRef, thisObjRef, argumentCount, arguments.data(), &exception));
}
if (exception)
exec->setException(toJS(exec, exception));
return result;
}
}
Q_UNREACHABLE(); // getCallData should prevent us from reaching here
return JSValue();
}
template <class Base>
void JSCallbackObject<Base>::getOwnPropertyNames(ExecState* exec, PropertyNameArray& propertyNames, EnumerationMode mode)
{
JSContextRef execRef = toRef(exec);
JSObjectRef thisRef = toRef(this);
for (JSClassRef jsClass = classRef(); jsClass; jsClass = jsClass->parentClass) {
if (JSObjectGetPropertyNamesCallback getPropertyNames = jsClass->getPropertyNames) {
APICallbackShim callbackShim(exec);
getPropertyNames(execRef, thisRef, toRef(&propertyNames));
}
if (OpaqueJSClassStaticValuesTable* staticValues = jsClass->staticValues(exec)) {
typedef OpaqueJSClassStaticValuesTable::const_iterator iterator;
iterator end = staticValues->end();
for (iterator it = staticValues->begin(); it != end; ++it) {
UString::Rep* name = it->first.get();
StaticValueEntry* entry = it->second;
if (entry->getProperty && (!(entry->attributes & kJSPropertyAttributeDontEnum) || (mode == IncludeDontEnumProperties)))
propertyNames.add(Identifier(exec, name));
}
}
if (OpaqueJSClassStaticFunctionsTable* staticFunctions = jsClass->staticFunctions(exec)) {
typedef OpaqueJSClassStaticFunctionsTable::const_iterator iterator;
iterator end = staticFunctions->end();
for (iterator it = staticFunctions->begin(); it != end; ++it) {
UString::Rep* name = it->first.get();
StaticFunctionEntry* entry = it->second;
if (!(entry->attributes & kJSPropertyAttributeDontEnum) || (mode == IncludeDontEnumProperties))
propertyNames.add(Identifier(exec, name));
}
}
}
Base::getOwnPropertyNames(exec, propertyNames, mode);
}
template <class Base>
double JSCallbackObject<Base>::toNumber(ExecState* exec) const
{
// We need this check to guard against the case where this object is rhs of
// a binary expression where lhs threw an exception in its conversion to
// primitive
if (exec->hadException())
return NaN;
JSContextRef ctx = toRef(exec);
JSObjectRef thisRef = toRef(this);
for (JSClassRef jsClass = classRef(); jsClass; jsClass = jsClass->parentClass)
if (JSObjectConvertToTypeCallback convertToType = jsClass->convertToType) {
JSValueRef exception = 0;
JSValueRef value;
{
APICallbackShim callbackShim(exec);
value = convertToType(ctx, thisRef, NumberType, &exception);
}
if (exception) {
exec->setException(toJS(exec, exception));
return 0;
}
if (value) {
double dValue;
return toJS(exec, value).getNumber(dValue) ? dValue : NaN;
}
}
return Base::toNumber(exec);
}
template <class Base>
UString JSCallbackObject<Base>::toString(ExecState* exec) const
{
JSContextRef ctx = toRef(exec);
JSObjectRef thisRef = toRef(this);
for (JSClassRef jsClass = classRef(); jsClass; jsClass = jsClass->parentClass)
if (JSObjectConvertToTypeCallback convertToType = jsClass->convertToType) {
JSValueRef exception = 0;
JSValueRef value;
{
APICallbackShim callbackShim(exec);
value = convertToType(ctx, thisRef, StringType, &exception);
}
if (exception) {
exec->setException(toJS(exec, exception));
return "";
}
if (value)
return toJS(exec, value).getString(exec);
}
return Base::toString(exec);
}
template <class Base>
void JSCallbackObject<Base>::setPrivate(void* data)
{
m_callbackObjectData->privateData = data;
}
template <class Base>
void* JSCallbackObject<Base>::getPrivate()
{
return m_callbackObjectData->privateData;
}
template <class Base>
bool JSCallbackObject<Base>::inherits(JSClassRef c) const
{
for (JSClassRef jsClass = classRef(); jsClass; jsClass = jsClass->parentClass)
if (jsClass == c)
return true;
return false;
}
template <class Base>
JSValue JSCallbackObject<Base>::staticValueGetter(ExecState* exec, const Identifier& propertyName, const PropertySlot& slot)
{
JSCallbackObject* thisObj = asCallbackObject(slot.slotBase());
JSObjectRef thisRef = toRef(thisObj);
RefPtr<OpaqueJSString> propertyNameRef;
for (JSClassRef jsClass = thisObj->classRef(); jsClass; jsClass = jsClass->parentClass)
if (OpaqueJSClassStaticValuesTable* staticValues = jsClass->staticValues(exec))
if (StaticValueEntry* entry = staticValues->get(propertyName.ustring().rep()))
if (JSObjectGetPropertyCallback getProperty = entry->getProperty) {
if (!propertyNameRef)
propertyNameRef = OpaqueJSString::create(propertyName.ustring());
JSValueRef exception = 0;
JSValueRef value;
{
APICallbackShim callbackShim(exec);
value = getProperty(toRef(exec), thisRef, propertyNameRef.get(), &exception);
}
if (exception) {
exec->setException(toJS(exec, exception));
return jsUndefined();
}
if (value)
return toJS(exec, value);
}
return throwError(exec, ReferenceError, "Static value property defined with NULL getProperty callback.");
}
template <class Base>
JSValue JSCallbackObject<Base>::staticFunctionGetter(ExecState* exec, const Identifier& propertyName, const PropertySlot& slot)
{
JSCallbackObject* thisObj = asCallbackObject(slot.slotBase());
// Check for cached or override property.
PropertySlot slot2(thisObj);
if (thisObj->Base::getOwnPropertySlot(exec, propertyName, slot2))
return slot2.getValue(exec, propertyName);
for (JSClassRef jsClass = thisObj->classRef(); jsClass; jsClass = jsClass->parentClass) {
if (OpaqueJSClassStaticFunctionsTable* staticFunctions = jsClass->staticFunctions(exec)) {
if (StaticFunctionEntry* entry = staticFunctions->get(propertyName.ustring().rep())) {
if (JSObjectCallAsFunctionCallback callAsFunction = entry->callAsFunction) {
JSObject* o = new (exec) JSCallbackFunction(exec, callAsFunction, propertyName);
thisObj->putDirect(propertyName, o, entry->attributes);
return o;
}
}
}
}
return throwError(exec, ReferenceError, "Static function property defined with NULL callAsFunction callback.");
}
template <class Base>
JSValue JSCallbackObject<Base>::callbackGetter(ExecState* exec, const Identifier& propertyName, const PropertySlot& slot)
{
JSCallbackObject* thisObj = asCallbackObject(slot.slotBase());
JSObjectRef thisRef = toRef(thisObj);
RefPtr<OpaqueJSString> propertyNameRef;
for (JSClassRef jsClass = thisObj->classRef(); jsClass; jsClass = jsClass->parentClass)
if (JSObjectGetPropertyCallback getProperty = jsClass->getProperty) {
if (!propertyNameRef)
propertyNameRef = OpaqueJSString::create(propertyName.ustring());
JSValueRef exception = 0;
JSValueRef value;
{
APICallbackShim callbackShim(exec);
value = getProperty(toRef(exec), thisRef, propertyNameRef.get(), &exception);
}
if (exception) {
exec->setException(toJS(exec, exception));
return jsUndefined();
}
if (value)
return toJS(exec, value);
}
return throwError(exec, ReferenceError, "hasProperty callback returned true for a property that doesn't exist.");
}
} // namespace JSC

View file

@ -1,241 +0,0 @@
/*
* Copyright (C) 2006, 2007 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "Platform.h"
#include "JSClassRef.h"
#include "APICast.h"
#include "JSCallbackObject.h"
#include "JSObjectRef.h"
#include <runtime/InitializeThreading.h>
#include <runtime/JSGlobalObject.h>
#include <runtime/ObjectPrototype.h>
#include <runtime/Identifier.h>
using namespace std;
using namespace JSC;
const JSClassDefinition kJSClassDefinitionEmpty = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
OpaqueJSClass::OpaqueJSClass(const JSClassDefinition* definition, OpaqueJSClass* protoClass)
: parentClass(definition->parentClass)
, prototypeClass(0)
, initialize(definition->initialize)
, finalize(definition->finalize)
, hasProperty(definition->hasProperty)
, getProperty(definition->getProperty)
, setProperty(definition->setProperty)
, deleteProperty(definition->deleteProperty)
, getPropertyNames(definition->getPropertyNames)
, callAsFunction(definition->callAsFunction)
, callAsConstructor(definition->callAsConstructor)
, hasInstance(definition->hasInstance)
, convertToType(definition->convertToType)
, m_className(UString::createFromUTF8(definition->className).rep()->ref())
, m_staticValues(0)
, m_staticFunctions(0)
{
initializeThreading();
if (const JSStaticValue* staticValue = definition->staticValues) {
m_staticValues = new OpaqueJSClassStaticValuesTable();
while (staticValue->name) {
// Use a local variable here to sidestep an RVCT compiler bug.
StaticValueEntry* entry = new StaticValueEntry(staticValue->getProperty, staticValue->setProperty, staticValue->attributes);
m_staticValues->add(UString::createFromUTF8(staticValue->name).rep()->ref(), entry);
++staticValue;
}
}
if (const JSStaticFunction* staticFunction = definition->staticFunctions) {
m_staticFunctions = new OpaqueJSClassStaticFunctionsTable();
while (staticFunction->name) {
// Use a local variable here to sidestep an RVCT compiler bug.
StaticFunctionEntry* entry = new StaticFunctionEntry(staticFunction->callAsFunction, staticFunction->attributes);
m_staticFunctions->add(UString::createFromUTF8(staticFunction->name).rep()->ref(), entry);
++staticFunction;
}
}
if (protoClass)
prototypeClass = JSClassRetain(protoClass);
}
OpaqueJSClass::~OpaqueJSClass()
{
Q_ASSERT(!m_className.rep()->isIdentifier());
if (m_staticValues) {
OpaqueJSClassStaticValuesTable::const_iterator end = m_staticValues->end();
for (OpaqueJSClassStaticValuesTable::const_iterator it = m_staticValues->begin(); it != end; ++it) {
Q_ASSERT(!it->first->isIdentifier());
delete it->second;
}
delete m_staticValues;
}
if (m_staticFunctions) {
OpaqueJSClassStaticFunctionsTable::const_iterator end = m_staticFunctions->end();
for (OpaqueJSClassStaticFunctionsTable::const_iterator it = m_staticFunctions->begin(); it != end; ++it) {
Q_ASSERT(!it->first->isIdentifier());
delete it->second;
}
delete m_staticFunctions;
}
if (prototypeClass)
JSClassRelease(prototypeClass);
}
PassRefPtr<OpaqueJSClass> OpaqueJSClass::createNoAutomaticPrototype(const JSClassDefinition* definition)
{
return adoptRef(new OpaqueJSClass(definition, 0));
}
static void clearReferenceToPrototype(JSObjectRef prototype)
{
OpaqueJSClassContextData* jsClassData = static_cast<OpaqueJSClassContextData*>(JSObjectGetPrivate(prototype));
Q_ASSERT(jsClassData);
jsClassData->cachedPrototype = 0;
}
PassRefPtr<OpaqueJSClass> OpaqueJSClass::create(const JSClassDefinition* clientDefinition)
{
JSClassDefinition definition = *clientDefinition; // Avoid modifying client copy.
JSClassDefinition protoDefinition = kJSClassDefinitionEmpty;
protoDefinition.finalize = clearReferenceToPrototype;
swap(definition.staticFunctions, protoDefinition.staticFunctions); // Move static functions to the prototype.
// We are supposed to use JSClassRetain/Release but since we know that we currently have
// the only reference to this class object we cheat and use a RefPtr instead.
RefPtr<OpaqueJSClass> protoClass = adoptRef(new OpaqueJSClass(&protoDefinition, 0));
return adoptRef(new OpaqueJSClass(&definition, protoClass.get()));
}
OpaqueJSClassContextData::OpaqueJSClassContextData(OpaqueJSClass* jsClass)
: m_class(jsClass)
{
if (jsClass->m_staticValues) {
staticValues = new OpaqueJSClassStaticValuesTable;
OpaqueJSClassStaticValuesTable::const_iterator end = jsClass->m_staticValues->end();
for (OpaqueJSClassStaticValuesTable::const_iterator it = jsClass->m_staticValues->begin(); it != end; ++it) {
Q_ASSERT(!it->first->isIdentifier());
// Use a local variable here to sidestep an RVCT compiler bug.
StaticValueEntry* entry = new StaticValueEntry(it->second->getProperty, it->second->setProperty, it->second->attributes);
staticValues->add(UString::Rep::create(it->first->data(), it->first->size()), entry);
}
} else
staticValues = 0;
if (jsClass->m_staticFunctions) {
staticFunctions = new OpaqueJSClassStaticFunctionsTable;
OpaqueJSClassStaticFunctionsTable::const_iterator end = jsClass->m_staticFunctions->end();
for (OpaqueJSClassStaticFunctionsTable::const_iterator it = jsClass->m_staticFunctions->begin(); it != end; ++it) {
Q_ASSERT(!it->first->isIdentifier());
// Use a local variable here to sidestep an RVCT compiler bug.
StaticFunctionEntry* entry = new StaticFunctionEntry(it->second->callAsFunction, it->second->attributes);
staticFunctions->add(UString::Rep::create(it->first->data(), it->first->size()), entry);
}
} else
staticFunctions = 0;
}
OpaqueJSClassContextData::~OpaqueJSClassContextData()
{
if (staticValues) {
deleteAllValues(*staticValues);
delete staticValues;
}
if (staticFunctions) {
deleteAllValues(*staticFunctions);
delete staticFunctions;
}
}
OpaqueJSClassContextData& OpaqueJSClass::contextData(ExecState* exec)
{
OpaqueJSClassContextData*& contextData = exec->globalData().opaqueJSClassData.add(this, 0).first->second;
if (!contextData)
contextData = new OpaqueJSClassContextData(this);
return *contextData;
}
UString OpaqueJSClass::className()
{
// Make a deep copy, so that the caller has no chance to put the original into IdentifierTable.
return UString(m_className.data(), m_className.size());
}
OpaqueJSClassStaticValuesTable* OpaqueJSClass::staticValues(JSC::ExecState* exec)
{
OpaqueJSClassContextData& jsClassData = contextData(exec);
return jsClassData.staticValues;
}
OpaqueJSClassStaticFunctionsTable* OpaqueJSClass::staticFunctions(JSC::ExecState* exec)
{
OpaqueJSClassContextData& jsClassData = contextData(exec);
return jsClassData.staticFunctions;
}
/*!
// Doc here in case we make this public. (Hopefully we won't.)
@function
@abstract Returns the prototype that will be used when constructing an object with a given class.
@param ctx The execution context to use.
@param jsClass A JSClass whose prototype you want to get.
@result The JSObject prototype that was automatically generated for jsClass, or NULL if no prototype was automatically generated. This is the prototype that will be used when constructing an object using jsClass.
*/
JSObject* OpaqueJSClass::prototype(ExecState* exec)
{
/* Class (C++) and prototype (JS) inheritance are parallel, so:
* (C++) | (JS)
* ParentClass | ParentClassPrototype
* ^ | ^
* | | |
* DerivedClass | DerivedClassPrototype
*/
if (!prototypeClass)
return 0;
OpaqueJSClassContextData& jsClassData = contextData(exec);
if (!jsClassData.cachedPrototype) {
// Recursive, but should be good enough for our purposes
jsClassData.cachedPrototype = new (exec) JSCallbackObject<JSObject>(exec, exec->lexicalGlobalObject()->callbackObjectStructure(), prototypeClass, &jsClassData); // set jsClassData as the object's private data, so it can clear our reference on destruction
if (parentClass) {
if (JSObject* prototype = parentClass->prototype(exec))
jsClassData.cachedPrototype->setPrototype(prototype);
}
}
return jsClassData.cachedPrototype.get();
}

View file

@ -1,123 +0,0 @@
/*
* Copyright (C) 2006 Apple Computer, Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef JSClassRef_h
#define JSClassRef_h
#include "JSObjectRef.h"
#include <runtime/JSObject.h>
#include <runtime/Protect.h>
#include <runtime/UString.h>
#include <runtime/WeakGCPtr.h>
#include <wtf/HashMap.h>
#include <wtf/RefCounted.h>
struct StaticValueEntry : FastAllocBase {
StaticValueEntry(JSObjectGetPropertyCallback _getProperty, JSObjectSetPropertyCallback _setProperty, JSPropertyAttributes _attributes)
: getProperty(_getProperty), setProperty(_setProperty), attributes(_attributes)
{
}
JSObjectGetPropertyCallback getProperty;
JSObjectSetPropertyCallback setProperty;
JSPropertyAttributes attributes;
};
struct StaticFunctionEntry : FastAllocBase {
StaticFunctionEntry(JSObjectCallAsFunctionCallback _callAsFunction, JSPropertyAttributes _attributes)
: callAsFunction(_callAsFunction), attributes(_attributes)
{
}
JSObjectCallAsFunctionCallback callAsFunction;
JSPropertyAttributes attributes;
};
typedef HashMap<RefPtr<JSC::UString::Rep>, StaticValueEntry*> OpaqueJSClassStaticValuesTable;
typedef HashMap<RefPtr<JSC::UString::Rep>, StaticFunctionEntry*> OpaqueJSClassStaticFunctionsTable;
struct OpaqueJSClass;
// An OpaqueJSClass (JSClass) is created without a context, so it can be used with any context, even across context groups.
// This structure holds data members that vary across context groups.
struct OpaqueJSClassContextData : Noncopyable {
OpaqueJSClassContextData(OpaqueJSClass*);
~OpaqueJSClassContextData();
// It is necessary to keep OpaqueJSClass alive because of the following rare scenario:
// 1. A class is created and used, so its context data is stored in JSGlobalData hash map.
// 2. The class is released, and when all JS objects that use it are collected, OpaqueJSClass
// is deleted (that's the part prevented by this RefPtr).
// 3. Another class is created at the same address.
// 4. When it is used, the old context data is found in JSGlobalData and used.
RefPtr<OpaqueJSClass> m_class;
OpaqueJSClassStaticValuesTable* staticValues;
OpaqueJSClassStaticFunctionsTable* staticFunctions;
JSC::WeakGCPtr<JSC::JSObject> cachedPrototype;
};
struct OpaqueJSClass : public ThreadSafeShared<OpaqueJSClass> {
static PassRefPtr<OpaqueJSClass> create(const JSClassDefinition*);
static PassRefPtr<OpaqueJSClass> createNoAutomaticPrototype(const JSClassDefinition*);
~OpaqueJSClass();
JSC::UString className();
OpaqueJSClassStaticValuesTable* staticValues(JSC::ExecState*);
OpaqueJSClassStaticFunctionsTable* staticFunctions(JSC::ExecState*);
JSC::JSObject* prototype(JSC::ExecState*);
OpaqueJSClass* parentClass;
OpaqueJSClass* prototypeClass;
JSObjectInitializeCallback initialize;
JSObjectFinalizeCallback finalize;
JSObjectHasPropertyCallback hasProperty;
JSObjectGetPropertyCallback getProperty;
JSObjectSetPropertyCallback setProperty;
JSObjectDeletePropertyCallback deleteProperty;
JSObjectGetPropertyNamesCallback getPropertyNames;
JSObjectCallAsFunctionCallback callAsFunction;
JSObjectCallAsConstructorCallback callAsConstructor;
JSObjectHasInstanceCallback hasInstance;
JSObjectConvertToTypeCallback convertToType;
private:
friend struct OpaqueJSClassContextData;
OpaqueJSClass();
OpaqueJSClass(const OpaqueJSClass&);
OpaqueJSClass(const JSClassDefinition*, OpaqueJSClass* protoClass);
OpaqueJSClassContextData& contextData(JSC::ExecState*);
// UStrings in these data members should not be put into any IdentifierTable.
JSC::UString m_className;
OpaqueJSClassStaticValuesTable* m_staticValues;
OpaqueJSClassStaticFunctionsTable* m_staticFunctions;
};
#endif // JSClassRef_h

View file

@ -1,134 +0,0 @@
/*
* Copyright (C) 2006, 2007 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "Platform.h"
#include "JSContextRef.h"
#include "JSContextRefPrivate.h"
#include "APICast.h"
#include "InitializeThreading.h"
#include "JSCallbackObject.h"
#include "JSClassRef.h"
#include "JSGlobalObject.h"
#include "JSObject.h"
#include <wtf/Platform.h>
using namespace JSC;
JSContextGroupRef JSContextGroupCreate()
{
initializeThreading();
return toRef(JSGlobalData::createNonDefault().releaseRef());
}
JSContextGroupRef JSContextGroupRetain(JSContextGroupRef group)
{
toJS(group)->ref();
return group;
}
void JSContextGroupRelease(JSContextGroupRef group)
{
toJS(group)->deref();
}
JSGlobalContextRef JSGlobalContextCreate(JSClassRef globalObjectClass)
{
initializeThreading();
return JSGlobalContextCreateInGroup(0, globalObjectClass);
}
JSGlobalContextRef JSGlobalContextCreateInGroup(JSContextGroupRef group, JSClassRef globalObjectClass)
{
initializeThreading();
RefPtr<JSGlobalData> globalData = group ? PassRefPtr<JSGlobalData>(toJS(group)) : JSGlobalData::createNonDefault();
APIEntryShim entryShim(globalData.get());
if (!globalObjectClass) {
JSGlobalObject* globalObject = new (globalData.get()) JSGlobalObject;
return JSGlobalContextRetain(toGlobalRef(globalObject->globalExec()));
}
JSGlobalObject* globalObject = new (globalData.get()) JSCallbackObject<JSGlobalObject>(globalObjectClass);
ExecState* exec = globalObject->globalExec();
JSValue prototype = globalObjectClass->prototype(exec);
if (!prototype)
prototype = jsNull();
globalObject->resetPrototype(prototype);
return JSGlobalContextRetain(toGlobalRef(exec));
}
JSGlobalContextRef JSGlobalContextRetain(JSGlobalContextRef ctx)
{
ExecState* exec = toJS(ctx);
APIEntryShim entryShim(exec);
JSGlobalData& globalData = exec->globalData();
gcProtect(exec->dynamicGlobalObject());
globalData.ref();
return ctx;
}
void JSGlobalContextRelease(JSGlobalContextRef ctx)
{
ExecState* exec = toJS(ctx);
APIEntryShim entryShim(exec);
gcUnprotect(exec->dynamicGlobalObject());
JSGlobalData& globalData = exec->globalData();
if (globalData.refCount() == 2) { // One reference is held by JSGlobalObject, another added by JSGlobalContextRetain().
// The last reference was released, this is our last chance to collect.
globalData.heap.destroy();
} else
globalData.heap.collectAllGarbage();
globalData.deref();
}
JSObjectRef JSContextGetGlobalObject(JSContextRef ctx)
{
ExecState* exec = toJS(ctx);
APIEntryShim entryShim(exec);
// It is necessary to call toThisObject to get the wrapper object when used with WebCore.
return toRef(exec->lexicalGlobalObject()->toThisObject(exec));
}
JSContextGroupRef JSContextGetGroup(JSContextRef ctx)
{
ExecState* exec = toJS(ctx);
return toRef(&exec->globalData());
}
JSGlobalContextRef JSContextGetGlobalContext(JSContextRef ctx)
{
ExecState* exec = toJS(ctx);
APIEntryShim entryShim(exec);
return toGlobalRef(exec->lexicalGlobalObject()->globalExec());
}

View file

@ -1,127 +0,0 @@
/*
* Copyright (C) 2006 Apple Computer, Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef JSContextRef_h
#define JSContextRef_h
#include <JSObjectRef.h>
#include <JSValueRef.h>
#ifdef __cplusplus
extern "C" {
#endif
/*!
@function
@abstract Creates a JavaScript context group.
@discussion A JSContextGroup associates JavaScript contexts with one another.
Contexts in the same group may share and exchange JavaScript objects. Sharing and/or exchanging
JavaScript objects between contexts in different groups will produce undefined behavior.
When objects from the same context group are used in multiple threads, explicit
synchronization is required.
@result The created JSContextGroup.
*/
JS_EXPORT JSContextGroupRef JSContextGroupCreate();
/*!
@function
@abstract Retains a JavaScript context group.
@param group The JSContextGroup to retain.
@result A JSContextGroup that is the same as group.
*/
JS_EXPORT JSContextGroupRef JSContextGroupRetain(JSContextGroupRef group);
/*!
@function
@abstract Releases a JavaScript context group.
@param group The JSContextGroup to release.
*/
JS_EXPORT void JSContextGroupRelease(JSContextGroupRef group);
/*!
@function
@abstract Creates a global JavaScript execution context.
@discussion JSGlobalContextCreate allocates a global object and populates it with all the
built-in JavaScript objects, such as Object, Function, String, and Array.
In WebKit version 4.0 and later, the context is created in a unique context group.
Therefore, scripts may execute in it concurrently with scripts executing in other contexts.
However, you may not use values created in the context in other contexts.
@param globalObjectClass The class to use when creating the global object. Pass
NULL to use the default object class.
@result A JSGlobalContext with a global object of class globalObjectClass.
*/
JS_EXPORT JSGlobalContextRef JSGlobalContextCreate(JSClassRef globalObjectClass);
/*!
@function
@abstract Creates a global JavaScript execution context in the context group provided.
@discussion JSGlobalContextCreateInGroup allocates a global object and populates it with
all the built-in JavaScript objects, such as Object, Function, String, and Array.
@param globalObjectClass The class to use when creating the global object. Pass
NULL to use the default object class.
@param group The context group to use. The created global context retains the group.
Pass NULL to create a unique group for the context.
@result A JSGlobalContext with a global object of class globalObjectClass and a context
group equal to group.
*/
JS_EXPORT JSGlobalContextRef JSGlobalContextCreateInGroup(JSContextGroupRef group, JSClassRef globalObjectClass);
/*!
@function
@abstract Retains a global JavaScript execution context.
@param ctx The JSGlobalContext to retain.
@result A JSGlobalContext that is the same as ctx.
*/
JS_EXPORT JSGlobalContextRef JSGlobalContextRetain(JSGlobalContextRef ctx);
/*!
@function
@abstract Releases a global JavaScript execution context.
@param ctx The JSGlobalContext to release.
*/
JS_EXPORT void JSGlobalContextRelease(JSGlobalContextRef ctx);
/*!
@function
@abstract Gets the global object of a JavaScript execution context.
@param ctx The JSContext whose global object you want to get.
@result ctx's global object.
*/
JS_EXPORT JSObjectRef JSContextGetGlobalObject(JSContextRef ctx);
/*!
@function
@abstract Gets the context group to which a JavaScript execution context belongs.
@param ctx The JSContext whose group you want to get.
@result ctx's group.
*/
JS_EXPORT JSContextGroupRef JSContextGetGroup(JSContextRef ctx);
#ifdef __cplusplus
}
#endif
#endif /* JSContextRef_h */

View file

@ -1,48 +0,0 @@
/*
* Copyright (C) 2009 Apple Computer, Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef JSContextRefPrivate_h
#define JSContextRefPrivate_h
#include <JSObjectRef.h>
#include <JSValueRef.h>
#ifdef __cplusplus
extern "C" {
#endif
/*!
@function
@abstract Gets the global context of a JavaScript execution context.
@param ctx The JSContext whose global context you want to get.
@result ctx's global context.
*/
JS_EXPORT JSGlobalContextRef JSContextGetGlobalContext(JSContextRef ctx);
#ifdef __cplusplus
}
#endif
#endif /* JSContextRefPrivate_h */

View file

@ -1,496 +0,0 @@
/*
* Copyright (C) 2006, 2007, 2008 Apple Inc. All rights reserved.
* Copyright (C) 2008 Kelvin W Sherlock (ksherlock@gmail.com)
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "Platform.h"
#include "JSObjectRef.h"
#include "APICast.h"
#include "CodeBlock.h"
#include "DateConstructor.h"
#include "ErrorConstructor.h"
#include "FunctionConstructor.h"
#include "Identifier.h"
#include "InitializeThreading.h"
#include "JSArray.h"
#include "JSCallbackConstructor.h"
#include "JSCallbackFunction.h"
#include "JSCallbackObject.h"
#include "JSClassRef.h"
#include "JSFunction.h"
#include "JSGlobalObject.h"
#include "JSObject.h"
#include "JSRetainPtr.h"
#include "JSString.h"
#include "JSValueRef.h"
#include "ObjectPrototype.h"
#include "PropertyNameArray.h"
#include "RegExpConstructor.h"
#include <wtf/Platform.h>
using namespace JSC;
JSClassRef JSClassCreate(const JSClassDefinition* definition)
{
initializeThreading();
RefPtr<OpaqueJSClass> jsClass = (definition->attributes & kJSClassAttributeNoAutomaticPrototype)
? OpaqueJSClass::createNoAutomaticPrototype(definition)
: OpaqueJSClass::create(definition);
return jsClass.release().releaseRef();
}
JSClassRef JSClassRetain(JSClassRef jsClass)
{
jsClass->ref();
return jsClass;
}
void JSClassRelease(JSClassRef jsClass)
{
jsClass->deref();
}
JSObjectRef JSObjectMake(JSContextRef ctx, JSClassRef jsClass, void* data)
{
ExecState* exec = toJS(ctx);
APIEntryShim entryShim(exec);
if (!jsClass)
return toRef(new (exec) JSObject(exec->lexicalGlobalObject()->emptyObjectStructure())); // slightly more efficient
JSCallbackObject<JSObject>* object = new (exec) JSCallbackObject<JSObject>(exec, exec->lexicalGlobalObject()->callbackObjectStructure(), jsClass, data);
if (JSObject* prototype = jsClass->prototype(exec))
object->setPrototype(prototype);
return toRef(object);
}
JSObjectRef JSObjectMakeFunctionWithCallback(JSContextRef ctx, JSStringRef name, JSObjectCallAsFunctionCallback callAsFunction)
{
ExecState* exec = toJS(ctx);
APIEntryShim entryShim(exec);
Identifier nameID = name ? name->identifier(&exec->globalData()) : Identifier(exec, "anonymous");
return toRef(new (exec) JSCallbackFunction(exec, callAsFunction, nameID));
}
JSObjectRef JSObjectMakeConstructor(JSContextRef ctx, JSClassRef jsClass, JSObjectCallAsConstructorCallback callAsConstructor)
{
ExecState* exec = toJS(ctx);
APIEntryShim entryShim(exec);
JSValue jsPrototype = jsClass ? jsClass->prototype(exec) : 0;
if (!jsPrototype)
jsPrototype = exec->lexicalGlobalObject()->objectPrototype();
JSCallbackConstructor* constructor = new (exec) JSCallbackConstructor(exec->lexicalGlobalObject()->callbackConstructorStructure(), jsClass, callAsConstructor);
constructor->putDirect(exec->propertyNames().prototype, jsPrototype, DontEnum | DontDelete | ReadOnly);
return toRef(constructor);
}
JSObjectRef JSObjectMakeFunction(JSContextRef ctx, JSStringRef name, unsigned parameterCount, const JSStringRef parameterNames[], JSStringRef body, JSStringRef sourceURL, int startingLineNumber, JSValueRef* exception)
{
ExecState* exec = toJS(ctx);
APIEntryShim entryShim(exec);
Identifier nameID = name ? name->identifier(&exec->globalData()) : Identifier(exec, "anonymous");
MarkedArgumentBuffer args;
for (unsigned i = 0; i < parameterCount; i++)
args.append(jsString(exec, parameterNames[i]->ustring()));
args.append(jsString(exec, body->ustring()));
JSObject* result = constructFunction(exec, args, nameID, sourceURL->ustring(), startingLineNumber);
if (exec->hadException()) {
if (exception)
*exception = toRef(exec, exec->exception());
exec->clearException();
result = 0;
}
return toRef(result);
}
JSObjectRef JSObjectMakeArray(JSContextRef ctx, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
ExecState* exec = toJS(ctx);
APIEntryShim entryShim(exec);
JSObject* result;
if (argumentCount) {
MarkedArgumentBuffer argList;
for (size_t i = 0; i < argumentCount; ++i)
argList.append(toJS(exec, arguments[i]));
result = constructArray(exec, argList);
} else
result = constructEmptyArray(exec);
if (exec->hadException()) {
if (exception)
*exception = toRef(exec, exec->exception());
exec->clearException();
result = 0;
}
return toRef(result);
}
JSObjectRef JSObjectMakeDate(JSContextRef ctx, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
ExecState* exec = toJS(ctx);
APIEntryShim entryShim(exec);
MarkedArgumentBuffer argList;
for (size_t i = 0; i < argumentCount; ++i)
argList.append(toJS(exec, arguments[i]));
JSObject* result = constructDate(exec, argList);
if (exec->hadException()) {
if (exception)
*exception = toRef(exec, exec->exception());
exec->clearException();
result = 0;
}
return toRef(result);
}
JSObjectRef JSObjectMakeError(JSContextRef ctx, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
ExecState* exec = toJS(ctx);
APIEntryShim entryShim(exec);
MarkedArgumentBuffer argList;
for (size_t i = 0; i < argumentCount; ++i)
argList.append(toJS(exec, arguments[i]));
JSObject* result = constructError(exec, argList);
if (exec->hadException()) {
if (exception)
*exception = toRef(exec, exec->exception());
exec->clearException();
result = 0;
}
return toRef(result);
}
JSObjectRef JSObjectMakeRegExp(JSContextRef ctx, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
ExecState* exec = toJS(ctx);
APIEntryShim entryShim(exec);
MarkedArgumentBuffer argList;
for (size_t i = 0; i < argumentCount; ++i)
argList.append(toJS(exec, arguments[i]));
JSObject* result = constructRegExp(exec, argList);
if (exec->hadException()) {
if (exception)
*exception = toRef(exec, exec->exception());
exec->clearException();
result = 0;
}
return toRef(result);
}
JSValueRef JSObjectGetPrototype(JSContextRef ctx, JSObjectRef object)
{
ExecState* exec = toJS(ctx);
APIEntryShim entryShim(exec);
JSObject* jsObject = toJS(object);
return toRef(exec, jsObject->prototype());
}
void JSObjectSetPrototype(JSContextRef ctx, JSObjectRef object, JSValueRef value)
{
ExecState* exec = toJS(ctx);
APIEntryShim entryShim(exec);
JSObject* jsObject = toJS(object);
JSValue jsValue = toJS(exec, value);
jsObject->setPrototype(jsValue.isObject() ? jsValue : jsNull());
}
bool JSObjectHasProperty(JSContextRef ctx, JSObjectRef object, JSStringRef propertyName)
{
ExecState* exec = toJS(ctx);
APIEntryShim entryShim(exec);
JSObject* jsObject = toJS(object);
return jsObject->hasProperty(exec, propertyName->identifier(&exec->globalData()));
}
JSValueRef JSObjectGetProperty(JSContextRef ctx, JSObjectRef object, JSStringRef propertyName, JSValueRef* exception)
{
ExecState* exec = toJS(ctx);
APIEntryShim entryShim(exec);
JSObject* jsObject = toJS(object);
JSValue jsValue = jsObject->get(exec, propertyName->identifier(&exec->globalData()));
if (exec->hadException()) {
if (exception)
*exception = toRef(exec, exec->exception());
exec->clearException();
}
return toRef(exec, jsValue);
}
void JSObjectSetProperty(JSContextRef ctx, JSObjectRef object, JSStringRef propertyName, JSValueRef value, JSPropertyAttributes attributes, JSValueRef* exception)
{
ExecState* exec = toJS(ctx);
APIEntryShim entryShim(exec);
JSObject* jsObject = toJS(object);
Identifier name(propertyName->identifier(&exec->globalData()));
JSValue jsValue = toJS(exec, value);
if (attributes && !jsObject->hasProperty(exec, name))
jsObject->putWithAttributes(exec, name, jsValue, attributes);
else {
PutPropertySlot slot;
jsObject->put(exec, name, jsValue, slot);
}
if (exec->hadException()) {
if (exception)
*exception = toRef(exec, exec->exception());
exec->clearException();
}
}
JSValueRef JSObjectGetPropertyAtIndex(JSContextRef ctx, JSObjectRef object, unsigned propertyIndex, JSValueRef* exception)
{
ExecState* exec = toJS(ctx);
APIEntryShim entryShim(exec);
JSObject* jsObject = toJS(object);
JSValue jsValue = jsObject->get(exec, propertyIndex);
if (exec->hadException()) {
if (exception)
*exception = toRef(exec, exec->exception());
exec->clearException();
}
return toRef(exec, jsValue);
}
void JSObjectSetPropertyAtIndex(JSContextRef ctx, JSObjectRef object, unsigned propertyIndex, JSValueRef value, JSValueRef* exception)
{
ExecState* exec = toJS(ctx);
APIEntryShim entryShim(exec);
JSObject* jsObject = toJS(object);
JSValue jsValue = toJS(exec, value);
jsObject->put(exec, propertyIndex, jsValue);
if (exec->hadException()) {
if (exception)
*exception = toRef(exec, exec->exception());
exec->clearException();
}
}
bool JSObjectDeleteProperty(JSContextRef ctx, JSObjectRef object, JSStringRef propertyName, JSValueRef* exception)
{
ExecState* exec = toJS(ctx);
APIEntryShim entryShim(exec);
JSObject* jsObject = toJS(object);
bool result = jsObject->deleteProperty(exec, propertyName->identifier(&exec->globalData()));
if (exec->hadException()) {
if (exception)
*exception = toRef(exec, exec->exception());
exec->clearException();
}
return result;
}
void* JSObjectGetPrivate(JSObjectRef object)
{
JSObject* jsObject = toJS(object);
if (jsObject->inherits(&JSGlobalObject::info))
return static_cast<JSCallbackObject<JSGlobalObject>*>(jsObject)->getPrivate();
else if (jsObject->inherits(&JSObject::info))
return static_cast<JSCallbackObject<JSObject>*>(jsObject)->getPrivate();
return 0;
}
bool JSObjectSetPrivate(JSObjectRef object, void* data)
{
JSObject* jsObject = toJS(object);
if (jsObject->inherits(&JSGlobalObject::info)) {
static_cast<JSCallbackObject<JSGlobalObject>*>(jsObject)->setPrivate(data);
return true;
} else if (jsObject->inherits(&JSObject::info)) {
static_cast<JSCallbackObject<JSObject>*>(jsObject)->setPrivate(data);
return true;
}
return false;
}
bool JSObjectIsFunction(JSContextRef, JSObjectRef object)
{
CallData callData;
return toJS(object)->getCallData(callData) != CallTypeNone;
}
JSValueRef JSObjectCallAsFunction(JSContextRef ctx, JSObjectRef object, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
ExecState* exec = toJS(ctx);
APIEntryShim entryShim(exec);
JSObject* jsObject = toJS(object);
JSObject* jsThisObject = toJS(thisObject);
if (!jsThisObject)
jsThisObject = exec->globalThisValue();
MarkedArgumentBuffer argList;
for (size_t i = 0; i < argumentCount; i++)
argList.append(toJS(exec, arguments[i]));
CallData callData;
CallType callType = jsObject->getCallData(callData);
if (callType == CallTypeNone)
return 0;
JSValueRef result = toRef(exec, call(exec, jsObject, callType, callData, jsThisObject, argList));
if (exec->hadException()) {
if (exception)
*exception = toRef(exec, exec->exception());
exec->clearException();
result = 0;
}
return result;
}
bool JSObjectIsConstructor(JSContextRef, JSObjectRef object)
{
JSObject* jsObject = toJS(object);
ConstructData constructData;
return jsObject->getConstructData(constructData) != ConstructTypeNone;
}
JSObjectRef JSObjectCallAsConstructor(JSContextRef ctx, JSObjectRef object, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
ExecState* exec = toJS(ctx);
APIEntryShim entryShim(exec);
JSObject* jsObject = toJS(object);
ConstructData constructData;
ConstructType constructType = jsObject->getConstructData(constructData);
if (constructType == ConstructTypeNone)
return 0;
MarkedArgumentBuffer argList;
for (size_t i = 0; i < argumentCount; i++)
argList.append(toJS(exec, arguments[i]));
JSObjectRef result = toRef(construct(exec, jsObject, constructType, constructData, argList));
if (exec->hadException()) {
if (exception)
*exception = toRef(exec, exec->exception());
exec->clearException();
result = 0;
}
return result;
}
struct OpaqueJSPropertyNameArray : FastAllocBase {
OpaqueJSPropertyNameArray(JSGlobalData* globalData)
: refCount(0)
, globalData(globalData)
{
}
unsigned refCount;
JSGlobalData* globalData;
Vector<JSRetainPtr<JSStringRef> > array;
};
JSPropertyNameArrayRef JSObjectCopyPropertyNames(JSContextRef ctx, JSObjectRef object)
{
JSObject* jsObject = toJS(object);
ExecState* exec = toJS(ctx);
APIEntryShim entryShim(exec);
JSGlobalData* globalData = &exec->globalData();
JSPropertyNameArrayRef propertyNames = new OpaqueJSPropertyNameArray(globalData);
PropertyNameArray array(globalData);
jsObject->getPropertyNames(exec, array);
size_t size = array.size();
propertyNames->array.reserveInitialCapacity(size);
for (size_t i = 0; i < size; ++i)
propertyNames->array.append(JSRetainPtr<JSStringRef>(Adopt, OpaqueJSString::create(array[i].ustring()).releaseRef()));
return JSPropertyNameArrayRetain(propertyNames);
}
JSPropertyNameArrayRef JSPropertyNameArrayRetain(JSPropertyNameArrayRef array)
{
++array->refCount;
return array;
}
void JSPropertyNameArrayRelease(JSPropertyNameArrayRef array)
{
if (--array->refCount == 0) {
APIEntryShim entryShim(array->globalData);
delete array;
}
}
size_t JSPropertyNameArrayGetCount(JSPropertyNameArrayRef array)
{
return array->array.size();
}
JSStringRef JSPropertyNameArrayGetNameAtIndex(JSPropertyNameArrayRef array, size_t index)
{
return array->array[static_cast<unsigned>(index)].get();
}
void JSPropertyNameAccumulatorAddName(JSPropertyNameAccumulatorRef array, JSStringRef propertyName)
{
PropertyNameArray* propertyNames = toJS(array);
APIEntryShim entryShim(propertyNames->globalData());
propertyNames->add(propertyName->identifier(propertyNames->globalData()));
}

View file

@ -1,690 +0,0 @@
/*
* Copyright (C) 2006, 2007 Apple Inc. All rights reserved.
* Copyright (C) 2008 Kelvin W Sherlock (ksherlock@gmail.com)
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef JSObjectRef_h
#define JSObjectRef_h
#include <JSBase.h>
#include <JSValueRef.h>
#include <stddef.h> /* for size_t */
#ifdef __cplusplus
extern "C" {
#endif
/*!
@enum JSPropertyAttribute
@constant kJSPropertyAttributeNone Specifies that a property has no special attributes.
@constant kJSPropertyAttributeReadOnly Specifies that a property is read-only.
@constant kJSPropertyAttributeDontEnum Specifies that a property should not be enumerated by JSPropertyEnumerators and JavaScript for...in loops.
@constant kJSPropertyAttributeDontDelete Specifies that the delete operation should fail on a property.
*/
enum {
kJSPropertyAttributeNone = 0,
kJSPropertyAttributeReadOnly = 1 << 1,
kJSPropertyAttributeDontEnum = 1 << 2,
kJSPropertyAttributeDontDelete = 1 << 3
};
/*!
@typedef JSPropertyAttributes
@abstract A set of JSPropertyAttributes. Combine multiple attributes by logically ORing them together.
*/
typedef unsigned JSPropertyAttributes;
/*!
@enum JSClassAttribute
@constant kJSClassAttributeNone Specifies that a class has no special attributes.
@constant kJSClassAttributeNoAutomaticPrototype Specifies that a class should not automatically generate a shared prototype for its instance objects. Use kJSClassAttributeNoAutomaticPrototype in combination with JSObjectSetPrototype to manage prototypes manually.
*/
enum {
kJSClassAttributeNone = 0,
kJSClassAttributeNoAutomaticPrototype = 1 << 1
};
/*!
@typedef JSClassAttributes
@abstract A set of JSClassAttributes. Combine multiple attributes by logically ORing them together.
*/
typedef unsigned JSClassAttributes;
/*!
@typedef JSObjectInitializeCallback
@abstract The callback invoked when an object is first created.
@param ctx The execution context to use.
@param object The JSObject being created.
@discussion If you named your function Initialize, you would declare it like this:
void Initialize(JSContextRef ctx, JSObjectRef object);
Unlike the other object callbacks, the initialize callback is called on the least
derived class (the parent class) first, and the most derived class last.
*/
typedef void
(*JSObjectInitializeCallback) (JSContextRef ctx, JSObjectRef object);
/*!
@typedef JSObjectFinalizeCallback
@abstract The callback invoked when an object is finalized (prepared for garbage collection). An object may be finalized on any thread.
@param object The JSObject being finalized.
@discussion If you named your function Finalize, you would declare it like this:
void Finalize(JSObjectRef object);
The finalize callback is called on the most derived class first, and the least
derived class (the parent class) last.
You must not call any function that may cause a garbage collection or an allocation
of a garbage collected object from within a JSObjectFinalizeCallback. This includes
all functions that have a JSContextRef parameter.
*/
typedef void
(*JSObjectFinalizeCallback) (JSObjectRef object);
/*!
@typedef JSObjectHasPropertyCallback
@abstract The callback invoked when determining whether an object has a property.
@param ctx The execution context to use.
@param object The JSObject to search for the property.
@param propertyName A JSString containing the name of the property look up.
@result true if object has the property, otherwise false.
@discussion If you named your function HasProperty, you would declare it like this:
bool HasProperty(JSContextRef ctx, JSObjectRef object, JSStringRef propertyName);
If this function returns false, the hasProperty request forwards to object's statically declared properties, then its parent class chain (which includes the default object class), then its prototype chain.
This callback enables optimization in cases where only a property's existence needs to be known, not its value, and computing its value would be expensive.
If this callback is NULL, the getProperty callback will be used to service hasProperty requests.
*/
typedef bool
(*JSObjectHasPropertyCallback) (JSContextRef ctx, JSObjectRef object, JSStringRef propertyName);
/*!
@typedef JSObjectGetPropertyCallback
@abstract The callback invoked when getting a property's value.
@param ctx The execution context to use.
@param object The JSObject to search for the property.
@param propertyName A JSString containing the name of the property to get.
@param exception A pointer to a JSValueRef in which to return an exception, if any.
@result The property's value if object has the property, otherwise NULL.
@discussion If you named your function GetProperty, you would declare it like this:
JSValueRef GetProperty(JSContextRef ctx, JSObjectRef object, JSStringRef propertyName, JSValueRef* exception);
If this function returns NULL, the get request forwards to object's statically declared properties, then its parent class chain (which includes the default object class), then its prototype chain.
*/
typedef JSValueRef
(*JSObjectGetPropertyCallback) (JSContextRef ctx, JSObjectRef object, JSStringRef propertyName, JSValueRef* exception);
/*!
@typedef JSObjectSetPropertyCallback
@abstract The callback invoked when setting a property's value.
@param ctx The execution context to use.
@param object The JSObject on which to set the property's value.
@param propertyName A JSString containing the name of the property to set.
@param value A JSValue to use as the property's value.
@param exception A pointer to a JSValueRef in which to return an exception, if any.
@result true if the property was set, otherwise false.
@discussion If you named your function SetProperty, you would declare it like this:
bool SetProperty(JSContextRef ctx, JSObjectRef object, JSStringRef propertyName, JSValueRef value, JSValueRef* exception);
If this function returns false, the set request forwards to object's statically declared properties, then its parent class chain (which includes the default object class).
*/
typedef bool
(*JSObjectSetPropertyCallback) (JSContextRef ctx, JSObjectRef object, JSStringRef propertyName, JSValueRef value, JSValueRef* exception);
/*!
@typedef JSObjectDeletePropertyCallback
@abstract The callback invoked when deleting a property.
@param ctx The execution context to use.
@param object The JSObject in which to delete the property.
@param propertyName A JSString containing the name of the property to delete.
@param exception A pointer to a JSValueRef in which to return an exception, if any.
@result true if propertyName was successfully deleted, otherwise false.
@discussion If you named your function DeleteProperty, you would declare it like this:
bool DeleteProperty(JSContextRef ctx, JSObjectRef object, JSStringRef propertyName, JSValueRef* exception);
If this function returns false, the delete request forwards to object's statically declared properties, then its parent class chain (which includes the default object class).
*/
typedef bool
(*JSObjectDeletePropertyCallback) (JSContextRef ctx, JSObjectRef object, JSStringRef propertyName, JSValueRef* exception);
/*!
@typedef JSObjectGetPropertyNamesCallback
@abstract The callback invoked when collecting the names of an object's properties.
@param ctx The execution context to use.
@param object The JSObject whose property names are being collected.
@param accumulator A JavaScript property name accumulator in which to accumulate the names of object's properties.
@discussion If you named your function GetPropertyNames, you would declare it like this:
void GetPropertyNames(JSContextRef ctx, JSObjectRef object, JSPropertyNameAccumulatorRef propertyNames);
Property name accumulators are used by JSObjectCopyPropertyNames and JavaScript for...in loops.
Use JSPropertyNameAccumulatorAddName to add property names to accumulator. A class's getPropertyNames callback only needs to provide the names of properties that the class vends through a custom getProperty or setProperty callback. Other properties, including statically declared properties, properties vended by other classes, and properties belonging to object's prototype, are added independently.
*/
typedef void
(*JSObjectGetPropertyNamesCallback) (JSContextRef ctx, JSObjectRef object, JSPropertyNameAccumulatorRef propertyNames);
/*!
@typedef JSObjectCallAsFunctionCallback
@abstract The callback invoked when an object is called as a function.
@param ctx The execution context to use.
@param function A JSObject that is the function being called.
@param thisObject A JSObject that is the 'this' variable in the function's scope.
@param argumentCount An integer count of the number of arguments in arguments.
@param arguments A JSValue array of the arguments passed to the function.
@param exception A pointer to a JSValueRef in which to return an exception, if any.
@result A JSValue that is the function's return value.
@discussion If you named your function CallAsFunction, you would declare it like this:
JSValueRef CallAsFunction(JSContextRef ctx, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception);
If your callback were invoked by the JavaScript expression 'myObject.myFunction()', function would be set to myFunction, and thisObject would be set to myObject.
If this callback is NULL, calling your object as a function will throw an exception.
*/
typedef JSValueRef
(*JSObjectCallAsFunctionCallback) (JSContextRef ctx, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception);
/*!
@typedef JSObjectCallAsConstructorCallback
@abstract The callback invoked when an object is used as a constructor in a 'new' expression.
@param ctx The execution context to use.
@param constructor A JSObject that is the constructor being called.
@param argumentCount An integer count of the number of arguments in arguments.
@param arguments A JSValue array of the arguments passed to the function.
@param exception A pointer to a JSValueRef in which to return an exception, if any.
@result A JSObject that is the constructor's return value.
@discussion If you named your function CallAsConstructor, you would declare it like this:
JSObjectRef CallAsConstructor(JSContextRef ctx, JSObjectRef constructor, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception);
If your callback were invoked by the JavaScript expression 'new myConstructor()', constructor would be set to myConstructor.
If this callback is NULL, using your object as a constructor in a 'new' expression will throw an exception.
*/
typedef JSObjectRef
(*JSObjectCallAsConstructorCallback) (JSContextRef ctx, JSObjectRef constructor, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception);
/*!
@typedef JSObjectHasInstanceCallback
@abstract hasInstance The callback invoked when an object is used as the target of an 'instanceof' expression.
@param ctx The execution context to use.
@param constructor The JSObject that is the target of the 'instanceof' expression.
@param possibleInstance The JSValue being tested to determine if it is an instance of constructor.
@param exception A pointer to a JSValueRef in which to return an exception, if any.
@result true if possibleInstance is an instance of constructor, otherwise false.
@discussion If you named your function HasInstance, you would declare it like this:
bool HasInstance(JSContextRef ctx, JSObjectRef constructor, JSValueRef possibleInstance, JSValueRef* exception);
If your callback were invoked by the JavaScript expression 'someValue instanceof myObject', constructor would be set to myObject and possibleInstance would be set to someValue.
If this callback is NULL, 'instanceof' expressions that target your object will return false.
Standard JavaScript practice calls for objects that implement the callAsConstructor callback to implement the hasInstance callback as well.
*/
typedef bool
(*JSObjectHasInstanceCallback) (JSContextRef ctx, JSObjectRef constructor, JSValueRef possibleInstance, JSValueRef* exception);
/*!
@typedef JSObjectConvertToTypeCallback
@abstract The callback invoked when converting an object to a particular JavaScript type.
@param ctx The execution context to use.
@param object The JSObject to convert.
@param type A JSType specifying the JavaScript type to convert to.
@param exception A pointer to a JSValueRef in which to return an exception, if any.
@result The objects's converted value, or NULL if the object was not converted.
@discussion If you named your function ConvertToType, you would declare it like this:
JSValueRef ConvertToType(JSContextRef ctx, JSObjectRef object, JSType type, JSValueRef* exception);
If this function returns false, the conversion request forwards to object's parent class chain (which includes the default object class).
This function is only invoked when converting an object to number or string. An object converted to boolean is 'true.' An object converted to object is itself.
*/
typedef JSValueRef
(*JSObjectConvertToTypeCallback) (JSContextRef ctx, JSObjectRef object, JSC::JSType type, JSValueRef* exception);
/*!
@struct JSStaticValue
@abstract This structure describes a statically declared value property.
@field name A null-terminated UTF8 string containing the property's name.
@field getProperty A JSObjectGetPropertyCallback to invoke when getting the property's value.
@field setProperty A JSObjectSetPropertyCallback to invoke when setting the property's value. May be NULL if the ReadOnly attribute is set.
@field attributes A logically ORed set of JSPropertyAttributes to give to the property.
*/
typedef struct {
const char* const name;
JSObjectGetPropertyCallback getProperty;
JSObjectSetPropertyCallback setProperty;
JSPropertyAttributes attributes;
} JSStaticValue;
/*!
@struct JSStaticFunction
@abstract This structure describes a statically declared function property.
@field name A null-terminated UTF8 string containing the property's name.
@field callAsFunction A JSObjectCallAsFunctionCallback to invoke when the property is called as a function.
@field attributes A logically ORed set of JSPropertyAttributes to give to the property.
*/
typedef struct {
const char* const name;
JSObjectCallAsFunctionCallback callAsFunction;
JSPropertyAttributes attributes;
} JSStaticFunction;
/*!
@struct JSClassDefinition
@abstract This structure contains properties and callbacks that define a type of object. All fields other than the version field are optional. Any pointer may be NULL.
@field version The version number of this structure. The current version is 0.
@field attributes A logically ORed set of JSClassAttributes to give to the class.
@field className A null-terminated UTF8 string containing the class's name.
@field parentClass A JSClass to set as the class's parent class. Pass NULL use the default object class.
@field staticValues A JSStaticValue array containing the class's statically declared value properties. Pass NULL to specify no statically declared value properties. The array must be terminated by a JSStaticValue whose name field is NULL.
@field staticFunctions A JSStaticFunction array containing the class's statically declared function properties. Pass NULL to specify no statically declared function properties. The array must be terminated by a JSStaticFunction whose name field is NULL.
@field initialize The callback invoked when an object is first created. Use this callback to initialize the object.
@field finalize The callback invoked when an object is finalized (prepared for garbage collection). Use this callback to release resources allocated for the object, and perform other cleanup.
@field hasProperty The callback invoked when determining whether an object has a property. If this field is NULL, getProperty is called instead. The hasProperty callback enables optimization in cases where only a property's existence needs to be known, not its value, and computing its value is expensive.
@field getProperty The callback invoked when getting a property's value.
@field setProperty The callback invoked when setting a property's value.
@field deleteProperty The callback invoked when deleting a property.
@field getPropertyNames The callback invoked when collecting the names of an object's properties.
@field callAsFunction The callback invoked when an object is called as a function.
@field hasInstance The callback invoked when an object is used as the target of an 'instanceof' expression.
@field callAsConstructor The callback invoked when an object is used as a constructor in a 'new' expression.
@field convertToType The callback invoked when converting an object to a particular JavaScript type.
@discussion The staticValues and staticFunctions arrays are the simplest and most efficient means for vending custom properties. Statically declared properties autmatically service requests like getProperty, setProperty, and getPropertyNames. Property access callbacks are required only to implement unusual properties, like array indexes, whose names are not known at compile-time.
If you named your getter function "GetX" and your setter function "SetX", you would declare a JSStaticValue array containing "X" like this:
JSStaticValue StaticValueArray[] = {
{ "X", GetX, SetX, kJSPropertyAttributeNone },
{ 0, 0, 0, 0 }
};
Standard JavaScript practice calls for storing function objects in prototypes, so they can be shared. The default JSClass created by JSClassCreate follows this idiom, instantiating objects with a shared, automatically generating prototype containing the class's function objects. The kJSClassAttributeNoAutomaticPrototype attribute specifies that a JSClass should not automatically generate such a prototype. The resulting JSClass instantiates objects with the default object prototype, and gives each instance object its own copy of the class's function objects.
A NULL callback specifies that the default object callback should substitute, except in the case of hasProperty, where it specifies that getProperty should substitute.
*/
typedef struct {
int version; /* current (and only) version is 0 */
JSClassAttributes attributes;
const char* className;
JSClassRef parentClass;
const JSStaticValue* staticValues;
const JSStaticFunction* staticFunctions;
JSObjectInitializeCallback initialize;
JSObjectFinalizeCallback finalize;
JSObjectHasPropertyCallback hasProperty;
JSObjectGetPropertyCallback getProperty;
JSObjectSetPropertyCallback setProperty;
JSObjectDeletePropertyCallback deleteProperty;
JSObjectGetPropertyNamesCallback getPropertyNames;
JSObjectCallAsFunctionCallback callAsFunction;
JSObjectCallAsConstructorCallback callAsConstructor;
JSObjectHasInstanceCallback hasInstance;
JSObjectConvertToTypeCallback convertToType;
} JSClassDefinition;
/*!
@const kJSClassDefinitionEmpty
@abstract A JSClassDefinition structure of the current version, filled with NULL pointers and having no attributes.
@discussion Use this constant as a convenience when creating class definitions. For example, to create a class definition with only a finalize method:
JSClassDefinition definition = kJSClassDefinitionEmpty;
definition.finalize = Finalize;
*/
JS_EXPORT extern const JSClassDefinition kJSClassDefinitionEmpty;
/*!
@function
@abstract Creates a JavaScript class suitable for use with JSObjectMake.
@param definition A JSClassDefinition that defines the class.
@result A JSClass with the given definition. Ownership follows the Create Rule.
*/
JS_EXPORT JSClassRef JSClassCreate(const JSClassDefinition* definition);
/*!
@function
@abstract Retains a JavaScript class.
@param jsClass The JSClass to retain.
@result A JSClass that is the same as jsClass.
*/
JS_EXPORT JSClassRef JSClassRetain(JSClassRef jsClass);
/*!
@function
@abstract Releases a JavaScript class.
@param jsClass The JSClass to release.
*/
JS_EXPORT void JSClassRelease(JSClassRef jsClass);
/*!
@function
@abstract Creates a JavaScript object.
@param ctx The execution context to use.
@param jsClass The JSClass to assign to the object. Pass NULL to use the default object class.
@param data A void* to set as the object's private data. Pass NULL to specify no private data.
@result A JSObject with the given class and private data.
@discussion The default object class does not allocate storage for private data, so you must provide a non-NULL jsClass to JSObjectMake if you want your object to be able to store private data.
data is set on the created object before the intialize methods in its class chain are called. This enables the initialize methods to retrieve and manipulate data through JSObjectGetPrivate.
*/
JS_EXPORT JSObjectRef JSObjectMake(JSContextRef ctx, JSClassRef jsClass, void* data);
/*!
@function
@abstract Convenience method for creating a JavaScript function with a given callback as its implementation.
@param ctx The execution context to use.
@param name A JSString containing the function's name. This will be used when converting the function to string. Pass NULL to create an anonymous function.
@param callAsFunction The JSObjectCallAsFunctionCallback to invoke when the function is called.
@result A JSObject that is a function. The object's prototype will be the default function prototype.
*/
JS_EXPORT JSObjectRef JSObjectMakeFunctionWithCallback(JSContextRef ctx, JSStringRef name, JSObjectCallAsFunctionCallback callAsFunction);
/*!
@function
@abstract Convenience method for creating a JavaScript constructor.
@param ctx The execution context to use.
@param jsClass A JSClass that is the class your constructor will assign to the objects its constructs. jsClass will be used to set the constructor's .prototype property, and to evaluate 'instanceof' expressions. Pass NULL to use the default object class.
@param callAsConstructor A JSObjectCallAsConstructorCallback to invoke when your constructor is used in a 'new' expression. Pass NULL to use the default object constructor.
@result A JSObject that is a constructor. The object's prototype will be the default object prototype.
@discussion The default object constructor takes no arguments and constructs an object of class jsClass with no private data.
*/
JS_EXPORT JSObjectRef JSObjectMakeConstructor(JSContextRef ctx, JSClassRef jsClass, JSObjectCallAsConstructorCallback callAsConstructor);
/*!
@function
@abstract Creates a JavaScript Array object.
@param ctx The execution context to use.
@param argumentCount An integer count of the number of arguments in arguments.
@param arguments A JSValue array of data to populate the Array with. Pass NULL if argumentCount is 0.
@param exception A pointer to a JSValueRef in which to store an exception, if any. Pass NULL if you do not care to store an exception.
@result A JSObject that is an Array.
@discussion The behavior of this function does not exactly match the behavior of the built-in Array constructor. Specifically, if one argument
is supplied, this function returns an array with one element.
*/
JS_EXPORT JSObjectRef JSObjectMakeArray(JSContextRef ctx, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception);
/*!
@function
@abstract Creates a JavaScript Date object, as if by invoking the built-in Date constructor.
@param ctx The execution context to use.
@param argumentCount An integer count of the number of arguments in arguments.
@param arguments A JSValue array of arguments to pass to the Date Constructor. Pass NULL if argumentCount is 0.
@param exception A pointer to a JSValueRef in which to store an exception, if any. Pass NULL if you do not care to store an exception.
@result A JSObject that is a Date.
*/
JS_EXPORT JSObjectRef JSObjectMakeDate(JSContextRef ctx, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception);
/*!
@function
@abstract Creates a JavaScript Error object, as if by invoking the built-in Error constructor.
@param ctx The execution context to use.
@param argumentCount An integer count of the number of arguments in arguments.
@param arguments A JSValue array of arguments to pass to the Error Constructor. Pass NULL if argumentCount is 0.
@param exception A pointer to a JSValueRef in which to store an exception, if any. Pass NULL if you do not care to store an exception.
@result A JSObject that is a Error.
*/
JS_EXPORT JSObjectRef JSObjectMakeError(JSContextRef ctx, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception);
/*!
@function
@abstract Creates a JavaScript RegExp object, as if by invoking the built-in RegExp constructor.
@param ctx The execution context to use.
@param argumentCount An integer count of the number of arguments in arguments.
@param arguments A JSValue array of arguments to pass to the RegExp Constructor. Pass NULL if argumentCount is 0.
@param exception A pointer to a JSValueRef in which to store an exception, if any. Pass NULL if you do not care to store an exception.
@result A JSObject that is a RegExp.
*/
JS_EXPORT JSObjectRef JSObjectMakeRegExp(JSContextRef ctx, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception);
/*!
@function
@abstract Creates a function with a given script as its body.
@param ctx The execution context to use.
@param name A JSString containing the function's name. This will be used when converting the function to string. Pass NULL to create an anonymous function.
@param parameterCount An integer count of the number of parameter names in parameterNames.
@param parameterNames A JSString array containing the names of the function's parameters. Pass NULL if parameterCount is 0.
@param body A JSString containing the script to use as the function's body.
@param sourceURL A JSString containing a URL for the script's source file. This is only used when reporting exceptions. Pass NULL if you do not care to include source file information in exceptions.
@param startingLineNumber An integer value specifying the script's starting line number in the file located at sourceURL. This is only used when reporting exceptions.
@param exception A pointer to a JSValueRef in which to store a syntax error exception, if any. Pass NULL if you do not care to store a syntax error exception.
@result A JSObject that is a function, or NULL if either body or parameterNames contains a syntax error. The object's prototype will be the default function prototype.
@discussion Use this method when you want to execute a script repeatedly, to avoid the cost of re-parsing the script before each execution.
*/
JS_EXPORT JSObjectRef JSObjectMakeFunction(JSContextRef ctx, JSStringRef name, unsigned parameterCount, const JSStringRef parameterNames[], JSStringRef body, JSStringRef sourceURL, int startingLineNumber, JSValueRef* exception);
/*!
@function
@abstract Gets an object's prototype.
@param ctx The execution context to use.
@param object A JSObject whose prototype you want to get.
@result A JSValue that is the object's prototype.
*/
JS_EXPORT JSValueRef JSObjectGetPrototype(JSContextRef ctx, JSObjectRef object);
/*!
@function
@abstract Sets an object's prototype.
@param ctx The execution context to use.
@param object The JSObject whose prototype you want to set.
@param value A JSValue to set as the object's prototype.
*/
JS_EXPORT void JSObjectSetPrototype(JSContextRef ctx, JSObjectRef object, JSValueRef value);
/*!
@function
@abstract Tests whether an object has a given property.
@param object The JSObject to test.
@param propertyName A JSString containing the property's name.
@result true if the object has a property whose name matches propertyName, otherwise false.
*/
JS_EXPORT bool JSObjectHasProperty(JSContextRef ctx, JSObjectRef object, JSStringRef propertyName);
/*!
@function
@abstract Gets a property from an object.
@param ctx The execution context to use.
@param object The JSObject whose property you want to get.
@param propertyName A JSString containing the property's name.
@param exception A pointer to a JSValueRef in which to store an exception, if any. Pass NULL if you do not care to store an exception.
@result The property's value if object has the property, otherwise the undefined value.
*/
JS_EXPORT JSValueRef JSObjectGetProperty(JSContextRef ctx, JSObjectRef object, JSStringRef propertyName, JSValueRef* exception);
/*!
@function
@abstract Sets a property on an object.
@param ctx The execution context to use.
@param object The JSObject whose property you want to set.
@param propertyName A JSString containing the property's name.
@param value A JSValue to use as the property's value.
@param exception A pointer to a JSValueRef in which to store an exception, if any. Pass NULL if you do not care to store an exception.
@param attributes A logically ORed set of JSPropertyAttributes to give to the property.
*/
JS_EXPORT void JSObjectSetProperty(JSContextRef ctx, JSObjectRef object, JSStringRef propertyName, JSValueRef value, JSPropertyAttributes attributes, JSValueRef* exception);
/*!
@function
@abstract Deletes a property from an object.
@param ctx The execution context to use.
@param object The JSObject whose property you want to delete.
@param propertyName A JSString containing the property's name.
@param exception A pointer to a JSValueRef in which to store an exception, if any. Pass NULL if you do not care to store an exception.
@result true if the delete operation succeeds, otherwise false (for example, if the property has the kJSPropertyAttributeDontDelete attribute set).
*/
JS_EXPORT bool JSObjectDeleteProperty(JSContextRef ctx, JSObjectRef object, JSStringRef propertyName, JSValueRef* exception);
/*!
@function
@abstract Gets a property from an object by numeric index.
@param ctx The execution context to use.
@param object The JSObject whose property you want to get.
@param propertyIndex An integer value that is the property's name.
@param exception A pointer to a JSValueRef in which to store an exception, if any. Pass NULL if you do not care to store an exception.
@result The property's value if object has the property, otherwise the undefined value.
@discussion Calling JSObjectGetPropertyAtIndex is equivalent to calling JSObjectGetProperty with a string containing propertyIndex, but JSObjectGetPropertyAtIndex provides optimized access to numeric properties.
*/
JS_EXPORT JSValueRef JSObjectGetPropertyAtIndex(JSContextRef ctx, JSObjectRef object, unsigned propertyIndex, JSValueRef* exception);
/*!
@function
@abstract Sets a property on an object by numeric index.
@param ctx The execution context to use.
@param object The JSObject whose property you want to set.
@param propertyIndex The property's name as a number.
@param value A JSValue to use as the property's value.
@param exception A pointer to a JSValueRef in which to store an exception, if any. Pass NULL if you do not care to store an exception.
@discussion Calling JSObjectSetPropertyAtIndex is equivalent to calling JSObjectSetProperty with a string containing propertyIndex, but JSObjectSetPropertyAtIndex provides optimized access to numeric properties.
*/
JS_EXPORT void JSObjectSetPropertyAtIndex(JSContextRef ctx, JSObjectRef object, unsigned propertyIndex, JSValueRef value, JSValueRef* exception);
/*!
@function
@abstract Gets an object's private data.
@param object A JSObject whose private data you want to get.
@result A void* that is the object's private data, if the object has private data, otherwise NULL.
*/
JS_EXPORT void* JSObjectGetPrivate(JSObjectRef object);
/*!
@function
@abstract Sets a pointer to private data on an object.
@param object The JSObject whose private data you want to set.
@param data A void* to set as the object's private data.
@result true if object can store private data, otherwise false.
@discussion The default object class does not allocate storage for private data. Only objects created with a non-NULL JSClass can store private data.
*/
JS_EXPORT bool JSObjectSetPrivate(JSObjectRef object, void* data);
/*!
@function
@abstract Tests whether an object can be called as a function.
@param ctx The execution context to use.
@param object The JSObject to test.
@result true if the object can be called as a function, otherwise false.
*/
JS_EXPORT bool JSObjectIsFunction(JSContextRef ctx, JSObjectRef object);
/*!
@function
@abstract Calls an object as a function.
@param ctx The execution context to use.
@param object The JSObject to call as a function.
@param thisObject The object to use as "this," or NULL to use the global object as "this."
@param argumentCount An integer count of the number of arguments in arguments.
@param arguments A JSValue array of arguments to pass to the function. Pass NULL if argumentCount is 0.
@param exception A pointer to a JSValueRef in which to store an exception, if any. Pass NULL if you do not care to store an exception.
@result The JSValue that results from calling object as a function, or NULL if an exception is thrown or object is not a function.
*/
JS_EXPORT JSValueRef JSObjectCallAsFunction(JSContextRef ctx, JSObjectRef object, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception);
/*!
@function
@abstract Tests whether an object can be called as a constructor.
@param ctx The execution context to use.
@param object The JSObject to test.
@result true if the object can be called as a constructor, otherwise false.
*/
JS_EXPORT bool JSObjectIsConstructor(JSContextRef ctx, JSObjectRef object);
/*!
@function
@abstract Calls an object as a constructor.
@param ctx The execution context to use.
@param object The JSObject to call as a constructor.
@param argumentCount An integer count of the number of arguments in arguments.
@param arguments A JSValue array of arguments to pass to the constructor. Pass NULL if argumentCount is 0.
@param exception A pointer to a JSValueRef in which to store an exception, if any. Pass NULL if you do not care to store an exception.
@result The JSObject that results from calling object as a constructor, or NULL if an exception is thrown or object is not a constructor.
*/
JS_EXPORT JSObjectRef JSObjectCallAsConstructor(JSContextRef ctx, JSObjectRef object, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception);
/*!
@function
@abstract Gets the names of an object's enumerable properties.
@param ctx The execution context to use.
@param object The object whose property names you want to get.
@result A JSPropertyNameArray containing the names object's enumerable properties. Ownership follows the Create Rule.
*/
JS_EXPORT JSPropertyNameArrayRef JSObjectCopyPropertyNames(JSContextRef ctx, JSObjectRef object);
/*!
@function
@abstract Retains a JavaScript property name array.
@param array The JSPropertyNameArray to retain.
@result A JSPropertyNameArray that is the same as array.
*/
JS_EXPORT JSPropertyNameArrayRef JSPropertyNameArrayRetain(JSPropertyNameArrayRef array);
/*!
@function
@abstract Releases a JavaScript property name array.
@param array The JSPropetyNameArray to release.
*/
JS_EXPORT void JSPropertyNameArrayRelease(JSPropertyNameArrayRef array);
/*!
@function
@abstract Gets a count of the number of items in a JavaScript property name array.
@param array The array from which to retrieve the count.
@result An integer count of the number of names in array.
*/
JS_EXPORT size_t JSPropertyNameArrayGetCount(JSPropertyNameArrayRef array);
/*!
@function
@abstract Gets a property name at a given index in a JavaScript property name array.
@param array The array from which to retrieve the property name.
@param index The index of the property name to retrieve.
@result A JSStringRef containing the property name.
*/
JS_EXPORT JSStringRef JSPropertyNameArrayGetNameAtIndex(JSPropertyNameArrayRef array, size_t index);
/*!
@function
@abstract Adds a property name to a JavaScript property name accumulator.
@param accumulator The accumulator object to which to add the property name.
@param propertyName The property name to add.
*/
JS_EXPORT void JSPropertyNameAccumulatorAddName(JSPropertyNameAccumulatorRef accumulator, JSStringRef propertyName);
#ifdef __cplusplus
}
#endif
#endif /* JSObjectRef_h */

View file

@ -1,173 +0,0 @@
/*
* Copyright (C) 2005, 2006, 2007 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef JSRetainPtr_h
#define JSRetainPtr_h
#include <JSStringRef.h>
#include <algorithm>
inline void JSRetain(JSStringRef string) { JSStringRetain(string); }
inline void JSRelease(JSStringRef string) { JSStringRelease(string); }
enum AdoptTag { Adopt };
template <typename T> class JSRetainPtr {
public:
JSRetainPtr() : m_ptr(0) {}
JSRetainPtr(T ptr) : m_ptr(ptr) { if (ptr) JSRetain(ptr); }
JSRetainPtr(AdoptTag, T ptr) : m_ptr(ptr) { }
JSRetainPtr(const JSRetainPtr& o) : m_ptr(o.m_ptr) { if (T ptr = m_ptr) JSRetain(ptr); }
~JSRetainPtr() { if (T ptr = m_ptr) JSRelease(ptr); }
template <typename U> JSRetainPtr(const JSRetainPtr<U>& o) : m_ptr(o.get()) { if (T ptr = m_ptr) JSRetain(ptr); }
T get() const { return m_ptr; }
T releaseRef() { T tmp = m_ptr; m_ptr = 0; return tmp; }
T operator->() const { return m_ptr; }
bool operator!() const { return !m_ptr; }
// This conversion operator allows implicit conversion to bool but not to other integer types.
typedef T JSRetainPtr::*UnspecifiedBoolType;
operator UnspecifiedBoolType() const { return m_ptr ? &JSRetainPtr::m_ptr : 0; }
JSRetainPtr& operator=(const JSRetainPtr&);
template <typename U> JSRetainPtr& operator=(const JSRetainPtr<U>&);
JSRetainPtr& operator=(T);
template <typename U> JSRetainPtr& operator=(U*);
void adopt(T);
void swap(JSRetainPtr&);
private:
T m_ptr;
};
template <typename T> inline JSRetainPtr<T>& JSRetainPtr<T>::operator=(const JSRetainPtr<T>& o)
{
T optr = o.get();
if (optr)
JSRetain(optr);
T ptr = m_ptr;
m_ptr = optr;
if (ptr)
JSRelease(ptr);
return *this;
}
template <typename T> template <typename U> inline JSRetainPtr<T>& JSRetainPtr<T>::operator=(const JSRetainPtr<U>& o)
{
T optr = o.get();
if (optr)
JSRetain(optr);
T ptr = m_ptr;
m_ptr = optr;
if (ptr)
JSRelease(ptr);
return *this;
}
template <typename T> inline JSRetainPtr<T>& JSRetainPtr<T>::operator=(T optr)
{
if (optr)
JSRetain(optr);
T ptr = m_ptr;
m_ptr = optr;
if (ptr)
JSRelease(ptr);
return *this;
}
template <typename T> inline void JSRetainPtr<T>::adopt(T optr)
{
T ptr = m_ptr;
m_ptr = optr;
if (ptr)
JSRelease(ptr);
}
template <typename T> template <typename U> inline JSRetainPtr<T>& JSRetainPtr<T>::operator=(U* optr)
{
if (optr)
JSRetain(optr);
T ptr = m_ptr;
m_ptr = optr;
if (ptr)
JSRelease(ptr);
return *this;
}
template <class T> inline void JSRetainPtr<T>::swap(JSRetainPtr<T>& o)
{
std::swap(m_ptr, o.m_ptr);
}
template <class T> inline void swap(JSRetainPtr<T>& a, JSRetainPtr<T>& b)
{
a.swap(b);
}
template <typename T, typename U> inline bool operator==(const JSRetainPtr<T>& a, const JSRetainPtr<U>& b)
{
return a.get() == b.get();
}
template <typename T, typename U> inline bool operator==(const JSRetainPtr<T>& a, U* b)
{
return a.get() == b;
}
template <typename T, typename U> inline bool operator==(T* a, const JSRetainPtr<U>& b)
{
return a == b.get();
}
template <typename T, typename U> inline bool operator!=(const JSRetainPtr<T>& a, const JSRetainPtr<U>& b)
{
return a.get() != b.get();
}
template <typename T, typename U> inline bool operator!=(const JSRetainPtr<T>& a, U* b)
{
return a.get() != b;
}
template <typename T, typename U> inline bool operator!=(T* a, const JSRetainPtr<U>& b)
{
return a != b.get();
}
#endif // JSRetainPtr_h

View file

@ -1,73 +0,0 @@
/*
* Copyright (C) 2006, 2007 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "Platform.h"
#include "JSStringRef.h"
#include "InitializeThreading.h"
#include "OpaqueJSString.h"
#include <wtf/unicode/UTF8.h>
using namespace JSC;
using namespace WTF::Unicode;
JSStringRef JSStringCreateWithCharacters(const JSChar* chars, size_t numChars)
{
initializeThreading();
return OpaqueJSString::create(chars, numChars).releaseRef();
}
JSStringRef JSStringRetain(JSStringRef string)
{
string->ref();
return string;
}
void JSStringRelease(JSStringRef string)
{
string->deref();
}
size_t JSStringGetLength(JSStringRef string)
{
return string->length();
}
const JSChar* JSStringGetCharactersPtr(JSStringRef string)
{
return string->characters();
}
size_t JSStringGetMaximumUTF8CStringSize(JSStringRef string)
{
// Any UTF8 character > 3 bytes encodes as a UTF16 surrogate pair.
return string->length() * 3 + 1; // + 1 for terminating '\0'
}
bool JSStringIsEqual(JSStringRef a, JSStringRef b)
{
unsigned len = a->length();
return len == b->length() && 0 == memcmp(a->characters(), b->characters(), len * sizeof(UChar));
}

View file

@ -1,110 +0,0 @@
/*
* Copyright (C) 2006 Apple Computer, Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef JSStringRef_h
#define JSStringRef_h
#include <JSValueRef.h>
#include <stddef.h> /* for size_t */
#ifdef __cplusplus
extern "C" {
#endif
/*!
@typedef JSChar
@abstract A Unicode character.
*/
typedef unsigned short JSChar;
/*!
@function
@abstract Creates a JavaScript string from a buffer of Unicode characters.
@param chars The buffer of Unicode characters to copy into the new JSString.
@param numChars The number of characters to copy from the buffer pointed to by chars.
@result A JSString containing chars. Ownership follows the Create Rule.
*/
JS_EXPORT JSStringRef JSStringCreateWithCharacters(const JSChar* chars, size_t numChars);
/*!
@function
@abstract Retains a JavaScript string.
@param string The JSString to retain.
@result A JSString that is the same as string.
*/
JS_EXPORT JSStringRef JSStringRetain(JSStringRef string);
/*!
@function
@abstract Releases a JavaScript string.
@param string The JSString to release.
*/
JS_EXPORT void JSStringRelease(JSStringRef string);
/*!
@function
@abstract Returns the number of Unicode characters in a JavaScript string.
@param string The JSString whose length (in Unicode characters) you want to know.
@result The number of Unicode characters stored in string.
*/
JS_EXPORT size_t JSStringGetLength(JSStringRef string);
/*!
@function
@abstract Returns a pointer to the Unicode character buffer that
serves as the backing store for a JavaScript string.
@param string The JSString whose backing store you want to access.
@result A pointer to the Unicode character buffer that serves as string's
backing store, which will be deallocated when string is deallocated.
*/
JS_EXPORT const JSChar* JSStringGetCharactersPtr(JSStringRef string);
/*!
@function
@abstract Returns the maximum number of bytes a JavaScript string will
take up if converted into a null-terminated UTF8 string.
@param string The JSString whose maximum converted size (in bytes) you
want to know.
@result The maximum number of bytes that could be required to convert string into a
null-terminated UTF8 string. The number of bytes that the conversion actually ends
up requiring could be less than this, but never more.
*/
JS_EXPORT size_t JSStringGetMaximumUTF8CStringSize(JSStringRef string);
/*!
@function
@abstract Tests whether two JavaScript strings match.
@param a The first JSString to test.
@param b The second JSString to test.
@result true if the two strings match, otherwise false.
*/
JS_EXPORT bool JSStringIsEqual(JSStringRef a, JSStringRef b);
#ifdef __cplusplus
}
#endif
#endif /* JSStringRef_h */

View file

@ -1,301 +0,0 @@
/*
* Copyright (C) 2006, 2007 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "Platform.h"
#include "JSValueRef.h"
#include <wtf/Platform.h>
#include "APICast.h"
#include "APIShims.h"
#include "JSCallbackObject.h"
#include <runtime/JSGlobalObject.h>
#include <runtime/JSString.h>
#include <runtime/Operations.h>
#include <runtime/Protect.h>
#include <runtime/UString.h>
#include <runtime/JSValue.h>
#include <wtf/Assertions.h>
#include <algorithm> // for std::min
using namespace JSC;
::JSType JSValueGetType(JSContextRef ctx, JSValueRef value)
{
ExecState* exec = toJS(ctx);
APIEntryShim entryShim(exec);
JSValue jsValue = toJS(exec, value);
if (jsValue.isUndefined())
return UndefinedType;
if (jsValue.isNull())
return NullType;
if (jsValue.isBoolean())
return BooleanType;
if (jsValue.isNumber())
return NumberType;
if (jsValue.isString())
return StringType;
Q_ASSERT(jsValue.isObject());
return ObjectType;
}
bool JSValueIsUndefined(JSContextRef ctx, JSValueRef value)
{
ExecState* exec = toJS(ctx);
APIEntryShim entryShim(exec);
JSValue jsValue = toJS(exec, value);
return jsValue.isUndefined();
}
bool JSValueIsNull(JSContextRef ctx, JSValueRef value)
{
ExecState* exec = toJS(ctx);
APIEntryShim entryShim(exec);
JSValue jsValue = toJS(exec, value);
return jsValue.isNull();
}
bool JSValueIsBoolean(JSContextRef ctx, JSValueRef value)
{
ExecState* exec = toJS(ctx);
APIEntryShim entryShim(exec);
JSValue jsValue = toJS(exec, value);
return jsValue.isBoolean();
}
bool JSValueIsNumber(JSContextRef ctx, JSValueRef value)
{
ExecState* exec = toJS(ctx);
APIEntryShim entryShim(exec);
JSValue jsValue = toJS(exec, value);
return jsValue.isNumber();
}
bool JSValueIsString(JSContextRef ctx, JSValueRef value)
{
ExecState* exec = toJS(ctx);
APIEntryShim entryShim(exec);
JSValue jsValue = toJS(exec, value);
return jsValue.isString();
}
bool JSValueIsObject(JSContextRef ctx, JSValueRef value)
{
ExecState* exec = toJS(ctx);
APIEntryShim entryShim(exec);
JSValue jsValue = toJS(exec, value);
return jsValue.isObject();
}
bool JSValueIsObjectOfClass(JSContextRef ctx, JSValueRef value, JSClassRef jsClass)
{
ExecState* exec = toJS(ctx);
APIEntryShim entryShim(exec);
JSValue jsValue = toJS(exec, value);
if (JSObject* o = jsValue.getObject()) {
if (o->inherits(&JSCallbackObject<JSGlobalObject>::info))
return static_cast<JSCallbackObject<JSGlobalObject>*>(o)->inherits(jsClass);
else if (o->inherits(&JSCallbackObject<JSObject>::info))
return static_cast<JSCallbackObject<JSObject>*>(o)->inherits(jsClass);
}
return false;
}
bool JSValueIsEqual(JSContextRef ctx, JSValueRef a, JSValueRef b, JSValueRef* exception)
{
ExecState* exec = toJS(ctx);
APIEntryShim entryShim(exec);
JSValue jsA = toJS(exec, a);
JSValue jsB = toJS(exec, b);
bool result = JSValue::equal(exec, jsA, jsB); // false if an exception is thrown
if (exec->hadException()) {
if (exception)
*exception = toRef(exec, exec->exception());
exec->clearException();
}
return result;
}
bool JSValueIsStrictEqual(JSContextRef ctx, JSValueRef a, JSValueRef b)
{
ExecState* exec = toJS(ctx);
APIEntryShim entryShim(exec);
JSValue jsA = toJS(exec, a);
JSValue jsB = toJS(exec, b);
return JSValue::strictEqual(exec, jsA, jsB);
}
bool JSValueIsInstanceOfConstructor(JSContextRef ctx, JSValueRef value, JSObjectRef constructor, JSValueRef* exception)
{
ExecState* exec = toJS(ctx);
APIEntryShim entryShim(exec);
JSValue jsValue = toJS(exec, value);
JSObject* jsConstructor = toJS(constructor);
if (!jsConstructor->structure()->typeInfo().implementsHasInstance())
return false;
bool result = jsConstructor->hasInstance(exec, jsValue, jsConstructor->get(exec, exec->propertyNames().prototype)); // false if an exception is thrown
if (exec->hadException()) {
if (exception)
*exception = toRef(exec, exec->exception());
exec->clearException();
}
return result;
}
JSValueRef JSValueMakeUndefined(JSContextRef ctx)
{
ExecState* exec = toJS(ctx);
APIEntryShim entryShim(exec);
return toRef(exec, jsUndefined());
}
JSValueRef JSValueMakeNull(JSContextRef ctx)
{
ExecState* exec = toJS(ctx);
APIEntryShim entryShim(exec);
return toRef(exec, jsNull());
}
JSValueRef JSValueMakeBoolean(JSContextRef ctx, bool value)
{
ExecState* exec = toJS(ctx);
APIEntryShim entryShim(exec);
return toRef(exec, jsBoolean(value));
}
JSValueRef JSValueMakeNumber(JSContextRef ctx, double value)
{
ExecState* exec = toJS(ctx);
APIEntryShim entryShim(exec);
return toRef(exec, jsNumber(exec, value));
}
JSValueRef JSValueMakeString(JSContextRef ctx, JSStringRef string)
{
ExecState* exec = toJS(ctx);
APIEntryShim entryShim(exec);
return toRef(exec, jsString(exec, string->ustring()));
}
bool JSValueToBoolean(JSContextRef ctx, JSValueRef value)
{
ExecState* exec = toJS(ctx);
APIEntryShim entryShim(exec);
JSValue jsValue = toJS(exec, value);
return jsValue.toBoolean(exec);
}
double JSValueToNumber(JSContextRef ctx, JSValueRef value, JSValueRef* exception)
{
ExecState* exec = toJS(ctx);
APIEntryShim entryShim(exec);
JSValue jsValue = toJS(exec, value);
double number = jsValue.toNumber(exec);
if (exec->hadException()) {
if (exception)
*exception = toRef(exec, exec->exception());
exec->clearException();
number = NaN;
}
return number;
}
JSStringRef JSValueToStringCopy(JSContextRef ctx, JSValueRef value, JSValueRef* exception)
{
ExecState* exec = toJS(ctx);
APIEntryShim entryShim(exec);
JSValue jsValue = toJS(exec, value);
RefPtr<OpaqueJSString> stringRef(OpaqueJSString::create(jsValue.toString(exec)));
if (exec->hadException()) {
if (exception)
*exception = toRef(exec, exec->exception());
exec->clearException();
stringRef.clear();
}
return stringRef.release().releaseRef();
}
JSObjectRef JSValueToObject(JSContextRef ctx, JSValueRef value, JSValueRef* exception)
{
ExecState* exec = toJS(ctx);
APIEntryShim entryShim(exec);
JSValue jsValue = toJS(exec, value);
JSObjectRef objectRef = toRef(jsValue.toObject(exec));
if (exec->hadException()) {
if (exception)
*exception = toRef(exec, exec->exception());
exec->clearException();
objectRef = 0;
}
return objectRef;
}
void JSValueProtect(JSContextRef ctx, JSValueRef value)
{
ExecState* exec = toJS(ctx);
APIEntryShim entryShim(exec);
JSValue jsValue = toJSForGC(exec, value);
gcProtect(jsValue);
}
void JSValueUnprotect(JSContextRef ctx, JSValueRef value)
{
ExecState* exec = toJS(ctx);
APIEntryShim entryShim(exec);
JSValue jsValue = toJSForGC(exec, value);
gcUnprotect(jsValue);
}

View file

@ -1,270 +0,0 @@
/*
* Copyright (C) 2006 Apple Computer, Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef JSValueRef_h
#define JSValueRef_h
#include <JSBase.h>
#include <JSType.h>
/*!
@enum JSType
@abstract A constant identifying the type of a JSValue.
@constant UnspecifiedType
@constant UndefinedType The unique undefined value.
@constant BooleanType A primitive boolean value, one of true or false.
@constant NumberType A primitive number value.
@constant NullType The unique null value.
@constant StringType A primitive string value.
@constant CompoundType
@constant ObjectType An object value (meaning that this JSValueRef is a JSObjectRef).
@constant GetterSetterType
*/
#ifdef __cplusplus
extern "C" {
#endif
/*!
@function
@abstract Returns a JavaScript value's type.
@param ctx The execution context to use.
@param value The JSValue whose type you want to obtain.
@result A value of type JSType that identifies value's type.
*/
JS_EXPORT JSC::JSType JSValueGetType(JSContextRef ctx, JSValueRef value);
/*!
@function
@abstract Tests whether a JavaScript value's type is the undefined type.
@param ctx The execution context to use.
@param value The JSValue to test.
@result true if value's type is the undefined type, otherwise false.
*/
JS_EXPORT bool JSValueIsUndefined(JSContextRef ctx, JSValueRef value);
/*!
@function
@abstract Tests whether a JavaScript value's type is the null type.
@param ctx The execution context to use.
@param value The JSValue to test.
@result true if value's type is the null type, otherwise false.
*/
JS_EXPORT bool JSValueIsNull(JSContextRef ctx, JSValueRef value);
/*!
@function
@abstract Tests whether a JavaScript value's type is the boolean type.
@param ctx The execution context to use.
@param value The JSValue to test.
@result true if value's type is the boolean type, otherwise false.
*/
JS_EXPORT bool JSValueIsBoolean(JSContextRef ctx, JSValueRef value);
/*!
@function
@abstract Tests whether a JavaScript value's type is the number type.
@param ctx The execution context to use.
@param value The JSValue to test.
@result true if value's type is the number type, otherwise false.
*/
JS_EXPORT bool JSValueIsNumber(JSContextRef ctx, JSValueRef value);
/*!
@function
@abstract Tests whether a JavaScript value's type is the string type.
@param ctx The execution context to use.
@param value The JSValue to test.
@result true if value's type is the string type, otherwise false.
*/
JS_EXPORT bool JSValueIsString(JSContextRef ctx, JSValueRef value);
/*!
@function
@abstract Tests whether a JavaScript value's type is the object type.
@param ctx The execution context to use.
@param value The JSValue to test.
@result true if value's type is the object type, otherwise false.
*/
JS_EXPORT bool JSValueIsObject(JSContextRef ctx, JSValueRef value);
/*!
@function
@abstract Tests whether a JavaScript value is an object with a given class in its class chain.
@param ctx The execution context to use.
@param value The JSValue to test.
@param jsClass The JSClass to test against.
@result true if value is an object and has jsClass in its class chain, otherwise false.
*/
JS_EXPORT bool JSValueIsObjectOfClass(JSContextRef ctx, JSValueRef value, JSClassRef jsClass);
/* Comparing values */
/*!
@function
@abstract Tests whether two JavaScript values are equal, as compared by the JS == operator.
@param ctx The execution context to use.
@param a The first value to test.
@param b The second value to test.
@param exception A pointer to a JSValueRef in which to store an exception, if any. Pass NULL if you do not care to store an exception.
@result true if the two values are equal, false if they are not equal or an exception is thrown.
*/
JS_EXPORT bool JSValueIsEqual(JSContextRef ctx, JSValueRef a, JSValueRef b, JSValueRef* exception);
/*!
@function
@abstract Tests whether two JavaScript values are strict equal, as compared by the JS === operator.
@param ctx The execution context to use.
@param a The first value to test.
@param b The second value to test.
@result true if the two values are strict equal, otherwise false.
*/
JS_EXPORT bool JSValueIsStrictEqual(JSContextRef ctx, JSValueRef a, JSValueRef b);
/*!
@function
@abstract Tests whether a JavaScript value is an object constructed by a given constructor, as compared by the JS instanceof operator.
@param ctx The execution context to use.
@param value The JSValue to test.
@param constructor The constructor to test against.
@param exception A pointer to a JSValueRef in which to store an exception, if any. Pass NULL if you do not care to store an exception.
@result true if value is an object constructed by constructor, as compared by the JS instanceof operator, otherwise false.
*/
JS_EXPORT bool JSValueIsInstanceOfConstructor(JSContextRef ctx, JSValueRef value, JSObjectRef constructor, JSValueRef* exception);
/* Creating values */
/*!
@function
@abstract Creates a JavaScript value of the undefined type.
@param ctx The execution context to use.
@result The unique undefined value.
*/
JS_EXPORT JSValueRef JSValueMakeUndefined(JSContextRef ctx);
/*!
@function
@abstract Creates a JavaScript value of the null type.
@param ctx The execution context to use.
@result The unique null value.
*/
JS_EXPORT JSValueRef JSValueMakeNull(JSContextRef ctx);
/*!
@function
@abstract Creates a JavaScript value of the boolean type.
@param ctx The execution context to use.
@param boolean The bool to assign to the newly created JSValue.
@result A JSValue of the boolean type, representing the value of boolean.
*/
JS_EXPORT JSValueRef JSValueMakeBoolean(JSContextRef ctx, bool boolean);
/*!
@function
@abstract Creates a JavaScript value of the number type.
@param ctx The execution context to use.
@param number The double to assign to the newly created JSValue.
@result A JSValue of the number type, representing the value of number.
*/
JS_EXPORT JSValueRef JSValueMakeNumber(JSContextRef ctx, double number);
/*!
@function
@abstract Creates a JavaScript value of the string type.
@param ctx The execution context to use.
@param string The JSString to assign to the newly created JSValue. The
newly created JSValue retains string, and releases it upon garbage collection.
@result A JSValue of the string type, representing the value of string.
*/
JS_EXPORT JSValueRef JSValueMakeString(JSContextRef ctx, JSStringRef string);
/* Converting to primitive values */
/*!
@function
@abstract Converts a JavaScript value to boolean and returns the resulting boolean.
@param ctx The execution context to use.
@param value The JSValue to convert.
@result The boolean result of conversion.
*/
JS_EXPORT bool JSValueToBoolean(JSContextRef ctx, JSValueRef value);
/*!
@function
@abstract Converts a JavaScript value to number and returns the resulting number.
@param ctx The execution context to use.
@param value The JSValue to convert.
@param exception A pointer to a JSValueRef in which to store an exception, if any. Pass NULL if you do not care to store an exception.
@result The numeric result of conversion, or NaN if an exception is thrown.
*/
JS_EXPORT double JSValueToNumber(JSContextRef ctx, JSValueRef value, JSValueRef* exception);
/*!
@function
@abstract Converts a JavaScript value to string and copies the result into a JavaScript string.
@param ctx The execution context to use.
@param value The JSValue to convert.
@param exception A pointer to a JSValueRef in which to store an exception, if any. Pass NULL if you do not care to store an exception.
@result A JSString with the result of conversion, or NULL if an exception is thrown. Ownership follows the Create Rule.
*/
JS_EXPORT JSStringRef JSValueToStringCopy(JSContextRef ctx, JSValueRef value, JSValueRef* exception);
/*!
@function
@abstract Converts a JavaScript value to object and returns the resulting object.
@param ctx The execution context to use.
@param value The JSValue to convert.
@param exception A pointer to a JSValueRef in which to store an exception, if any. Pass NULL if you do not care to store an exception.
@result The JSObject result of conversion, or NULL if an exception is thrown.
*/
JS_EXPORT JSObjectRef JSValueToObject(JSContextRef ctx, JSValueRef value, JSValueRef* exception);
/* Garbage collection */
/*!
@function
@abstract Protects a JavaScript value from garbage collection.
@param ctx The execution context to use.
@param value The JSValue to protect.
@discussion Use this method when you want to store a JSValue in a global or on the heap, where the garbage collector will not be able to discover your reference to it.
A value may be protected multiple times and must be unprotected an equal number of times before becoming eligible for garbage collection.
*/
JS_EXPORT void JSValueProtect(JSContextRef ctx, JSValueRef value);
/*!
@function
@abstract Unprotects a JavaScript value from garbage collection.
@param ctx The execution context to use.
@param value The JSValue to unprotect.
@discussion A value may be protected multiple times and must be unprotected an
equal number of times before becoming eligible for garbage collection.
*/
JS_EXPORT void JSValueUnprotect(JSContextRef ctx, JSValueRef value);
#ifdef __cplusplus
}
#endif
#endif /* JSValueRef_h */

View file

@ -1,36 +0,0 @@
/*
* Copyright (C) 2006, 2008 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef JavaScriptCore_h
#define JavaScriptCore_h
#include <JSBase.h>
#include <JSContextRef.h>
#include <JSStringRef.h>
#include <JSObjectRef.h>
#include <JSValueRef.h>
#include <JSStringRefCF.h>
#endif /* JavaScriptCore_h */

View file

@ -1,55 +0,0 @@
/*
* Copyright (C) 2008 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "Platform.h"
#include "OpaqueJSString.h"
#include <interpreter/CallFrame.h>
#include <runtime/JSGlobalObject.h>
#include <runtime/Identifier.h>
using namespace JSC;
PassRefPtr<OpaqueJSString> OpaqueJSString::create(const UString& ustring)
{
if (!ustring.isNull())
return adoptRef(new OpaqueJSString(ustring.data(), ustring.size()));
return 0;
}
UString OpaqueJSString::ustring() const
{
if (m_characters)
return UString(m_characters, m_length);
return UString::null();
}
Identifier OpaqueJSString::identifier(JSGlobalData* globalData) const
{
if (!m_characters)
return Identifier(globalData, static_cast<const char*>(0));
return Identifier(globalData, m_characters, m_length);
}

View file

@ -1,81 +0,0 @@
/*
* Copyright (C) 2008 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef OpaqueJSString_h
#define OpaqueJSString_h
#include <runtime/UString.h>
namespace JSC {
class Identifier;
class JSGlobalData;
}
struct OpaqueJSString : public ThreadSafeShared<OpaqueJSString> {
static PassRefPtr<OpaqueJSString> create() // null
{
return adoptRef(new OpaqueJSString);
}
static PassRefPtr<OpaqueJSString> create(const UChar* characters, unsigned length)
{
return adoptRef(new OpaqueJSString(characters, length));
}
static PassRefPtr<OpaqueJSString> create(const JSC::UString&);
UChar* characters() { return m_characters; }
unsigned length() { return m_length; }
JSC::UString ustring() const;
JSC::Identifier identifier(JSC::JSGlobalData*) const;
private:
friend class WTF::ThreadSafeShared<OpaqueJSString>;
OpaqueJSString()
: m_characters(0)
, m_length(0)
{
}
OpaqueJSString(const UChar* characters, unsigned length)
: m_length(length)
{
m_characters = new UChar[length];
memcpy(m_characters, characters, length * sizeof(UChar));
}
~OpaqueJSString()
{
delete[] m_characters;
}
UChar* m_characters;
unsigned m_length;
};
#endif

View file

@ -1,2 +0,0 @@
Harri Porten (porten@kde.org)
Peter Kelly (pmk@post.com)

View file

@ -1,488 +0,0 @@
NOTE! The LGPL below is copyrighted by the Free Software Foundation, but
the instance of code that it refers to (the kde libraries) are copyrighted
by the authors who actually wrote it.
---------------------------------------------------------------------------
GNU LIBRARY GENERAL PUBLIC LICENSE
Version 2, June 1991
Copyright (C) 1991 Free Software Foundation, Inc.
51 Franklin Street, Fifth Floor
Boston, MA 02110-1301, USA.
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
[This is the first released version of the library GPL. It is
numbered 2 because it goes with version 2 of the ordinary GPL.]
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
Licenses are intended to guarantee your freedom to share and change
free software--to make sure the software is free for all its users.
This license, the Library General Public License, applies to some
specially designated Free Software Foundation software, and to any
other libraries whose authors decide to use it. You can use it for
your libraries, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
this service if you wish), that you receive source code or can get it
if you want it, that you can change the software or use pieces of it
in new free programs; and that you know you can do these things.
To protect your rights, we need to make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if
you distribute copies of the library, or if you modify it.
For example, if you distribute copies of the library, whether gratis
or for a fee, you must give the recipients all the rights that we gave
you. You must make sure that they, too, receive or can get the source
code. If you link a program with the library, you must provide
complete object files to the recipients so that they can relink them
with the library, after making changes to the library and recompiling
it. And you must show them these terms so they know their rights.
Our method of protecting your rights has two steps: (1) copyright
the library, and (2) offer you this license which gives you legal
permission to copy, distribute and/or modify the library.
Also, for each distributor's protection, we want to make certain
that everyone understands that there is no warranty for this free
library. If the library is modified by someone else and passed on, we
want its recipients to know that what they have is not the original
version, so that any problems introduced by others will not reflect on
the original authors' reputations.
Finally, any free program is threatened constantly by software
patents. We wish to avoid the danger that companies distributing free
software will individually obtain patent licenses, thus in effect
transforming the program into proprietary software. To prevent this,
we have made it clear that any patent must be licensed for everyone's
free use or not licensed at all.
Most GNU software, including some libraries, is covered by the ordinary
GNU General Public License, which was designed for utility programs. This
license, the GNU Library General Public License, applies to certain
designated libraries. This license is quite different from the ordinary
one; be sure to read it in full, and don't assume that anything in it is
the same as in the ordinary license.
The reason we have a separate public license for some libraries is that
they blur the distinction we usually make between modifying or adding to a
program and simply using it. Linking a program with a library, without
changing the library, is in some sense simply using the library, and is
analogous to running a utility program or application program. However, in
a textual and legal sense, the linked executable is a combined work, a
derivative of the original library, and the ordinary General Public License
treats it as such.
Because of this blurred distinction, using the ordinary General
Public License for libraries did not effectively promote software
sharing, because most developers did not use the libraries. We
concluded that weaker conditions might promote sharing better.
However, unrestricted linking of non-free programs would deprive the
users of those programs of all benefit from the free status of the
libraries themselves. This Library General Public License is intended to
permit developers of non-free programs to use free libraries, while
preserving your freedom as a user of such programs to change the free
libraries that are incorporated in them. (We have not seen how to achieve
this as regards changes in header files, but we have achieved it as regards
changes in the actual functions of the Library.) The hope is that this
will lead to faster development of free libraries.
The precise terms and conditions for copying, distribution and
modification follow. Pay close attention to the difference between a
"work based on the library" and a "work that uses the library". The
former contains code derived from the library, while the latter only
works together with the library.
Note that it is possible for a library to be covered by the ordinary
General Public License rather than by this special one.
GNU LIBRARY GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License Agreement applies to any software library which
contains a notice placed by the copyright holder or other authorized
party saying it may be distributed under the terms of this Library
General Public License (also called "this License"). Each licensee is
addressed as "you".
A "library" means a collection of software functions and/or data
prepared so as to be conveniently linked with application programs
(which use some of those functions and data) to form executables.
The "Library", below, refers to any such software library or work
which has been distributed under these terms. A "work based on the
Library" means either the Library or any derivative work under
copyright law: that is to say, a work containing the Library or a
portion of it, either verbatim or with modifications and/or translated
straightforwardly into another language. (Hereinafter, translation is
included without limitation in the term "modification".)
"Source code" for a work means the preferred form of the work for
making modifications to it. For a library, complete source code means
all the source code for all modules it contains, plus any associated
interface definition files, plus the scripts used to control compilation
and installation of the library.
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running a program using the Library is not restricted, and output from
such a program is covered only if its contents constitute a work based
on the Library (independent of the use of the Library in a tool for
writing it). Whether that is true depends on what the Library does
and what the program that uses the Library does.
1. You may copy and distribute verbatim copies of the Library's
complete source code as you receive it, in any medium, provided that
you conspicuously and appropriately publish on each copy an
appropriate copyright notice and disclaimer of warranty; keep intact
all the notices that refer to this License and to the absence of any
warranty; and distribute a copy of this License along with the
Library.
You may charge a fee for the physical act of transferring a copy,
and you may at your option offer warranty protection in exchange for a
fee.
2. You may modify your copy or copies of the Library or any portion
of it, thus forming a work based on the Library, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) The modified work must itself be a software library.
b) You must cause the files modified to carry prominent notices
stating that you changed the files and the date of any change.
c) You must cause the whole of the work to be licensed at no
charge to all third parties under the terms of this License.
d) If a facility in the modified Library refers to a function or a
table of data to be supplied by an application program that uses
the facility, other than as an argument passed when the facility
is invoked, then you must make a good faith effort to ensure that,
in the event an application does not supply such function or
table, the facility still operates, and performs whatever part of
its purpose remains meaningful.
(For example, a function in a library to compute square roots has
a purpose that is entirely well-defined independent of the
application. Therefore, Subsection 2d requires that any
application-supplied function or table used by this function must
be optional: if the application does not supply it, the square
root function must still compute square roots.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Library,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Library, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote
it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Library.
In addition, mere aggregation of another work not based on the Library
with the Library (or with a work based on the Library) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may opt to apply the terms of the ordinary GNU General Public
License instead of this License to a given copy of the Library. To do
this, you must alter all the notices that refer to this License, so
that they refer to the ordinary GNU General Public License, version 2,
instead of to this License. (If a newer version than version 2 of the
ordinary GNU General Public License has appeared, then you can specify
that version instead if you wish.) Do not make any other change in
these notices.
Once this change is made in a given copy, it is irreversible for
that copy, so the ordinary GNU General Public License applies to all
subsequent copies and derivative works made from that copy.
This option is useful when you wish to copy part of the code of
the Library into a program that is not a library.
4. You may copy and distribute the Library (or a portion or
derivative of it, under Section 2) in object code or executable form
under the terms of Sections 1 and 2 above provided that you accompany
it with the complete corresponding machine-readable source code, which
must be distributed under the terms of Sections 1 and 2 above on a
medium customarily used for software interchange.
If distribution of object code is made by offering access to copy
from a designated place, then offering equivalent access to copy the
source code from the same place satisfies the requirement to
distribute the source code, even though third parties are not
compelled to copy the source along with the object code.
5. A program that contains no derivative of any portion of the
Library, but is designed to work with the Library by being compiled or
linked with it, is called a "work that uses the Library". Such a
work, in isolation, is not a derivative work of the Library, and
therefore falls outside the scope of this License.
However, linking a "work that uses the Library" with the Library
creates an executable that is a derivative of the Library (because it
contains portions of the Library), rather than a "work that uses the
library". The executable is therefore covered by this License.
Section 6 states terms for distribution of such executables.
When a "work that uses the Library" uses material from a header file
that is part of the Library, the object code for the work may be a
derivative work of the Library even though the source code is not.
Whether this is true is especially significant if the work can be
linked without the Library, or if the work is itself a library. The
threshold for this to be true is not precisely defined by law.
If such an object file uses only numerical parameters, data
structure layouts and accessors, and small macros and small inline
functions (ten lines or less in length), then the use of the object
file is unrestricted, regardless of whether it is legally a derivative
work. (Executables containing this object code plus portions of the
Library will still fall under Section 6.)
Otherwise, if the work is a derivative of the Library, you may
distribute the object code for the work under the terms of Section 6.
Any executables containing that work also fall under Section 6,
whether or not they are linked directly with the Library itself.
6. As an exception to the Sections above, you may also compile or
link a "work that uses the Library" with the Library to produce a
work containing portions of the Library, and distribute that work
under terms of your choice, provided that the terms permit
modification of the work for the customer's own use and reverse
engineering for debugging such modifications.
You must give prominent notice with each copy of the work that the
Library is used in it and that the Library and its use are covered by
this License. You must supply a copy of this License. If the work
during execution displays copyright notices, you must include the
copyright notice for the Library among them, as well as a reference
directing the user to the copy of this License. Also, you must do one
of these things:
a) Accompany the work with the complete corresponding
machine-readable source code for the Library including whatever
changes were used in the work (which must be distributed under
Sections 1 and 2 above); and, if the work is an executable linked
with the Library, with the complete machine-readable "work that
uses the Library", as object code and/or source code, so that the
user can modify the Library and then relink to produce a modified
executable containing the modified Library. (It is understood
that the user who changes the contents of definitions files in the
Library will not necessarily be able to recompile the application
to use the modified definitions.)
b) Accompany the work with a written offer, valid for at
least three years, to give the same user the materials
specified in Subsection 6a, above, for a charge no more
than the cost of performing this distribution.
c) If distribution of the work is made by offering access to copy
from a designated place, offer equivalent access to copy the above
specified materials from the same place.
d) Verify that the user has already received a copy of these
materials or that you have already sent this user a copy.
For an executable, the required form of the "work that uses the
Library" must include any data and utility programs needed for
reproducing the executable from it. However, as a special exception,
the source code distributed need not include anything that is normally
distributed (in either source or binary form) with the major
components (compiler, kernel, and so on) of the operating system on
which the executable runs, unless that component itself accompanies
the executable.
It may happen that this requirement contradicts the license
restrictions of other proprietary libraries that do not normally
accompany the operating system. Such a contradiction means you cannot
use both them and the Library together in an executable that you
distribute.
7. You may place library facilities that are a work based on the
Library side-by-side in a single library together with other library
facilities not covered by this License, and distribute such a combined
library, provided that the separate distribution of the work based on
the Library and of the other library facilities is otherwise
permitted, and provided that you do these two things:
a) Accompany the combined library with a copy of the same work
based on the Library, uncombined with any other library
facilities. This must be distributed under the terms of the
Sections above.
b) Give prominent notice with the combined library of the fact
that part of it is a work based on the Library, and explaining
where to find the accompanying uncombined form of the same work.
8. You may not copy, modify, sublicense, link with, or distribute
the Library except as expressly provided under this License. Any
attempt otherwise to copy, modify, sublicense, link with, or
distribute the Library is void, and will automatically terminate your
rights under this License. However, parties who have received copies,
or rights, from you under this License will not have their licenses
terminated so long as such parties remain in full compliance.
9. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Library or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Library (or any work based on the
Library), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Library or works based on it.
10. Each time you redistribute the Library (or any work based on the
Library), the recipient automatically receives a license from the
original licensor to copy, distribute, link with or modify the Library
subject to these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.
11. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Library at all. For example, if a patent
license would not permit royalty-free redistribution of the Library by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Library.
If any portion of this section is held invalid or unenforceable under any
particular circumstance, the balance of the section is intended to apply,
and the section as a whole is intended to apply in other circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
12. If the distribution and/or use of the Library is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Library under this License may add
an explicit geographical distribution limitation excluding those countries,
so that distribution is permitted only in or among countries not thus
excluded. In such case, this License incorporates the limitation as if
written in the body of this License.
13. The Free Software Foundation may publish revised and/or new
versions of the Library General Public License from time to time.
Such new versions will be similar in spirit to the present version,
but may differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the Library
specifies a version number of this License which applies to it and
"any later version", you have the option of following the terms and
conditions either of that version or of any later version published by
the Free Software Foundation. If the Library does not specify a
license version number, you may choose any version ever published by
the Free Software Foundation.
14. If you wish to incorporate parts of the Library into other free
programs whose distribution conditions are incompatible with these,
write to the author to ask for permission. For software which is
copyrighted by the Free Software Foundation, write to the Free
Software Foundation; we sometimes make exceptions for this. Our
decision will be guided by the two goals of preserving the free status
of all derivatives of our free software and of promoting the sharing
and reuse of software generally.
NO WARRANTY
15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO
WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY
KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE
LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME
THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY
AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU
FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR
CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE
LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
DAMAGES.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Libraries
If you develop a new library, and you want it to be of the greatest
possible use to the public, we recommend making it free software that
everyone can redistribute and change. You can do so by permitting
redistribution under these terms (or, alternatively, under the terms of the
ordinary General Public License).
To apply these terms, attach the following notices to the library. It is
safest to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least the
"copyright" line and a pointer to where the full notice is found.
<one line to give the library's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Also add information on how to contact you by electronic and paper mail.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the library, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the
library `Frob' (a library for tweaking knobs) written by James Random Hacker.
<signature of Ty Coon>, 1 April 1990
Ty Coon, President of Vice
That's all there is to it!

View file

@ -1,60 +0,0 @@
# Copyright (C) 2006, 2007, 2008, 2009 Apple Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
# its contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
# THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
VPATH = \
$(JavaScriptCore) \
$(JavaScriptCore)/parser \
$(JavaScriptCore)/runtime \
$(JavaScriptCore)/interpreter
#
.PHONY : all
all : \
ArrayPrototype.lut.h \
DatePrototype.lut.h \
Grammar.cpp \
JSONObject.lut.h \
Lexer.lut.h \
MathObject.lut.h \
NumberConstructor.lut.h \
RegExpConstructor.lut.h \
RegExpObject.lut.h \
StringPrototype.lut.h
#
# lookup tables for classes
%.lut.h: create_hash_table %.cpp
$^ -i > $@
Lexer.lut.h: create_hash_table Keywords.table
$^ > $@
# JavaScript language grammar
Grammar.cpp: Grammar.y
bison --no-lines -d -p jscyy $< -o $@ > bison_out.txt 2>&1
perl -p -e 'END { if ($$conflict) { unlink "Grammar.cpp"; die; } } $$conflict ||= /conflict/' < bison_out.txt
rm -f bison_out.txt

View file

@ -1,2 +0,0 @@
This is Git checkout 3ab0f621048fbeb480b687a28ed31d92d8506150
from git://gitorious.org/qtwebkit/qtwebkit.git that has been modified.

View file

@ -1,8 +0,0 @@
I would like to thank the following people for their help:
Richard Moore <rich@kde.org> - for filling the Math object with some life
Daegeun Lee <realking@mizi.com> - for pointing out some bugs and providing
much code for the String and Date object.
Marco Pinelli <pinmc@libero.it> - for his patches
Christian Kirsch <ck@held.mind.de> - for his contribution to the Date object

File diff suppressed because it is too large Load diff

View file

@ -1,398 +0,0 @@
/*
* Copyright (C) 2008, 2009 Apple Inc. All rights reserved.
* Copyright (C) 2008 Cameron Zwarich <cwzwarich@uwaterloo.ca>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef CodeBlock_h
#define CodeBlock_h
#include "EvalCodeCache.h"
#include "Instruction.h"
#include "JSGlobalObject.h"
#include "JumpTable.h"
#include "Nodes.h"
#include "PtrAndFlags.h"
#include "RegExp.h"
#include "UString.h"
#include <wtf/FastAllocBase.h>
#include <wtf/RefPtr.h>
#include <wtf/Vector.h>
// Register numbers used in bytecode operations have different meaning accoring to their ranges:
// 0x80000000-0xFFFFFFFF Negative indicies from the CallFrame pointer are entries in the call frame, see RegisterFile.h.
// 0x00000000-0x3FFFFFFF Forwards indices from the CallFrame pointer are local vars and temporaries with the function's callframe.
// 0x40000000-0x7FFFFFFF Positive indices from 0x40000000 specify entries in the constant pool on the CodeBlock.
static const int FirstConstantRegisterIndex = 0x40000000;
namespace JSC {
enum HasSeenShouldRepatch {
hasSeenShouldRepatch
};
class ExecState;
enum CodeType { GlobalCode, EvalCode, FunctionCode };
static ALWAYS_INLINE int missingThisObjectMarker() { return std::numeric_limits<int>::max(); }
struct HandlerInfo {
uint32_t start;
uint32_t end;
uint32_t target;
uint32_t scopeDepth;
};
struct ExpressionRangeInfo {
enum {
MaxOffset = (1 << 7) - 1,
MaxDivot = (1 << 25) - 1
};
uint32_t instructionOffset : 25;
uint32_t divotPoint : 25;
uint32_t startOffset : 7;
uint32_t endOffset : 7;
};
struct LineInfo {
uint32_t instructionOffset;
int32_t lineNumber;
};
// Both op_construct and op_instanceof require a use of op_get_by_id to get
// the prototype property from an object. The exception messages for exceptions
// thrown by these instances op_get_by_id need to reflect this.
struct GetByIdExceptionInfo {
unsigned bytecodeOffset : 31;
bool isOpConstruct : 1;
};
struct ExceptionInfo : FastAllocBase {
Vector<ExpressionRangeInfo> m_expressionInfo;
Vector<LineInfo> m_lineInfo;
Vector<GetByIdExceptionInfo> m_getByIdExceptionInfo;
};
class CodeBlock : public FastAllocBase {
protected:
CodeBlock(ScriptExecutable* ownerExecutable, CodeType, PassRefPtr<SourceProvider>, unsigned sourceOffset, SymbolTable* symbolTable);
public:
virtual ~CodeBlock();
void markAggregate(MarkStack&);
void refStructures(Instruction* vPC) const;
void derefStructures(Instruction* vPC) const;
static void dumpStatistics();
#if !defined(QT_NO_DEBUG) || ENABLE_OPCODE_SAMPLING
void dump(ExecState*) const;
void printStructures(const Instruction*) const;
void printStructure(const char* name, const Instruction*, int operand) const;
#endif
inline bool isKnownNotImmediate(int index)
{
if (index == m_thisRegister)
return true;
if (isConstantRegisterIndex(index))
return getConstant(index).isCell();
return false;
}
ALWAYS_INLINE bool isTemporaryRegisterIndex(int index)
{
return index >= m_numVars;
}
HandlerInfo* handlerForBytecodeOffset(unsigned bytecodeOffset);
int lineNumberForBytecodeOffset(CallFrame*, unsigned bytecodeOffset);
int expressionRangeForBytecodeOffset(CallFrame*, unsigned bytecodeOffset, int& divot, int& startOffset, int& endOffset);
bool getByIdExceptionInfoForBytecodeOffset(CallFrame*, unsigned bytecodeOffset, OpcodeID&);
void setIsNumericCompareFunction(bool isNumericCompareFunction) { m_isNumericCompareFunction = isNumericCompareFunction; }
bool isNumericCompareFunction() { return m_isNumericCompareFunction; }
Vector<Instruction>& instructions() { return m_instructions; }
void discardBytecode() { m_instructions.clear(); }
#ifndef QT_NO_DEBUG
unsigned instructionCount() { return m_instructionCount; }
void setInstructionCount(unsigned instructionCount) { m_instructionCount = instructionCount; }
#endif
ScriptExecutable* ownerExecutable() const { return m_ownerExecutable; }
void setGlobalData(JSGlobalData* globalData) { m_globalData = globalData; }
void setThisRegister(int thisRegister) { m_thisRegister = thisRegister; }
int thisRegister() const { return m_thisRegister; }
void setNeedsFullScopeChain(bool needsFullScopeChain) { m_needsFullScopeChain = needsFullScopeChain; }
bool needsFullScopeChain() const { return m_needsFullScopeChain; }
void setUsesEval(bool usesEval) { m_usesEval = usesEval; }
bool usesEval() const { return m_usesEval; }
void setUsesArguments(bool usesArguments) { m_usesArguments = usesArguments; }
bool usesArguments() const { return m_usesArguments; }
CodeType codeType() const { return m_codeType; }
SourceProvider* source() const { return m_source.get(); }
unsigned sourceOffset() const { return m_sourceOffset; }
size_t numberOfJumpTargets() const { return m_jumpTargets.size(); }
void addJumpTarget(unsigned jumpTarget) { m_jumpTargets.append(jumpTarget); }
unsigned jumpTarget(int index) const { return m_jumpTargets[index]; }
unsigned lastJumpTarget() const { return m_jumpTargets.last(); }
void addPropertyAccessInstruction(unsigned propertyAccessInstruction) { m_propertyAccessInstructions.append(propertyAccessInstruction); }
void addGlobalResolveInstruction(unsigned globalResolveInstruction) { m_globalResolveInstructions.append(globalResolveInstruction); }
bool hasGlobalResolveInstructionAtBytecodeOffset(unsigned bytecodeOffset);
// Exception handling support
size_t numberOfExceptionHandlers() const { return m_rareData ? m_rareData->m_exceptionHandlers.size() : 0; }
void addExceptionHandler(const HandlerInfo& hanler) { createRareDataIfNecessary(); return m_rareData->m_exceptionHandlers.append(hanler); }
HandlerInfo& exceptionHandler(int index) { Q_ASSERT(m_rareData); return m_rareData->m_exceptionHandlers[index]; }
bool hasExceptionInfo() const { return m_exceptionInfo; }
void clearExceptionInfo() { m_exceptionInfo.clear(); }
ExceptionInfo* extractExceptionInfo() { Q_ASSERT(m_exceptionInfo); return m_exceptionInfo.release(); }
void addExpressionInfo(const ExpressionRangeInfo& expressionInfo) { Q_ASSERT(m_exceptionInfo); m_exceptionInfo->m_expressionInfo.append(expressionInfo); }
void addGetByIdExceptionInfo(const GetByIdExceptionInfo& info) { Q_ASSERT(m_exceptionInfo); m_exceptionInfo->m_getByIdExceptionInfo.append(info); }
size_t numberOfLineInfos() const { Q_ASSERT(m_exceptionInfo); return m_exceptionInfo->m_lineInfo.size(); }
void addLineInfo(const LineInfo& lineInfo) { Q_ASSERT(m_exceptionInfo); m_exceptionInfo->m_lineInfo.append(lineInfo); }
LineInfo& lastLineInfo() { Q_ASSERT(m_exceptionInfo); return m_exceptionInfo->m_lineInfo.last(); }
// Constant Pool
size_t numberOfIdentifiers() const { return m_identifiers.size(); }
void addIdentifier(const Identifier& i) { return m_identifiers.append(i); }
Identifier& identifier(int index) { return m_identifiers[index]; }
size_t numberOfConstantRegisters() const { return m_constantRegisters.size(); }
void addConstantRegister(const Register& r) { return m_constantRegisters.append(r); }
Register& constantRegister(int index) { return m_constantRegisters[index - FirstConstantRegisterIndex]; }
ALWAYS_INLINE bool isConstantRegisterIndex(int index) const { return index >= FirstConstantRegisterIndex; }
ALWAYS_INLINE JSValue getConstant(int index) const { return m_constantRegisters[index - FirstConstantRegisterIndex].jsValue(); }
unsigned addFunctionDecl(NonNullPassRefPtr<FunctionExecutable> n) { unsigned size = m_functionDecls.size(); m_functionDecls.append(n); return size; }
FunctionExecutable* functionDecl(int index) { return m_functionDecls[index].get(); }
int numberOfFunctionDecls() { return m_functionDecls.size(); }
unsigned addFunctionExpr(NonNullPassRefPtr<FunctionExecutable> n) { unsigned size = m_functionExprs.size(); m_functionExprs.append(n); return size; }
FunctionExecutable* functionExpr(int index) { return m_functionExprs[index].get(); }
unsigned addRegExp(RegExp* r) { createRareDataIfNecessary(); unsigned size = m_rareData->m_regexps.size(); m_rareData->m_regexps.append(r); return size; }
RegExp* regexp(int index) const { Q_ASSERT(m_rareData); return m_rareData->m_regexps[index].get(); }
// Jump Tables
size_t numberOfImmediateSwitchJumpTables() const { return m_rareData ? m_rareData->m_immediateSwitchJumpTables.size() : 0; }
SimpleJumpTable& addImmediateSwitchJumpTable() { createRareDataIfNecessary(); m_rareData->m_immediateSwitchJumpTables.append(SimpleJumpTable()); return m_rareData->m_immediateSwitchJumpTables.last(); }
SimpleJumpTable& immediateSwitchJumpTable(int tableIndex) { Q_ASSERT(m_rareData); return m_rareData->m_immediateSwitchJumpTables[tableIndex]; }
size_t numberOfCharacterSwitchJumpTables() const { return m_rareData ? m_rareData->m_characterSwitchJumpTables.size() : 0; }
SimpleJumpTable& addCharacterSwitchJumpTable() { createRareDataIfNecessary(); m_rareData->m_characterSwitchJumpTables.append(SimpleJumpTable()); return m_rareData->m_characterSwitchJumpTables.last(); }
SimpleJumpTable& characterSwitchJumpTable(int tableIndex) { Q_ASSERT(m_rareData); return m_rareData->m_characterSwitchJumpTables[tableIndex]; }
size_t numberOfStringSwitchJumpTables() const { return m_rareData ? m_rareData->m_stringSwitchJumpTables.size() : 0; }
StringJumpTable& addStringSwitchJumpTable() { createRareDataIfNecessary(); m_rareData->m_stringSwitchJumpTables.append(StringJumpTable()); return m_rareData->m_stringSwitchJumpTables.last(); }
StringJumpTable& stringSwitchJumpTable(int tableIndex) { Q_ASSERT(m_rareData); return m_rareData->m_stringSwitchJumpTables[tableIndex]; }
SymbolTable* symbolTable() { return m_symbolTable; }
SharedSymbolTable* sharedSymbolTable() { Q_ASSERT(m_codeType == FunctionCode); return static_cast<SharedSymbolTable*>(m_symbolTable); }
EvalCodeCache& evalCodeCache() { createRareDataIfNecessary(); return m_rareData->m_evalCodeCache; }
void shrinkToFit();
// FIXME: Make these remaining members private.
int m_numCalleeRegisters;
int m_numVars;
int m_numParameters;
private:
#if !defined(QT_NO_DEBUG) || ENABLE(OPCODE_SAMPLING)
void dump(ExecState*, const Vector<Instruction>::const_iterator& begin, Vector<Instruction>::const_iterator&) const;
const char* registerName(ExecState*, int r) const;
void printUnaryOp(ExecState*, int location, Vector<Instruction>::const_iterator&, const char* op) const;
void printBinaryOp(ExecState*, int location, Vector<Instruction>::const_iterator&, const char* op) const;
void printConditionalJump(ExecState*, const Vector<Instruction>::const_iterator&, Vector<Instruction>::const_iterator&, int location, const char* op) const;
void printGetByIdOp(ExecState*, int location, Vector<Instruction>::const_iterator&, const char* op) const;
void printPutByIdOp(ExecState*, int location, Vector<Instruction>::const_iterator&, const char* op) const;
#endif
void reparseForExceptionInfoIfNecessary(CallFrame*);
void createRareDataIfNecessary()
{
if (!m_rareData)
m_rareData.set(new RareData);
}
ScriptExecutable* m_ownerExecutable;
JSGlobalData* m_globalData;
Vector<Instruction> m_instructions;
#ifndef QT_NO_DEBUG
unsigned m_instructionCount;
#endif
int m_thisRegister;
bool m_needsFullScopeChain;
bool m_usesEval;
bool m_usesArguments;
bool m_isNumericCompareFunction;
CodeType m_codeType;
RefPtr<SourceProvider> m_source;
unsigned m_sourceOffset;
Vector<unsigned> m_propertyAccessInstructions;
Vector<unsigned> m_globalResolveInstructions;
Vector<unsigned> m_jumpTargets;
// Constant Pool
Vector<Identifier> m_identifiers;
Vector<Register> m_constantRegisters;
Vector<RefPtr<FunctionExecutable> > m_functionDecls;
Vector<RefPtr<FunctionExecutable> > m_functionExprs;
SymbolTable* m_symbolTable;
OwnPtr<ExceptionInfo> m_exceptionInfo;
struct RareData : FastAllocBase {
Vector<HandlerInfo> m_exceptionHandlers;
// Rare Constants
Vector<RefPtr<RegExp> > m_regexps;
// Jump Tables
Vector<SimpleJumpTable> m_immediateSwitchJumpTables;
Vector<SimpleJumpTable> m_characterSwitchJumpTables;
Vector<StringJumpTable> m_stringSwitchJumpTables;
EvalCodeCache m_evalCodeCache;
};
OwnPtr<RareData> m_rareData;
};
// Program code is not marked by any function, so we make the global object
// responsible for marking it.
class GlobalCodeBlock : public CodeBlock {
public:
GlobalCodeBlock(ScriptExecutable* ownerExecutable, CodeType codeType, PassRefPtr<SourceProvider> sourceProvider, unsigned sourceOffset, JSGlobalObject* globalObject)
: CodeBlock(ownerExecutable, codeType, sourceProvider, sourceOffset, &m_unsharedSymbolTable)
, m_globalObject(globalObject)
{
m_globalObject->codeBlocks().add(this);
}
~GlobalCodeBlock()
{
if (m_globalObject)
m_globalObject->codeBlocks().remove(this);
}
void clearGlobalObject() { m_globalObject = 0; }
private:
JSGlobalObject* m_globalObject; // For program and eval nodes, the global object that marks the constant pool.
SymbolTable m_unsharedSymbolTable;
};
class ProgramCodeBlock : public GlobalCodeBlock {
public:
ProgramCodeBlock(ProgramExecutable* ownerExecutable, CodeType codeType, JSGlobalObject* globalObject, PassRefPtr<SourceProvider> sourceProvider)
: GlobalCodeBlock(ownerExecutable, codeType, sourceProvider, 0, globalObject)
{
}
};
class EvalCodeBlock : public GlobalCodeBlock {
public:
EvalCodeBlock(EvalExecutable* ownerExecutable, JSGlobalObject* globalObject, PassRefPtr<SourceProvider> sourceProvider, int baseScopeDepth)
: GlobalCodeBlock(ownerExecutable, EvalCode, sourceProvider, 0, globalObject)
, m_baseScopeDepth(baseScopeDepth)
{
}
int baseScopeDepth() const { return m_baseScopeDepth; }
const Identifier& variable(unsigned index) { return m_variables[index]; }
unsigned numVariables() { return m_variables.size(); }
void adoptVariables(Vector<Identifier>& variables)
{
Q_ASSERT(m_variables.isEmpty());
m_variables.swap(variables);
}
private:
int m_baseScopeDepth;
Vector<Identifier> m_variables;
};
class FunctionCodeBlock : public CodeBlock {
public:
// Rather than using the usual RefCounted::create idiom for SharedSymbolTable we just use new
// as we need to initialise the CodeBlock before we could initialise any RefPtr to hold the shared
// symbol table, so we just pass as a raw pointer with a ref count of 1. We then manually deref
// in the destructor.
FunctionCodeBlock(FunctionExecutable* ownerExecutable, CodeType codeType, PassRefPtr<SourceProvider> sourceProvider, unsigned sourceOffset)
: CodeBlock(ownerExecutable, codeType, sourceProvider, sourceOffset, new SharedSymbolTable)
{
}
~FunctionCodeBlock()
{
sharedSymbolTable()->deref();
}
};
inline Register& ExecState::r(int index)
{
CodeBlock* codeBlock = this->codeBlock();
if (codeBlock->isConstantRegisterIndex(index))
return codeBlock->constantRegister(index);
return this[index];
}
} // namespace JSC
#endif // CodeBlock_h

View file

@ -1,77 +0,0 @@
/*
* Copyright (C) 2008, 2009 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef EvalCodeCache_h
#define EvalCodeCache_h
#include "Executable.h"
#include "JSGlobalObject.h"
#include "Nodes.h"
#include "Parser.h"
#include "SourceCode.h"
#include "UString.h"
#include <wtf/HashMap.h>
#include <wtf/RefPtr.h>
namespace JSC {
class EvalCodeCache {
public:
PassRefPtr<EvalExecutable> get(ExecState* exec, const UString& evalSource, ScopeChainNode* scopeChain, JSValue& exceptionValue)
{
RefPtr<EvalExecutable> evalExecutable;
if (evalSource.size() < maxCacheableSourceLength && (*scopeChain->begin())->isVariableObject())
evalExecutable = m_cacheMap.get(evalSource.rep());
if (!evalExecutable) {
evalExecutable = EvalExecutable::create(exec, makeSource(evalSource));
exceptionValue = evalExecutable->compile(exec, scopeChain);
if (exceptionValue)
return 0;
if (evalSource.size() < maxCacheableSourceLength && (*scopeChain->begin())->isVariableObject() && m_cacheMap.size() < maxCacheEntries)
m_cacheMap.set(evalSource.rep(), evalExecutable);
}
return evalExecutable.release();
}
bool isEmpty() const { return m_cacheMap.isEmpty(); }
private:
static const int maxCacheableSourceLength = 256;
static const int maxCacheEntries = 64;
typedef HashMap<RefPtr<UString::Rep>, RefPtr<EvalExecutable> > EvalCacheMap;
EvalCacheMap m_cacheMap;
};
} // namespace JSC
#endif // EvalCodeCache_h

View file

@ -1,83 +0,0 @@
/*
* Copyright (C) 2008 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef Instruction_h
#define Instruction_h
#include "Opcode.h"
#include "Structure.h"
#include "StructureChain.h"
#include <wtf/VectorTraits.h>
#define POLYMORPHIC_LIST_CACHE_SIZE 8
namespace JSC {
class JSCell;
class Structure;
class StructureChain;
struct Instruction {
Instruction(OpcodeID opcode)
{
// We have to initialize one of the pointer members to ensure that
// the entire struct is initialized, when opcode is not a pointer.
u.jsCell = 0;
u.opcode = opcode;
}
Instruction(int operand)
{
// We have to initialize one of the pointer members to ensure that
// the entire struct is initialized in 64-bit.
u.jsCell = 0;
u.operand = operand;
}
Instruction(Structure* structure) { u.structure = structure; }
Instruction(StructureChain* structureChain) { u.structureChain = structureChain; }
Instruction(JSCell* jsCell) { u.jsCell = jsCell; }
union {
OpcodeID opcode;
int operand;
Structure* structure;
StructureChain* structureChain;
JSCell* jsCell;
} u;
};
} // namespace JSC
namespace WTF {
template<> struct VectorTraits<JSC::Instruction> : VectorTraitsBase<true, JSC::Instruction> { };
} // namespace WTF
#endif // Instruction_h

View file

@ -1,45 +0,0 @@
/*
* Copyright (C) 2008 Apple Inc. All rights reserved.
* Copyright (C) 2008 Cameron Zwarich <cwzwarich@uwaterloo.ca>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "Platform.h"
#include "JumpTable.h"
namespace JSC {
int32_t SimpleJumpTable::offsetForValue(int32_t value, int32_t defaultOffset)
{
if (value >= min && static_cast<uint32_t>(value - min) < branchOffsets.size()) {
int32_t offset = branchOffsets[value - min];
if (offset)
return offset;
}
return defaultOffset;
}
} // namespace JSC

View file

@ -1,70 +0,0 @@
/*
* Copyright (C) 2008 Apple Inc. All rights reserved.
* Copyright (C) 2008 Cameron Zwarich <cwzwarich@uwaterloo.ca>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef JumpTable_h
#define JumpTable_h
#include "UString.h"
#include <wtf/HashMap.h>
#include <wtf/Vector.h>
namespace JSC {
typedef int32_t OffsetLocation;
struct StringJumpTable {
typedef HashMap<RefPtr<UString::Rep>, OffsetLocation> StringOffsetTable;
StringOffsetTable offsetTable;
inline int32_t offsetForValue(UString::Rep* value, int32_t defaultOffset)
{
StringOffsetTable::const_iterator end = offsetTable.end();
StringOffsetTable::const_iterator loc = offsetTable.find(value);
if (loc == end)
return defaultOffset;
return loc->second;
}
};
struct SimpleJumpTable {
// FIXME: The two Vectors can be combind into one Vector<OffsetLocation>
Vector<int32_t> branchOffsets;
int32_t min;
int32_t offsetForValue(int32_t value, int32_t defaultOffset);
void add(int32_t key, int32_t offset)
{
if (!branchOffsets[key])
branchOffsets[key] = offset;
}
};
} // namespace JSC
#endif // JumpTable_h

View file

@ -1,186 +0,0 @@
/*
* Copyright (C) 2008 Apple Inc. All rights reserved.
* Copyright (C) 2008 Cameron Zwarich <cwzwarich@uwaterloo.ca>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "Platform.h"
#include "Opcode.h"
using namespace std;
namespace JSC {
#if ENABLE(OPCODE_SAMPLING) || ENABLE(CODEBLOCK_SAMPLING) || ENABLE(OPCODE_STATS)
const char* const opcodeNames[] = {
#define OPCODE_NAME_ENTRY(opcode, size) #opcode,
FOR_EACH_OPCODE_ID(OPCODE_NAME_ENTRY)
#undef OPCODE_NAME_ENTRY
};
#endif
#if ENABLE(OPCODE_STATS)
long long OpcodeStats::opcodeCounts[numOpcodeIDs];
long long OpcodeStats::opcodePairCounts[numOpcodeIDs][numOpcodeIDs];
int OpcodeStats::lastOpcode = -1;
static OpcodeStats logger;
OpcodeStats::OpcodeStats()
{
for (int i = 0; i < numOpcodeIDs; ++i)
opcodeCounts[i] = 0;
for (int i = 0; i < numOpcodeIDs; ++i)
for (int j = 0; j < numOpcodeIDs; ++j)
opcodePairCounts[i][j] = 0;
}
static int compareOpcodeIndices(const void* left, const void* right)
{
long long leftValue = OpcodeStats::opcodeCounts[*(int*) left];
long long rightValue = OpcodeStats::opcodeCounts[*(int*) right];
if (leftValue < rightValue)
return 1;
else if (leftValue > rightValue)
return -1;
else
return 0;
}
static int compareOpcodePairIndices(const void* left, const void* right)
{
std::pair<int, int> leftPair = *(std::pair<int, int>*) left;
long long leftValue = OpcodeStats::opcodePairCounts[leftPair.first][leftPair.second];
std::pair<int, int> rightPair = *(std::pair<int, int>*) right;
long long rightValue = OpcodeStats::opcodePairCounts[rightPair.first][rightPair.second];
if (leftValue < rightValue)
return 1;
else if (leftValue > rightValue)
return -1;
else
return 0;
}
OpcodeStats::~OpcodeStats()
{
long long totalInstructions = 0;
for (int i = 0; i < numOpcodeIDs; ++i)
totalInstructions += opcodeCounts[i];
long long totalInstructionPairs = 0;
for (int i = 0; i < numOpcodeIDs; ++i)
for (int j = 0; j < numOpcodeIDs; ++j)
totalInstructionPairs += opcodePairCounts[i][j];
int sortedIndices[numOpcodeIDs];
for (int i = 0; i < numOpcodeIDs; ++i)
sortedIndices[i] = i;
qsort(sortedIndices, numOpcodeIDs, sizeof(int), compareOpcodeIndices);
std::pair<int, int> sortedPairIndices[numOpcodeIDs * numOpcodeIDs];
std::pair<int, int>* currentPairIndex = sortedPairIndices;
for (int i = 0; i < numOpcodeIDs; ++i)
for (int j = 0; j < numOpcodeIDs; ++j)
*(currentPairIndex++) = std::make_pair(i, j);
qsort(sortedPairIndices, numOpcodeIDs * numOpcodeIDs, sizeof(std::pair<int, int>), compareOpcodePairIndices);
printf("\nExecuted opcode statistics\n");
printf("Total instructions executed: %lld\n\n", totalInstructions);
printf("All opcodes by frequency:\n\n");
for (int i = 0; i < numOpcodeIDs; ++i) {
int index = sortedIndices[i];
printf("%s:%s %lld - %.2f%%\n", opcodeNames[index], padOpcodeName((OpcodeID)index, 28), opcodeCounts[index], ((double) opcodeCounts[index]) / ((double) totalInstructions) * 100.0);
}
printf("\n");
printf("2-opcode sequences by frequency: %lld\n\n", totalInstructions);
for (int i = 0; i < numOpcodeIDs * numOpcodeIDs; ++i) {
std::pair<int, int> indexPair = sortedPairIndices[i];
long long count = opcodePairCounts[indexPair.first][indexPair.second];
if (!count)
break;
printf("%s%s %s:%s %lld %.2f%%\n", opcodeNames[indexPair.first], padOpcodeName((OpcodeID)indexPair.first, 28), opcodeNames[indexPair.second], padOpcodeName((OpcodeID)indexPair.second, 28), count, ((double) count) / ((double) totalInstructionPairs) * 100.0);
}
printf("\n");
printf("Most common opcodes and sequences:\n");
for (int i = 0; i < numOpcodeIDs; ++i) {
int index = sortedIndices[i];
long long opcodeCount = opcodeCounts[index];
double opcodeProportion = ((double) opcodeCount) / ((double) totalInstructions);
if (opcodeProportion < 0.0001)
break;
printf("\n%s:%s %lld - %.2f%%\n", opcodeNames[index], padOpcodeName((OpcodeID)index, 28), opcodeCount, opcodeProportion * 100.0);
for (int j = 0; j < numOpcodeIDs * numOpcodeIDs; ++j) {
std::pair<int, int> indexPair = sortedPairIndices[j];
long long pairCount = opcodePairCounts[indexPair.first][indexPair.second];
double pairProportion = ((double) pairCount) / ((double) totalInstructionPairs);
if (!pairCount || pairProportion < 0.0001 || pairProportion < opcodeProportion / 100)
break;
if (indexPair.first != index && indexPair.second != index)
continue;
printf(" %s%s %s:%s %lld - %.2f%%\n", opcodeNames[indexPair.first], padOpcodeName((OpcodeID)indexPair.first, 28), opcodeNames[indexPair.second], padOpcodeName((OpcodeID)indexPair.second, 28), pairCount, pairProportion * 100.0);
}
}
printf("\n");
}
void OpcodeStats::recordInstruction(int opcode)
{
opcodeCounts[opcode]++;
if (lastOpcode != -1)
opcodePairCounts[lastOpcode][opcode]++;
lastOpcode = opcode;
}
void OpcodeStats::resetLastInstruction()
{
lastOpcode = -1;
}
#endif
} // namespace JSC

View file

@ -1,230 +0,0 @@
/*
* Copyright (C) 2008, 2009 Apple Inc. All rights reserved.
* Copyright (C) 2008 Cameron Zwarich <cwzwarich@uwaterloo.ca>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef Opcode_h
#define Opcode_h
#include <algorithm>
#include <string.h>
#include <wtf/Assertions.h>
namespace JSC {
#define FOR_EACH_OPCODE_ID(macro) \
macro(op_enter, 1) \
macro(op_enter_with_activation, 2) \
macro(op_init_arguments, 1) \
macro(op_create_arguments, 1) \
macro(op_convert_this, 2) \
\
macro(op_new_object, 2) \
macro(op_new_array, 4) \
macro(op_new_regexp, 3) \
macro(op_mov, 3) \
\
macro(op_not, 3) \
macro(op_eq, 4) \
macro(op_eq_null, 3) \
macro(op_neq, 4) \
macro(op_neq_null, 3) \
macro(op_stricteq, 4) \
macro(op_nstricteq, 4) \
macro(op_less, 4) \
macro(op_lesseq, 4) \
\
macro(op_pre_inc, 2) \
macro(op_pre_dec, 2) \
macro(op_post_inc, 3) \
macro(op_post_dec, 3) \
macro(op_to_jsnumber, 3) \
macro(op_negate, 3) \
macro(op_add, 5) \
macro(op_mul, 5) \
macro(op_div, 5) \
macro(op_mod, 4) \
macro(op_sub, 5) \
\
macro(op_lshift, 4) \
macro(op_rshift, 4) \
macro(op_urshift, 4) \
macro(op_bitand, 5) \
macro(op_bitxor, 5) \
macro(op_bitor, 5) \
macro(op_bitnot, 3) \
\
macro(op_instanceof, 5) \
macro(op_typeof, 3) \
macro(op_is_undefined, 3) \
macro(op_is_boolean, 3) \
macro(op_is_number, 3) \
macro(op_is_string, 3) \
macro(op_is_object, 3) \
macro(op_is_function, 3) \
macro(op_in, 4) \
\
macro(op_resolve, 3) \
macro(op_resolve_skip, 4) \
macro(op_resolve_global, 6) \
macro(op_get_scoped_var, 4) \
macro(op_put_scoped_var, 4) \
macro(op_get_global_var, 4) \
macro(op_put_global_var, 4) \
macro(op_resolve_base, 3) \
macro(op_resolve_with_base, 4) \
macro(op_get_by_id, 8) \
macro(op_get_by_id_self, 8) \
macro(op_get_by_id_proto, 8) \
macro(op_get_by_id_chain, 8) \
macro(op_get_by_id_generic, 8) \
macro(op_get_array_length, 8) \
macro(op_get_string_length, 8) \
macro(op_put_by_id, 8) \
macro(op_put_by_id_transition, 8) \
macro(op_put_by_id_replace, 8) \
macro(op_put_by_id_generic, 8) \
macro(op_del_by_id, 4) \
macro(op_get_by_val, 4) \
macro(op_get_by_pname, 7) \
macro(op_put_by_val, 4) \
macro(op_del_by_val, 4) \
macro(op_put_by_index, 4) \
macro(op_put_getter, 4) \
macro(op_put_setter, 4) \
\
macro(op_jmp, 2) \
macro(op_jtrue, 3) \
macro(op_jfalse, 3) \
macro(op_jeq_null, 3) \
macro(op_jneq_null, 3) \
macro(op_jneq_ptr, 4) \
macro(op_jnless, 4) \
macro(op_jnlesseq, 4) \
macro(op_jless, 4) \
macro(op_jmp_scopes, 3) \
macro(op_loop, 2) \
macro(op_loop_if_true, 3) \
macro(op_loop_if_false, 3) \
macro(op_loop_if_less, 4) \
macro(op_loop_if_lesseq, 4) \
macro(op_switch_imm, 4) \
macro(op_switch_char, 4) \
macro(op_switch_string, 4) \
\
macro(op_new_func, 3) \
macro(op_new_func_exp, 3) \
macro(op_call, 5) \
macro(op_call_eval, 5) \
macro(op_call_varargs, 5) \
macro(op_load_varargs, 3) \
macro(op_tear_off_activation, 2) \
macro(op_tear_off_arguments, 1) \
macro(op_ret, 2) \
macro(op_method_check, 1) \
\
macro(op_construct, 7) \
macro(op_construct_verify, 3) \
macro(op_strcat, 4) \
macro(op_to_primitive, 3) \
\
macro(op_get_pnames, 6) \
macro(op_next_pname, 7) \
\
macro(op_push_scope, 2) \
macro(op_pop_scope, 1) \
macro(op_push_new_scope, 4) \
\
macro(op_catch, 2) \
macro(op_throw, 2) \
macro(op_new_error, 4) \
\
macro(op_jsr, 3) \
macro(op_sret, 2) \
\
macro(op_debug, 4) \
\
macro(op_end, 2) // end must be the last opcode in the list
#define OPCODE_ID_ENUM(opcode, length) opcode,
typedef enum { FOR_EACH_OPCODE_ID(OPCODE_ID_ENUM) } OpcodeID;
#undef OPCODE_ID_ENUM
const int numOpcodeIDs = op_end + 1;
#define OPCODE_ID_LENGTHS(id, length) const int id##_length = length;
FOR_EACH_OPCODE_ID(OPCODE_ID_LENGTHS)
#undef OPCODE_ID_LENGTHS
#define OPCODE_LENGTH(opcode) opcode##_length
#define OPCODE_ID_LENGTH_MAP(opcode, length) length,
const int opcodeLengths[numOpcodeIDs] = { FOR_EACH_OPCODE_ID(OPCODE_ID_LENGTH_MAP) };
#undef OPCODE_ID_LENGTH_MAP
#define VERIFY_OPCODE_ID(id, size) COMPILE_ASSERT(id <= op_end, ASSERT_THAT_JS_OPCODE_IDS_ARE_VALID);
FOR_EACH_OPCODE_ID(VERIFY_OPCODE_ID)
#undef VERIFY_OPCODE_ID
#if ENABLE(OPCODE_SAMPLING) || ENABLE(CODEBLOCK_SAMPLING) || ENABLE(OPCODE_STATS)
#define PADDING_STRING " "
#define PADDING_STRING_LENGTH static_cast<unsigned>(strlen(PADDING_STRING))
extern const char* const opcodeNames[];
inline const char* padOpcodeName(OpcodeID op, unsigned width)
{
unsigned pad = width - strlen(opcodeNames[op]);
pad = std::min(pad, PADDING_STRING_LENGTH);
return PADDING_STRING + PADDING_STRING_LENGTH - pad;
}
#undef PADDING_STRING_LENGTH
#undef PADDING_STRING
#endif
#if ENABLE(OPCODE_STATS)
struct OpcodeStats {
OpcodeStats();
~OpcodeStats();
static long long opcodeCounts[numOpcodeIDs];
static long long opcodePairCounts[numOpcodeIDs][numOpcodeIDs];
static int lastOpcode;
static void recordInstruction(int opcode);
static void resetLastInstruction();
};
#endif
} // namespace JSC
#endif // Opcode_h

View file

@ -1,371 +0,0 @@
/*
* Copyright (C) 2008, 2009 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "Platform.h"
#include "SamplingTool.h"
#include "CodeBlock.h"
#include "Interpreter.h"
#include "Opcode.h"
#include <unistd.h>
namespace JSC {
#if ENABLE(SAMPLING_FLAGS)
void SamplingFlags::sample()
{
uint32_t mask = 1 << 31;
unsigned index;
for (index = 0; index < 32; ++index) {
if (mask & s_flags)
break;
mask >>= 1;
}
s_flagCounts[32 - index]++;
}
void SamplingFlags::start()
{
for (unsigned i = 0; i <= 32; ++i)
s_flagCounts[i] = 0;
}
void SamplingFlags::stop()
{
uint64_t total = 0;
for (unsigned i = 0; i <= 32; ++i)
total += s_flagCounts[i];
if (total) {
printf("\nSamplingFlags: sample counts with flags set: (%lld total)\n", total);
for (unsigned i = 0; i <= 32; ++i) {
if (s_flagCounts[i])
printf(" [ %02d ] : %lld\t\t(%03.2f%%)\n", i, s_flagCounts[i], (100.0 * s_flagCounts[i]) / total);
}
printf("\n");
} else
printf("\nSamplingFlags: no samples.\n\n");
}
uint64_t SamplingFlags::s_flagCounts[33];
#else
void SamplingFlags::start() {}
void SamplingFlags::stop() {}
#endif
/*
Start with flag 16 set.
By doing this the monitoring of lower valued flags will be masked out
until flag 16 is explictly cleared.
*/
uint32_t SamplingFlags::s_flags = 1 << 15;
SamplingTool* SamplingTool::s_samplingTool = 0;
bool SamplingThread::s_running = false;
unsigned SamplingThread::s_hertz = 10000;
ThreadIdentifier SamplingThread::s_samplingThread;
void* SamplingThread::threadStartFunc(void*)
{
while (s_running) {
QThread::usleep(1000000 / s_hertz);
#if ENABLE(SAMPLING_FLAGS)
SamplingFlags::sample();
#endif
#if ENABLE(OPCODE_SAMPLING)
SamplingTool::sample();
#endif
}
return 0;
}
void SamplingThread::start(unsigned hertz)
{
Q_ASSERT(!s_running);
s_running = true;
s_hertz = hertz;
s_samplingThread = createThread(threadStartFunc, 0, "JavaScriptCore::Sampler");
}
void SamplingThread::stop()
{
Q_ASSERT(s_running);
s_running = false;
waitForThreadCompletion(s_samplingThread);
}
void ScriptSampleRecord::sample(CodeBlock* codeBlock, Instruction* vPC)
{
if (!m_samples) {
m_size = codeBlock->instructions().size();
m_samples = static_cast<int*>(calloc(m_size, sizeof(int)));
m_codeBlock = codeBlock;
}
++m_sampleCount;
unsigned offest = vPC - codeBlock->instructions().begin();
// Since we don't read and write codeBlock and vPC atomically, this check
// can fail if we sample mid op_call / op_ret.
if (offest < m_size) {
m_samples[offest]++;
m_opcodeSampleCount++;
}
}
void SamplingTool::doRun()
{
Sample sample(m_sample, m_codeBlock);
++m_sampleCount;
if (sample.isNull())
return;
if (!sample.inHostFunction()) {
unsigned opcodeID = sample.vPC()[0].u.opcode;
++m_opcodeSampleCount;
++m_opcodeSamples[opcodeID];
if (sample.inCTIFunction())
m_opcodeSamplesInCTIFunctions[opcodeID]++;
}
#if ENABLE(CODEBLOCK_SAMPLING)
if (CodeBlock* codeBlock = sample.codeBlock()) {
QMutexLocker locker(m_scriptSampleMapMutex);
ScriptSampleRecord* record = m_scopeSampleMap->get(codeBlock->ownerExecutable());
Q_ASSERT(record);
record->sample(codeBlock, sample.vPC());
}
#endif
}
void SamplingTool::sample()
{
s_samplingTool->doRun();
}
void SamplingTool::notifyOfScope(ScriptExecutable* script)
{
#if ENABLE(CODEBLOCK_SAMPLING)
QMutexLocker locker(m_scriptSampleMapMutex);
m_scopeSampleMap->set(script, new ScriptSampleRecord(script));
#else
Q_UNUSED(script);
#endif
}
void SamplingTool::setup()
{
s_samplingTool = this;
}
#if ENABLE(OPCODE_SAMPLING)
struct OpcodeSampleInfo {
OpcodeID opcode;
long long count;
long long countInCTIFunctions;
};
struct LineCountInfo {
unsigned line;
unsigned count;
};
static int compareOpcodeIndicesSampling(const void* left, const void* right)
{
const OpcodeSampleInfo* leftSampleInfo = reinterpret_cast<const OpcodeSampleInfo*>(left);
const OpcodeSampleInfo* rightSampleInfo = reinterpret_cast<const OpcodeSampleInfo*>(right);
return (leftSampleInfo->count < rightSampleInfo->count) ? 1 : (leftSampleInfo->count > rightSampleInfo->count) ? -1 : 0;
}
#if ENABLE(CODEBLOCK_SAMPLING)
static int compareLineCountInfoSampling(const void* left, const void* right)
{
const LineCountInfo* leftLineCount = reinterpret_cast<const LineCountInfo*>(left);
const LineCountInfo* rightLineCount = reinterpret_cast<const LineCountInfo*>(right);
return (leftLineCount->line > rightLineCount->line) ? 1 : (leftLineCount->line < rightLineCount->line) ? -1 : 0;
}
static int compareScriptSampleRecords(const void* left, const void* right)
{
const ScriptSampleRecord* const leftValue = *static_cast<const ScriptSampleRecord* const *>(left);
const ScriptSampleRecord* const rightValue = *static_cast<const ScriptSampleRecord* const *>(right);
return (leftValue->m_sampleCount < rightValue->m_sampleCount) ? 1 : (leftValue->m_sampleCount > rightValue->m_sampleCount) ? -1 : 0;
}
#endif
void SamplingTool::dump(ExecState* exec)
{
// Tidies up SunSpider output by removing short scripts - such a small number of samples would likely not be useful anyhow.
if (m_sampleCount < 10)
return;
// (1) Build and sort 'opcodeSampleInfo' array.
OpcodeSampleInfo opcodeSampleInfo[numOpcodeIDs];
for (int i = 0; i < numOpcodeIDs; ++i) {
opcodeSampleInfo[i].opcode = static_cast<OpcodeID>(i);
opcodeSampleInfo[i].count = m_opcodeSamples[i];
opcodeSampleInfo[i].countInCTIFunctions = m_opcodeSamplesInCTIFunctions[i];
}
qsort(opcodeSampleInfo, numOpcodeIDs, sizeof(OpcodeSampleInfo), compareOpcodeIndicesSampling);
// (2) Print Opcode sampling results.
printf("\nBytecode samples [*]\n");
printf(" sample %% of %% of | cti cti %%\n");
printf("opcode count VM total | count of self\n");
printf("------------------------------------------------------- | ----------------\n");
for (int i = 0; i < numOpcodeIDs; ++i) {
long long count = opcodeSampleInfo[i].count;
if (!count)
continue;
OpcodeID opcodeID = opcodeSampleInfo[i].opcode;
const char* opcodeName = opcodeNames[opcodeID];
const char* opcodePadding = padOpcodeName(opcodeID, 28);
double percentOfVM = (static_cast<double>(count) * 100) / m_opcodeSampleCount;
double percentOfTotal = (static_cast<double>(count) * 100) / m_sampleCount;
long long countInCTIFunctions = opcodeSampleInfo[i].countInCTIFunctions;
double percentInCTIFunctions = (static_cast<double>(countInCTIFunctions) * 100) / count;
fprintf(stdout, "%s:%s%-6lld %.3f%%\t%.3f%%\t | %-6lld %.3f%%\n", opcodeName, opcodePadding, count, percentOfVM, percentOfTotal, countInCTIFunctions, percentInCTIFunctions);
}
printf("\n[*] Samples inside host code are not charged to any Bytecode.\n\n");
printf("\tSamples inside VM:\t\t%lld / %lld (%.3f%%)\n", m_opcodeSampleCount, m_sampleCount, (static_cast<double>(m_opcodeSampleCount) * 100) / m_sampleCount);
printf("\tSamples inside host code:\t%lld / %lld (%.3f%%)\n\n", m_sampleCount - m_opcodeSampleCount, m_sampleCount, (static_cast<double>(m_sampleCount - m_opcodeSampleCount) * 100) / m_sampleCount);
printf("\tsample count:\tsamples inside this opcode\n");
printf("\t%% of VM:\tsample count / all opcode samples\n");
printf("\t%% of total:\tsample count / all samples\n");
printf("\t--------------\n");
printf("\tcti count:\tsamples inside a CTI function called by this opcode\n");
printf("\tcti %% of self:\tcti count / sample count\n");
#if ENABLE(CODEBLOCK_SAMPLING)
// (3) Build and sort 'codeBlockSamples' array.
int scopeCount = m_scopeSampleMap->size();
Vector<ScriptSampleRecord*> codeBlockSamples(scopeCount);
ScriptSampleRecordMap::iterator iter = m_scopeSampleMap->begin();
for (int i = 0; i < scopeCount; ++i, ++iter)
codeBlockSamples[i] = iter->second;
qsort(codeBlockSamples.begin(), scopeCount, sizeof(ScriptSampleRecord*), compareScriptSampleRecords);
// (4) Print data from 'codeBlockSamples' array.
printf("\nCodeBlock samples\n\n");
for (int i = 0; i < scopeCount; ++i) {
ScriptSampleRecord* record = codeBlockSamples[i];
CodeBlock* codeBlock = record->m_codeBlock;
double blockPercent = (record->m_sampleCount * 100.0) / m_sampleCount;
if (blockPercent >= 1) {
//Instruction* code = codeBlock->instructions().begin();
printf("#%d: %s:%d: %d / %lld (%.3f%%)\n", i + 1, record->m_executable->sourceURL().UTF8String().c_str(), codeBlock->lineNumberForBytecodeOffset(exec, 0), record->m_sampleCount, m_sampleCount, blockPercent);
if (i < 10) {
HashMap<unsigned,unsigned> lineCounts;
codeBlock->dump(exec);
printf(" Opcode and line number samples [*]\n\n");
for (unsigned op = 0; op < record->m_size; ++op) {
int count = record->m_samples[op];
if (count) {
printf(" [% 4d] has sample count: % 4d\n", op, count);
unsigned line = codeBlock->lineNumberForBytecodeOffset(exec, op);
lineCounts.set(line, (lineCounts.contains(line) ? lineCounts.get(line) : 0) + count);
}
}
printf("\n");
int linesCount = lineCounts.size();
Vector<LineCountInfo> lineCountInfo(linesCount);
int lineno = 0;
for (HashMap<unsigned,unsigned>::iterator iter = lineCounts.begin(); iter != lineCounts.end(); ++iter, ++lineno) {
lineCountInfo[lineno].line = iter->first;
lineCountInfo[lineno].count = iter->second;
}
qsort(lineCountInfo.begin(), linesCount, sizeof(LineCountInfo), compareLineCountInfoSampling);
for (lineno = 0; lineno < linesCount; ++lineno) {
printf(" Line #%d has sample count %d.\n", lineCountInfo[lineno].line, lineCountInfo[lineno].count);
}
printf("\n");
printf(" [*] Samples inside host code are charged to the calling Bytecode.\n");
printf(" Samples on a call / return boundary are not charged to a specific opcode or line.\n\n");
printf(" Samples on a call / return boundary: %d / %d (%.3f%%)\n\n", record->m_sampleCount - record->m_opcodeSampleCount, record->m_sampleCount, (static_cast<double>(record->m_sampleCount - record->m_opcodeSampleCount) * 100) / record->m_sampleCount);
}
}
}
#else
Q_UNUSED(exec);
#endif // ENABLE(CODEBLOCK_SAMPLING)
}
#endif // ENABLE(OPCODE_SAMPLING)
void AbstractSamplingCounter::dump()
{
#if ENABLE(SAMPLING_COUNTERS)
if (s_abstractSamplingCounterChain != &s_abstractSamplingCounterChainEnd) {
printf("\nSampling Counter Values:\n");
for (AbstractSamplingCounter* currCounter = s_abstractSamplingCounterChain; (currCounter != &s_abstractSamplingCounterChainEnd); currCounter = currCounter->m_next)
printf("\t%s\t: %lld\n", currCounter->m_name, currCounter->m_counter);
printf("\n\n");
}
s_completed = true;
#endif
}
AbstractSamplingCounter AbstractSamplingCounter::s_abstractSamplingCounterChainEnd;
AbstractSamplingCounter* AbstractSamplingCounter::s_abstractSamplingCounterChain = &s_abstractSamplingCounterChainEnd;
bool AbstractSamplingCounter::s_completed = false;
} // namespace JSC

View file

@ -1,414 +0,0 @@
/*
* Copyright (C) 2008 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef SamplingTool_h
#define SamplingTool_h
#include <wtf/Assertions.h>
#include <wtf/HashMap.h>
#include <wtf/Threading.h>
#include "Nodes.h"
#include "Opcode.h"
namespace JSC {
class ScriptExecutable;
class SamplingFlags {
public:
static void start();
static void stop();
#if ENABLE(SAMPLING_FLAGS)
static void setFlag(unsigned flag)
{
Q_ASSERT(flag >= 1);
Q_ASSERT(flag <= 32);
s_flags |= 1u << (flag - 1);
}
static void clearFlag(unsigned flag)
{
Q_ASSERT(flag >= 1);
Q_ASSERT(flag <= 32);
s_flags &= ~(1u << (flag - 1));
}
static void sample();
class ScopedFlag {
public:
ScopedFlag(int flag)
: m_flag(flag)
{
setFlag(flag);
}
~ScopedFlag()
{
clearFlag(m_flag);
}
private:
int m_flag;
};
#endif
private:
static uint32_t s_flags;
#if ENABLE(SAMPLING_FLAGS)
static uint64_t s_flagCounts[33];
#endif
};
class CodeBlock;
class ExecState;
class Interpreter;
class ScopeNode;
struct Instruction;
struct ScriptSampleRecord {
ScriptSampleRecord(ScriptExecutable* executable)
: m_executable(executable)
, m_codeBlock(0)
, m_sampleCount(0)
, m_opcodeSampleCount(0)
, m_samples(0)
, m_size(0)
{
}
~ScriptSampleRecord()
{
if (m_samples)
free(m_samples);
}
void sample(CodeBlock*, Instruction*);
RefPtr<ScriptExecutable> m_executable;
CodeBlock* m_codeBlock;
int m_sampleCount;
int m_opcodeSampleCount;
int* m_samples;
unsigned m_size;
};
typedef WTF::HashMap<ScriptExecutable*, ScriptSampleRecord*> ScriptSampleRecordMap;
class SamplingThread {
public:
// Sampling thread state.
static bool s_running;
static unsigned s_hertz;
static ThreadIdentifier s_samplingThread;
static void start(unsigned hertz=10000);
static void stop();
static void* threadStartFunc(void*);
};
class SamplingTool {
public:
friend struct CallRecord;
friend class HostCallRecord;
#if ENABLE(OPCODE_SAMPLING)
class CallRecord : public Noncopyable {
public:
CallRecord(SamplingTool* samplingTool)
: m_samplingTool(samplingTool)
, m_savedSample(samplingTool->m_sample)
, m_savedCodeBlock(samplingTool->m_codeBlock)
{
}
~CallRecord()
{
m_samplingTool->m_sample = m_savedSample;
m_samplingTool->m_codeBlock = m_savedCodeBlock;
}
private:
SamplingTool* m_samplingTool;
intptr_t m_savedSample;
CodeBlock* m_savedCodeBlock;
};
class HostCallRecord : public CallRecord {
public:
HostCallRecord(SamplingTool* samplingTool)
: CallRecord(samplingTool)
{
samplingTool->m_sample |= 0x1;
}
};
#else
class CallRecord : public Noncopyable {
public:
CallRecord(SamplingTool*)
{
}
};
class HostCallRecord : public CallRecord {
public:
HostCallRecord(SamplingTool* samplingTool)
: CallRecord(samplingTool)
{
}
};
#endif
SamplingTool(Interpreter* interpreter)
: m_interpreter(interpreter)
, m_codeBlock(0)
, m_sample(0)
, m_sampleCount(0)
, m_opcodeSampleCount(0)
#if ENABLE(CODEBLOCK_SAMPLING)
, m_scopeSampleMap(new ScriptSampleRecordMap())
#endif
{
memset(m_opcodeSamples, 0, sizeof(m_opcodeSamples));
memset(m_opcodeSamplesInCTIFunctions, 0, sizeof(m_opcodeSamplesInCTIFunctions));
}
~SamplingTool()
{
#if ENABLE(CODEBLOCK_SAMPLING)
deleteAllValues(*m_scopeSampleMap);
#endif
}
void setup();
#if ENABLE(OPCODE_SAMPLING)
void dump(ExecState*);
#endif
void notifyOfScope(ScriptExecutable* scope);
void sample(CodeBlock* codeBlock, Instruction* vPC)
{
Q_ASSERT(!(reinterpret_cast<intptr_t>(vPC) & 0x3));
m_codeBlock = codeBlock;
m_sample = reinterpret_cast<intptr_t>(vPC);
}
CodeBlock** codeBlockSlot() { return &m_codeBlock; }
intptr_t* sampleSlot() { return &m_sample; }
void* encodeSample(Instruction* vPC, bool inCTIFunction = false, bool inHostFunction = false)
{
Q_ASSERT(!(reinterpret_cast<intptr_t>(vPC) & 0x3));
return reinterpret_cast<void*>(reinterpret_cast<intptr_t>(vPC) | (static_cast<intptr_t>(inCTIFunction) << 1) | static_cast<intptr_t>(inHostFunction));
}
static void sample();
private:
class Sample {
public:
Sample(volatile intptr_t sample, CodeBlock* volatile codeBlock)
: m_sample(sample)
, m_codeBlock(codeBlock)
{
}
bool isNull() { return !m_sample; }
CodeBlock* codeBlock() { return m_codeBlock; }
Instruction* vPC() { return reinterpret_cast<Instruction*>(m_sample & ~0x3); }
bool inHostFunction() { return m_sample & 0x1; }
bool inCTIFunction() { return m_sample & 0x2; }
private:
intptr_t m_sample;
CodeBlock* m_codeBlock;
};
void doRun();
static SamplingTool* s_samplingTool;
Interpreter* m_interpreter;
// State tracked by the main thread, used by the sampling thread.
CodeBlock* m_codeBlock;
intptr_t m_sample;
// Gathered sample data.
long long m_sampleCount;
long long m_opcodeSampleCount;
unsigned m_opcodeSamples[numOpcodeIDs];
unsigned m_opcodeSamplesInCTIFunctions[numOpcodeIDs];
#if ENABLE(CODEBLOCK_SAMPLING)
QMutex m_scriptSampleMapMutex;
OwnPtr<ScriptSampleRecordMap> m_scopeSampleMap;
#endif
};
// AbstractSamplingCounter:
//
// Implements a named set of counters, printed on exit if ENABLE(SAMPLING_COUNTERS).
// See subclasses below, SamplingCounter, GlobalSamplingCounter and DeletableSamplingCounter.
class AbstractSamplingCounter {
friend class DeletableSamplingCounter;
public:
void count(uint32_t count = 1)
{
m_counter += count;
}
static void dump();
protected:
// Effectively the contructor, however called lazily in the case of GlobalSamplingCounter.
void init(const char* name)
{
m_counter = 0;
m_name = name;
// Set m_next to point to the head of the chain, and inform whatever is
// currently at the head that this node will now hold the pointer to it.
m_next = s_abstractSamplingCounterChain;
s_abstractSamplingCounterChain->m_referer = &m_next;
// Add this node to the head of the list.
s_abstractSamplingCounterChain = this;
m_referer = &s_abstractSamplingCounterChain;
}
int64_t m_counter;
const char* m_name;
AbstractSamplingCounter* m_next;
// This is a pointer to the pointer to this node in the chain; used to
// allow fast linked list deletion.
AbstractSamplingCounter** m_referer;
// Null object used to detect end of static chain.
static AbstractSamplingCounter s_abstractSamplingCounterChainEnd;
static AbstractSamplingCounter* s_abstractSamplingCounterChain;
static bool s_completed;
};
#if ENABLE(SAMPLING_COUNTERS)
// SamplingCounter:
//
// This class is suitable and (hopefully!) convenient for cases where a counter is
// required within the scope of a single function. It can be instantiated as a
// static variable since it contains a constructor but not a destructor (static
// variables in WebKit cannot have destructors).
//
// For example:
//
// void someFunction()
// {
// static SamplingCounter countMe("This is my counter. There are many like it, but this one is mine.");
// countMe.count();
// // ...
// }
//
class SamplingCounter : public AbstractSamplingCounter {
public:
SamplingCounter(const char* name) { init(name); }
};
// GlobalSamplingCounter:
//
// This class is suitable for use where a counter is to be declared globally,
// since it contains neither a constructor nor destructor. Instead, ensure
// that 'name()' is called to provide the counter with a name (and also to
// allow it to be printed out on exit).
//
// GlobalSamplingCounter globalCounter;
//
// void firstFunction()
// {
// // Put this within a function that is definitely called!
// // (Or alternatively alongside all calls to 'count()').
// globalCounter.name("I Name You Destroyer.");
// globalCounter.count();
// // ...
// }
//
// void secondFunction()
// {
// globalCounter.count();
// // ...
// }
//
class GlobalSamplingCounter : public AbstractSamplingCounter {
public:
void name(const char* name)
{
// Global objects should be mapped in zero filled memory, so this should
// be a safe (albeit not necessarily threadsafe) check for 'first call'.
if (!m_next)
init(name);
}
};
// DeletableSamplingCounter:
//
// The above classes (SamplingCounter, GlobalSamplingCounter), are intended for
// use within a global or static scope, and as such cannot have a destructor.
// This means there is no convenient way for them to remove themselves from the
// static list of counters, and should an instance of either class be freed
// before 'dump()' has walked over the list it will potentially walk over an
// invalid pointer.
//
// This class is intended for use where the counter may possibly be deleted before
// the program exits. Should this occur, the counter will print it's value to
// stderr, and remove itself from the static list. Example:
//
// DeletableSamplingCounter* counter = new DeletableSamplingCounter("The Counter With No Name");
// counter->count();
// delete counter;
//
class DeletableSamplingCounter : public AbstractSamplingCounter {
public:
DeletableSamplingCounter(const char* name) { init(name); }
~DeletableSamplingCounter()
{
if (!s_completed)
fprintf(stderr, "DeletableSamplingCounter \"%s\" deleted early (with count %lld)\n", m_name, m_counter);
// Our m_referer pointer should know where the pointer to this node is,
// and m_next should know that this node is the previous node in the list.
Q_ASSERT(*m_referer == this);
Q_ASSERT(m_next->m_referer == &m_next);
// Remove this node from the list, and inform m_next that we have done so.
m_next->m_referer = m_referer;
*m_referer = m_next;
}
};
#endif
} // namespace JSC
#endif // SamplingTool_h

File diff suppressed because it is too large Load diff

View file

@ -1,529 +0,0 @@
/*
* Copyright (C) 2008, 2009 Apple Inc. All rights reserved.
* Copyright (C) 2008 Cameron Zwarich <cwzwarich@uwaterloo.ca>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef BytecodeGenerator_h
#define BytecodeGenerator_h
#include "CodeBlock.h"
#include "HashTraits.h"
#include "Instruction.h"
#include "Label.h"
#include "LabelScope.h"
#include "Interpreter.h"
#include "RegisterID.h"
#include "SymbolTable.h"
#include "Debugger.h"
#include "Nodes.h"
#include <wtf/FastAllocBase.h>
#include <wtf/PassRefPtr.h>
#include <wtf/SegmentedVector.h>
#include <wtf/Vector.h>
namespace JSC {
class Identifier;
class ScopeChain;
class ScopeNode;
struct FinallyContext {
Label* finallyAddr;
RegisterID* retAddrDst;
};
struct ControlFlowContext {
bool isFinallyBlock;
FinallyContext finallyContext;
};
struct ForInContext {
RefPtr<RegisterID> expectedSubscriptRegister;
RefPtr<RegisterID> iterRegister;
RefPtr<RegisterID> indexRegister;
RefPtr<RegisterID> propertyRegister;
};
class BytecodeGenerator : public FastAllocBase {
public:
typedef DeclarationStacks::VarStack VarStack;
typedef DeclarationStacks::FunctionStack FunctionStack;
static void setDumpsGeneratedCode(bool dumpsGeneratedCode);
static bool dumpsGeneratedCode();
BytecodeGenerator(ProgramNode*, const Debugger*, const ScopeChain&, SymbolTable*, ProgramCodeBlock*);
BytecodeGenerator(FunctionBodyNode*, const Debugger*, const ScopeChain&, SymbolTable*, CodeBlock*);
BytecodeGenerator(EvalNode*, const Debugger*, const ScopeChain&, SymbolTable*, EvalCodeBlock*);
JSGlobalData* globalData() const { return m_globalData; }
const CommonIdentifiers& propertyNames() const { return *m_globalData->propertyNames; }
void generate();
// Returns the register corresponding to a local variable, or 0 if no
// such register exists. Registers returned by registerFor do not
// require explicit reference counting.
RegisterID* registerFor(const Identifier&);
bool willResolveToArguments(const Identifier&);
RegisterID* uncheckedRegisterForArguments();
// Behaves as registerFor does, but ignores dynamic scope as
// dynamic scope should not interfere with const initialisation
RegisterID* constRegisterFor(const Identifier&);
// Searches the scope chain in an attempt to statically locate the requested
// property. Returns false if for any reason the property cannot be safely
// optimised at all. Otherwise it will return the index and depth of the
// VariableObject that defines the property. If the property cannot be found
// statically, depth will contain the depth of the scope chain where dynamic
// lookup must begin.
//
// NB: depth does _not_ include the local scope. eg. a depth of 0 refers
// to the scope containing this codeblock.
bool findScopedProperty(const Identifier&, int& index, size_t& depth, bool forWriting, JSObject*& globalObject);
// Returns the register storing "this"
RegisterID* thisRegister() { return &m_thisRegister; }
bool isLocal(const Identifier&);
bool isLocalConstant(const Identifier&);
// Returns the next available temporary register. Registers returned by
// newTemporary require a modified form of reference counting: any
// register with a refcount of 0 is considered "available", meaning that
// the next instruction may overwrite it.
RegisterID* newTemporary();
RegisterID* highestUsedRegister();
// The same as newTemporary(), but this function returns "suggestion" if
// "suggestion" is a temporary. This function is helpful in situations
// where you've put "suggestion" in a RefPtr, but you'd like to allow
// the next instruction to overwrite it anyway.
RegisterID* newTemporaryOr(RegisterID* suggestion) { return suggestion->isTemporary() ? suggestion : newTemporary(); }
// Functions for handling of dst register
RegisterID* ignoredResult() { return &m_ignoredResultRegister; }
// Returns a place to write intermediate values of an operation
// which reuses dst if it is safe to do so.
RegisterID* tempDestination(RegisterID* dst)
{
return (dst && dst != ignoredResult() && dst->isTemporary()) ? dst : newTemporary();
}
// Returns the place to write the final output of an operation.
RegisterID* finalDestination(RegisterID* originalDst, RegisterID* tempDst = 0)
{
if (originalDst && originalDst != ignoredResult())
return originalDst;
Q_ASSERT(tempDst != ignoredResult());
if (tempDst && tempDst->isTemporary())
return tempDst;
return newTemporary();
}
RegisterID* destinationForAssignResult(RegisterID* dst)
{
if (dst && dst != ignoredResult() && m_codeBlock->needsFullScopeChain())
return dst->isTemporary() ? dst : newTemporary();
return 0;
}
// Moves src to dst if dst is not null and is different from src, otherwise just returns src.
RegisterID* moveToDestinationIfNeeded(RegisterID* dst, RegisterID* src)
{
return dst == ignoredResult() ? 0 : (dst && dst != src) ? emitMove(dst, src) : src;
}
PassRefPtr<LabelScope> newLabelScope(LabelScope::Type, const Identifier* = 0);
PassRefPtr<Label> newLabel();
// The emitNode functions are just syntactic sugar for calling
// Node::emitCode. These functions accept a 0 for the register,
// meaning that the node should allocate a register, or ignoredResult(),
// meaning that the node need not put the result in a register.
// Other emit functions do not accept 0 or ignoredResult().
RegisterID* emitNode(RegisterID* dst, Node* n)
{
// Node::emitCode assumes that dst, if provided, is either a local or a referenced temporary.
Q_ASSERT(!dst || dst == ignoredResult() || !dst->isTemporary() || dst->refCount());
if (!m_codeBlock->numberOfLineInfos() || m_codeBlock->lastLineInfo().lineNumber != n->lineNo()) {
LineInfo info = { static_cast<uint32_t>(instructions().size()), n->lineNo() };
m_codeBlock->addLineInfo(info);
}
if (m_emitNodeDepth >= s_maxEmitNodeDepth)
return emitThrowExpressionTooDeepException();
++m_emitNodeDepth;
RegisterID* r = n->emitBytecode(*this, dst);
--m_emitNodeDepth;
return r;
}
inline RegisterID* emitNode(Node* n)
{
return emitNode(0, n);
}
void emitNodeInConditionContext(ExpressionNode* n, Label* trueTarget, Label* falseTarget, bool fallThroughMeansTrue)
{
if (!m_codeBlock->numberOfLineInfos() || m_codeBlock->lastLineInfo().lineNumber != n->lineNo()) {
LineInfo info = { static_cast<uint32_t>(instructions().size()), n->lineNo() };
m_codeBlock->addLineInfo(info);
}
if (m_emitNodeDepth >= s_maxEmitNodeDepth)
emitThrowExpressionTooDeepException();
++m_emitNodeDepth;
n->emitBytecodeInConditionContext(*this, trueTarget, falseTarget, fallThroughMeansTrue);
--m_emitNodeDepth;
}
void emitExpressionInfo(unsigned divot, unsigned startOffset, unsigned endOffset)
{
divot -= m_codeBlock->sourceOffset();
if (divot > ExpressionRangeInfo::MaxDivot) {
// Overflow has occurred, we can only give line number info for errors for this region
divot = 0;
startOffset = 0;
endOffset = 0;
} else if (startOffset > ExpressionRangeInfo::MaxOffset) {
// If the start offset is out of bounds we clear both offsets
// so we only get the divot marker. Error message will have to be reduced
// to line and column number.
startOffset = 0;
endOffset = 0;
} else if (endOffset > ExpressionRangeInfo::MaxOffset) {
// The end offset is only used for additional context, and is much more likely
// to overflow (eg. function call arguments) so we are willing to drop it without
// dropping the rest of the range.
endOffset = 0;
}
ExpressionRangeInfo info;
info.instructionOffset = instructions().size();
info.divotPoint = divot;
info.startOffset = startOffset;
info.endOffset = endOffset;
m_codeBlock->addExpressionInfo(info);
}
void emitGetByIdExceptionInfo(OpcodeID opcodeID)
{
// Only op_construct and op_instanceof need exception info for
// a preceding op_get_by_id.
Q_ASSERT(opcodeID == op_construct || opcodeID == op_instanceof);
GetByIdExceptionInfo info;
info.bytecodeOffset = instructions().size();
info.isOpConstruct = (opcodeID == op_construct);
m_codeBlock->addGetByIdExceptionInfo(info);
}
ALWAYS_INLINE bool leftHandSideNeedsCopy(bool rightHasAssignments, bool rightIsPure)
{
return (m_codeType != FunctionCode || m_codeBlock->needsFullScopeChain() || rightHasAssignments) && !rightIsPure;
}
ALWAYS_INLINE PassRefPtr<RegisterID> emitNodeForLeftHandSide(ExpressionNode* n, bool rightHasAssignments, bool rightIsPure)
{
if (leftHandSideNeedsCopy(rightHasAssignments, rightIsPure)) {
PassRefPtr<RegisterID> dst = newTemporary();
emitNode(dst.get(), n);
return dst;
}
return PassRefPtr<RegisterID>(emitNode(n));
}
RegisterID* emitLoad(RegisterID* dst, bool);
RegisterID* emitLoad(RegisterID* dst, double);
RegisterID* emitLoad(RegisterID* dst, const Identifier&);
RegisterID* emitLoad(RegisterID* dst, JSValue);
RegisterID* emitUnaryOp(OpcodeID, RegisterID* dst, RegisterID* src);
RegisterID* emitBinaryOp(OpcodeID, RegisterID* dst, RegisterID* src1, RegisterID* src2, OperandTypes);
RegisterID* emitEqualityOp(OpcodeID, RegisterID* dst, RegisterID* src1, RegisterID* src2);
RegisterID* emitUnaryNoDstOp(OpcodeID, RegisterID* src);
RegisterID* emitNewObject(RegisterID* dst);
RegisterID* emitNewArray(RegisterID* dst, ElementNode*); // stops at first elision
RegisterID* emitNewFunction(RegisterID* dst, FunctionBodyNode* body);
RegisterID* emitNewFunctionExpression(RegisterID* dst, FuncExprNode* func);
RegisterID* emitNewRegExp(RegisterID* dst, RegExp* regExp);
RegisterID* emitMove(RegisterID* dst, RegisterID* src);
RegisterID* emitToJSNumber(RegisterID* dst, RegisterID* src) { return emitUnaryOp(op_to_jsnumber, dst, src); }
RegisterID* emitPreInc(RegisterID* srcDst);
RegisterID* emitPreDec(RegisterID* srcDst);
RegisterID* emitPostInc(RegisterID* dst, RegisterID* srcDst);
RegisterID* emitPostDec(RegisterID* dst, RegisterID* srcDst);
RegisterID* emitInstanceOf(RegisterID* dst, RegisterID* value, RegisterID* base, RegisterID* basePrototype);
RegisterID* emitTypeOf(RegisterID* dst, RegisterID* src) { return emitUnaryOp(op_typeof, dst, src); }
RegisterID* emitIn(RegisterID* dst, RegisterID* property, RegisterID* base) { return emitBinaryOp(op_in, dst, property, base, OperandTypes()); }
RegisterID* emitResolve(RegisterID* dst, const Identifier& property);
RegisterID* emitGetScopedVar(RegisterID* dst, size_t skip, int index, JSValue globalObject);
RegisterID* emitPutScopedVar(size_t skip, int index, RegisterID* value, JSValue globalObject);
RegisterID* emitResolveBase(RegisterID* dst, const Identifier& property);
RegisterID* emitResolveWithBase(RegisterID* baseDst, RegisterID* propDst, const Identifier& property);
void emitMethodCheck();
RegisterID* emitGetById(RegisterID* dst, RegisterID* base, const Identifier& property);
RegisterID* emitPutById(RegisterID* base, const Identifier& property, RegisterID* value);
RegisterID* emitDeleteById(RegisterID* dst, RegisterID* base, const Identifier&);
RegisterID* emitGetByVal(RegisterID* dst, RegisterID* base, RegisterID* property);
RegisterID* emitPutByVal(RegisterID* base, RegisterID* property, RegisterID* value);
RegisterID* emitDeleteByVal(RegisterID* dst, RegisterID* base, RegisterID* property);
RegisterID* emitPutByIndex(RegisterID* base, unsigned index, RegisterID* value);
RegisterID* emitPutGetter(RegisterID* base, const Identifier& property, RegisterID* value);
RegisterID* emitPutSetter(RegisterID* base, const Identifier& property, RegisterID* value);
RegisterID* emitCall(RegisterID* dst, RegisterID* func, RegisterID* thisRegister, ArgumentsNode*, unsigned divot, unsigned startOffset, unsigned endOffset);
RegisterID* emitCallEval(RegisterID* dst, RegisterID* func, RegisterID* thisRegister, ArgumentsNode*, unsigned divot, unsigned startOffset, unsigned endOffset);
RegisterID* emitCallVarargs(RegisterID* dst, RegisterID* func, RegisterID* thisRegister, RegisterID* argCount, unsigned divot, unsigned startOffset, unsigned endOffset);
RegisterID* emitLoadVarargs(RegisterID* argCountDst, RegisterID* args);
RegisterID* emitReturn(RegisterID* src);
RegisterID* emitEnd(RegisterID* src) { return emitUnaryNoDstOp(op_end, src); }
RegisterID* emitConstruct(RegisterID* dst, RegisterID* func, ArgumentsNode*, unsigned divot, unsigned startOffset, unsigned endOffset);
RegisterID* emitStrcat(RegisterID* dst, RegisterID* src, int count);
void emitToPrimitive(RegisterID* dst, RegisterID* src);
PassRefPtr<Label> emitLabel(Label*);
PassRefPtr<Label> emitJump(Label* target);
PassRefPtr<Label> emitJumpIfTrue(RegisterID* cond, Label* target);
PassRefPtr<Label> emitJumpIfFalse(RegisterID* cond, Label* target);
PassRefPtr<Label> emitJumpIfNotFunctionCall(RegisterID* cond, Label* target);
PassRefPtr<Label> emitJumpIfNotFunctionApply(RegisterID* cond, Label* target);
PassRefPtr<Label> emitJumpScopes(Label* target, int targetScopeDepth);
PassRefPtr<Label> emitJumpSubroutine(RegisterID* retAddrDst, Label*);
void emitSubroutineReturn(RegisterID* retAddrSrc);
RegisterID* emitGetPropertyNames(RegisterID* dst, RegisterID* base, RegisterID* i, RegisterID* size, Label* breakTarget);
RegisterID* emitNextPropertyName(RegisterID* dst, RegisterID* base, RegisterID* i, RegisterID* size, RegisterID* iter, Label* target);
RegisterID* emitCatch(RegisterID*, Label* start, Label* end);
void emitThrow(RegisterID* exc) { emitUnaryNoDstOp(op_throw, exc); }
RegisterID* emitNewError(RegisterID* dst, ErrorType type, JSValue message);
void emitPushNewScope(RegisterID* dst, const Identifier& property, RegisterID* value);
RegisterID* emitPushScope(RegisterID* scope);
void emitPopScope();
void emitDebugHook(DebugHookID, int firstLine, int lastLine);
int scopeDepth() { return m_dynamicScopeDepth + m_finallyDepth; }
bool hasFinaliser() { return m_finallyDepth != 0; }
void pushFinallyContext(Label* target, RegisterID* returnAddrDst);
void popFinallyContext();
void pushOptimisedForIn(RegisterID* expectedBase, RegisterID* iter, RegisterID* index, RegisterID* propertyRegister)
{
ForInContext context = { expectedBase, iter, index, propertyRegister };
m_forInContextStack.append(context);
}
void popOptimisedForIn()
{
m_forInContextStack.removeLast();
}
LabelScope* breakTarget(const Identifier&);
LabelScope* continueTarget(const Identifier&);
void beginSwitch(RegisterID*, SwitchInfo::SwitchType);
void endSwitch(uint32_t clauseCount, RefPtr<Label>*, ExpressionNode**, Label* defaultLabel, int32_t min, int32_t range);
CodeType codeType() const { return m_codeType; }
void setRegeneratingForExceptionInfo(CodeBlock* originalCodeBlock)
{
m_regeneratingForExceptionInfo = true;
m_codeBlockBeingRegeneratedFrom = originalCodeBlock;
}
private:
void emitOpcode(OpcodeID);
void retrieveLastBinaryOp(int& dstIndex, int& src1Index, int& src2Index);
void retrieveLastUnaryOp(int& dstIndex, int& srcIndex);
void rewindBinaryOp();
void rewindUnaryOp();
PassRefPtr<Label> emitComplexJumpScopes(Label* target, ControlFlowContext* topScope, ControlFlowContext* bottomScope);
typedef HashMap<EncodedJSValue, unsigned, EncodedJSValueHash, EncodedJSValueHashTraits> JSValueMap;
struct IdentifierMapIndexHashTraits {
typedef int TraitType;
typedef IdentifierMapIndexHashTraits StorageTraits;
static int emptyValue() { return std::numeric_limits<int>::max(); }
static const bool emptyValueIsZero = false;
static const bool needsDestruction = false;
static const bool needsRef = false;
};
typedef HashMap<RefPtr<UString::Rep>, int, IdentifierRepHash, HashTraits<RefPtr<UString::Rep> >, IdentifierMapIndexHashTraits> IdentifierMap;
typedef HashMap<double, JSValue> NumberMap;
typedef HashMap<UString::Rep*, JSString*, IdentifierRepHash> IdentifierStringMap;
RegisterID* emitCall(OpcodeID, RegisterID* dst, RegisterID* func, RegisterID* thisRegister, ArgumentsNode*, unsigned divot, unsigned startOffset, unsigned endOffset);
RegisterID* newRegister();
// Returns the RegisterID corresponding to ident.
RegisterID* addVar(const Identifier& ident, bool isConstant)
{
RegisterID* local;
addVar(ident, isConstant, local);
return local;
}
// Returns true if a new RegisterID was added, false if a pre-existing RegisterID was re-used.
bool addVar(const Identifier&, bool isConstant, RegisterID*&);
// Returns the RegisterID corresponding to ident.
RegisterID* addGlobalVar(const Identifier& ident, bool isConstant)
{
RegisterID* local;
addGlobalVar(ident, isConstant, local);
return local;
}
// Returns true if a new RegisterID was added, false if a pre-existing RegisterID was re-used.
bool addGlobalVar(const Identifier&, bool isConstant, RegisterID*&);
RegisterID* addParameter(const Identifier&);
void preserveLastVar();
RegisterID& registerFor(int index)
{
if (index >= 0)
return m_calleeRegisters[index];
if (index == RegisterFile::OptionalCalleeArguments)
return m_argumentsRegister;
if (m_parameters.size()) {
Q_ASSERT(!m_globals.size());
return m_parameters[index + m_parameters.size() + RegisterFile::CallFrameHeaderSize];
}
return m_globals[-index - 1];
}
unsigned addConstant(const Identifier&);
RegisterID* addConstantValue(JSValue);
unsigned addRegExp(RegExp*);
PassRefPtr<FunctionExecutable> makeFunction(ExecState* exec, FunctionBodyNode* body)
{
return FunctionExecutable::create(exec, body->ident(), body->source(), body->usesArguments(), body->parameters(), body->lineNo(), body->lastLine());
}
PassRefPtr<FunctionExecutable> makeFunction(JSGlobalData* globalData, FunctionBodyNode* body)
{
return FunctionExecutable::create(globalData, body->ident(), body->source(), body->usesArguments(), body->parameters(), body->lineNo(), body->lastLine());
}
Vector<Instruction>& instructions() { return m_codeBlock->instructions(); }
SymbolTable& symbolTable() { return *m_symbolTable; }
bool shouldOptimizeLocals() { return (m_codeType != EvalCode) && !m_dynamicScopeDepth; }
bool canOptimizeNonLocals() { return (m_codeType == FunctionCode) && !m_dynamicScopeDepth && !m_codeBlock->usesEval(); }
RegisterID* emitThrowExpressionTooDeepException();
void createArgumentsIfNecessary();
bool m_shouldEmitDebugHooks;
const ScopeChain* m_scopeChain;
SymbolTable* m_symbolTable;
ScopeNode* m_scopeNode;
CodeBlock* m_codeBlock;
// Some of these objects keep pointers to one another. They are arranged
// to ensure a sane destruction order that avoids references to freed memory.
HashSet<RefPtr<UString::Rep>, IdentifierRepHash> m_functions;
RegisterID m_ignoredResultRegister;
RegisterID m_thisRegister;
RegisterID m_argumentsRegister;
int m_activationRegisterIndex;
SegmentedVector<RegisterID, 32> m_constantPoolRegisters;
SegmentedVector<RegisterID, 32> m_calleeRegisters;
SegmentedVector<RegisterID, 32> m_parameters;
SegmentedVector<RegisterID, 32> m_globals;
SegmentedVector<Label, 32> m_labels;
SegmentedVector<LabelScope, 8> m_labelScopes;
RefPtr<RegisterID> m_lastVar;
int m_finallyDepth;
int m_dynamicScopeDepth;
int m_baseScopeDepth;
CodeType m_codeType;
Vector<ControlFlowContext> m_scopeContextStack;
Vector<SwitchInfo> m_switchContextStack;
Vector<ForInContext> m_forInContextStack;
int m_nextGlobalIndex;
int m_nextParameterIndex;
int m_firstConstantIndex;
int m_nextConstantOffset;
int m_globalVarStorageOffset;
// Constant pool
IdentifierMap m_identifierMap;
JSValueMap m_jsValueMap;
NumberMap m_numberMap;
IdentifierStringMap m_stringMap;
JSGlobalData* m_globalData;
OpcodeID m_lastOpcodeID;
unsigned m_emitNodeDepth;
bool m_regeneratingForExceptionInfo;
CodeBlock* m_codeBlockBeingRegeneratedFrom;
static const unsigned s_maxEmitNodeDepth = 5000;
};
}
#endif // BytecodeGenerator_h

View file

@ -1,90 +0,0 @@
/*
* Copyright (C) 2008 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef Label_h
#define Label_h
#include "CodeBlock.h"
#include "Instruction.h"
#include <wtf/Assertions.h>
#include <wtf/Vector.h>
#include <limits.h>
namespace JSC {
class Label {
public:
explicit Label(CodeBlock* codeBlock)
: m_refCount(0)
, m_location(invalidLocation)
, m_codeBlock(codeBlock)
{
}
void setLocation(unsigned location)
{
m_location = location;
unsigned size = m_unresolvedJumps.size();
for (unsigned i = 0; i < size; ++i)
m_codeBlock->instructions()[m_unresolvedJumps[i].second].u.operand = m_location - m_unresolvedJumps[i].first;
}
int bind(int opcode, int offset) const
{
if (m_location == invalidLocation) {
m_unresolvedJumps.append(std::make_pair(opcode, offset));
return 0;
}
return m_location - opcode;
}
void ref() { ++m_refCount; }
void deref()
{
--m_refCount;
Q_ASSERT(m_refCount >= 0);
}
int refCount() const { return m_refCount; }
bool isForward() const { return m_location == invalidLocation; }
private:
typedef Vector<std::pair<int, int>, 8> JumpVector;
static const unsigned invalidLocation = UINT_MAX;
int m_refCount;
unsigned m_location;
CodeBlock* m_codeBlock;
mutable JumpVector m_unresolvedJumps;
};
} // namespace JSC
#endif // Label_h

View file

@ -1,79 +0,0 @@
/*
* Copyright (C) 2008 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef LabelScope_h
#define LabelScope_h
#include <wtf/PassRefPtr.h>
#include "Label.h"
namespace JSC {
class Identifier;
class LabelScope {
public:
enum Type { Loop, Switch, NamedLabel };
LabelScope(Type type, const Identifier* name, int scopeDepth, PassRefPtr<Label> breakTarget, PassRefPtr<Label> continueTarget)
: m_refCount(0)
, m_type(type)
, m_name(name)
, m_scopeDepth(scopeDepth)
, m_breakTarget(breakTarget)
, m_continueTarget(continueTarget)
{
}
void ref() { ++m_refCount; }
void deref()
{
--m_refCount;
Q_ASSERT(m_refCount >= 0);
}
int refCount() const { return m_refCount; }
Label* breakTarget() const { return m_breakTarget.get(); }
Label* continueTarget() const { return m_continueTarget.get(); }
Type type() const { return m_type; }
const Identifier* name() const { return m_name; }
int scopeDepth() const { return m_scopeDepth; }
private:
int m_refCount;
Type m_type;
const Identifier* m_name;
int m_scopeDepth;
RefPtr<Label> m_breakTarget;
RefPtr<Label> m_continueTarget;
};
} // namespace JSC
#endif // LabelScope_h

File diff suppressed because it is too large Load diff

View file

@ -1,121 +0,0 @@
/*
* Copyright (C) 2008 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef RegisterID_h
#define RegisterID_h
#include <wtf/Assertions.h>
#include <wtf/Noncopyable.h>
#include <wtf/VectorTraits.h>
namespace JSC {
class RegisterID : public Noncopyable {
public:
RegisterID()
: m_refCount(0)
, m_isTemporary(false)
#ifndef QT_NO_DEBUG
, m_didSetIndex(false)
#endif
{
}
explicit RegisterID(int index)
: m_refCount(0)
, m_index(index)
, m_isTemporary(false)
#ifndef QT_NO_DEBUG
, m_didSetIndex(true)
#endif
{
}
void setIndex(int index)
{
Q_ASSERT(!m_refCount);
#ifndef QT_NO_DEBUG
m_didSetIndex = true;
#endif
m_index = index;
}
void setTemporary()
{
m_isTemporary = true;
}
int index() const
{
Q_ASSERT(m_didSetIndex);
return m_index;
}
bool isTemporary()
{
return m_isTemporary;
}
void ref()
{
++m_refCount;
}
void deref()
{
--m_refCount;
Q_ASSERT(m_refCount >= 0);
}
int refCount() const
{
return m_refCount;
}
private:
int m_refCount;
int m_index;
bool m_isTemporary;
#ifndef QT_NO_DEBUG
bool m_didSetIndex;
#endif
};
} // namespace JSC
namespace WTF {
template<> struct VectorTraits<JSC::RegisterID> : VectorTraitsBase<true, JSC::RegisterID> {
static const bool needsInitialization = true;
static const bool canInitializeWithMemset = true; // Default initialization just sets everything to 0 or false, so this is safe.
};
} // namespace WTF
#endif // RegisterID_h

View file

@ -1,274 +0,0 @@
#! /usr/bin/perl -w
#
# Static Hashtable Generator
#
# (c) 2000-2002 by Harri Porten <porten@kde.org> and
# David Faure <faure@kde.org>
# Modified (c) 2004 by Nikolas Zimmermann <wildfox@kde.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 Lesser 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
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
#
use strict;
my $file = $ARGV[0];
shift;
my $includelookup = 0;
# Use -i as second argument to make it include "Lookup.h"
$includelookup = 1 if (defined($ARGV[0]) && $ARGV[0] eq "-i");
# Use -n as second argument to make it use the third argument as namespace parameter ie. -n KDOM
my $useNameSpace = $ARGV[1] if (defined($ARGV[0]) && $ARGV[0] eq "-n");
print STDERR "Creating hashtable for $file\n";
open(IN, $file) or die "No such file $file";
my @keys = ();
my @attrs = ();
my @values = ();
my @hashes = ();
my $inside = 0;
my $name;
my $pefectHashSize;
my $compactSize;
my $compactHashSizeMask;
my $banner = 0;
sub calcPerfectHashSize();
sub calcCompactHashSize();
sub output();
sub jsc_ucfirst($);
sub hashValue($);
while (<IN>) {
chomp;
s/^\s+//;
next if /^\#|^$/; # Comment or blank line. Do nothing.
if (/^\@begin/ && !$inside) {
if (/^\@begin\s*([:_\w]+)\s*\d*\s*$/) {
$inside = 1;
$name = $1;
} else {
print STDERR "WARNING: \@begin without table name, skipping $_\n";
}
} elsif (/^\@end\s*$/ && $inside) {
calcPerfectHashSize();
calcCompactHashSize();
output();
@keys = ();
@attrs = ();
@values = ();
@hashes = ();
$inside = 0;
} elsif (/^(\S+)\s*(\S+)\s*([\w\|]*)\s*(\w*)\s*$/ && $inside) {
my $key = $1;
my $val = $2;
my $att = $3;
my $param = $4;
push(@keys, $key);
push(@attrs, length($att) > 0 ? $att : "0");
if ($att =~ m/Function/) {
push(@values, { "type" => "Function", "function" => $val, "params" => (length($param) ? $param : "") });
#printf STDERR "WARNING: Number of arguments missing for $key/$val\n" if (length($param) == 0);
} elsif (length($att)) {
my $get = $val;
my $put = !($att =~ m/ReadOnly/) ? "set" . jsc_ucfirst($val) : "0";
push(@values, { "type" => "Property", "get" => $get, "put" => $put });
} else {
push(@values, { "type" => "Lexer", "value" => $val });
}
push(@hashes, hashValue($key));
} elsif ($inside) {
die "invalid data {" . $_ . "}";
}
}
die "missing closing \@end" if ($inside);
sub jsc_ucfirst($)
{
my ($value) = @_;
if ($value =~ /js/) {
$value =~ s/js/JS/;
return $value;
}
return ucfirst($value);
}
sub ceilingToPowerOf2
{
my ($pefectHashSize) = @_;
my $powerOf2 = 1;
while ($pefectHashSize > $powerOf2) {
$powerOf2 <<= 1;
}
return $powerOf2;
}
sub calcPerfectHashSize()
{
tableSizeLoop:
for ($pefectHashSize = ceilingToPowerOf2(scalar @keys); ; $pefectHashSize += $pefectHashSize) {
my @table = ();
foreach my $key (@keys) {
my $h = hashValue($key) % $pefectHashSize;
next tableSizeLoop if $table[$h];
$table[$h] = 1;
}
last;
}
}
sub leftShift($$) {
my ($value, $distance) = @_;
return (($value << $distance) & 0xFFFFFFFF);
}
sub calcCompactHashSize()
{
my @table = ();
my @links = ();
my $compactHashSize = ceilingToPowerOf2(2 * @keys);
$compactHashSizeMask = $compactHashSize - 1;
$compactSize = $compactHashSize;
my $collisions = 0;
my $maxdepth = 0;
my $i = 0;
foreach my $key (@keys) {
my $depth = 0;
my $h = hashValue($key) % $compactHashSize;
while (defined($table[$h])) {
if (defined($links[$h])) {
$h = $links[$h];
$depth++;
} else {
$collisions++;
$links[$h] = $compactSize;
$h = $compactSize;
$compactSize++;
}
}
$table[$h] = $i;
$i++;
$maxdepth = $depth if ( $depth > $maxdepth);
}
}
# Paul Hsieh's SuperFastHash
# http://www.azillionmonkeys.com/qed/hash.html
# Ported from UString..
sub hashValue($) {
my @chars = split(/ */, $_[0]);
# This hash is designed to work on 16-bit chunks at a time. But since the normal case
# (above) is to hash UTF-16 characters, we just treat the 8-bit chars as if they
# were 16-bit chunks, which should give matching results
my $EXP2_32 = 4294967296;
my $hash = 0x9e3779b9;
my $l = scalar @chars; #I wish this was in Ruby --- Maks
my $rem = $l & 1;
$l = $l >> 1;
my $s = 0;
# Main loop
for (; $l > 0; $l--) {
$hash += ord($chars[$s]);
my $tmp = leftShift(ord($chars[$s+1]), 11) ^ $hash;
$hash = (leftShift($hash, 16)% $EXP2_32) ^ $tmp;
$s += 2;
$hash += $hash >> 11;
$hash %= $EXP2_32;
}
# Handle end case
if ($rem !=0) {
$hash += ord($chars[$s]);
$hash ^= (leftShift($hash, 11)% $EXP2_32);
$hash += $hash >> 17;
}
# Force "avalanching" of final 127 bits
$hash ^= leftShift($hash, 3);
$hash += ($hash >> 5);
$hash = ($hash% $EXP2_32);
$hash ^= (leftShift($hash, 2)% $EXP2_32);
$hash += ($hash >> 15);
$hash = $hash% $EXP2_32;
$hash ^= (leftShift($hash, 10)% $EXP2_32);
# this avoids ever returning a hash code of 0, since that is used to
# signal "hash not computed yet", using a value that is likely to be
# effectively the same as 0 when the low bits are masked
$hash = 0x80000000 if ($hash == 0);
return $hash;
}
sub output() {
if (!$banner) {
$banner = 1;
print "// Automatically generated from $file using $0. DO NOT EDIT!\n";
}
my $nameEntries = "${name}Values";
$nameEntries =~ s/:/_/g;
print "\n#include \"Lookup.h\"\n" if ($includelookup);
if ($useNameSpace) {
print "\nnamespace ${useNameSpace} {\n";
print "\nusing namespace JSC;\n";
} else {
print "\nnamespace JSC {\n";
}
my $count = scalar @keys + 1;
print "\nstatic const struct HashTableValue ${nameEntries}\[$count\] = {\n";
my $i = 0;
foreach my $key (@keys) {
my $firstValue = "";
my $secondValue = "";
if ($values[$i]{"type"} eq "Function") {
$firstValue = $values[$i]{"function"};
$secondValue = $values[$i]{"params"};
} elsif ($values[$i]{"type"} eq "Property") {
$firstValue = $values[$i]{"get"};
$secondValue = $values[$i]{"put"};
} elsif ($values[$i]{"type"} eq "Lexer") {
$firstValue = $values[$i]{"value"};
$secondValue = "0";
}
print " { \"$key\", $attrs[$i], (intptr_t)$firstValue, (intptr_t)$secondValue },\n";
$i++;
}
print " { 0, 0, 0, 0 }\n";
print "};\n\n";
print "extern const HashTable $name =\n";
print " \{ $compactSize, $compactHashSizeMask, $nameEntries, 0 \};\n";
print "} // namespace\n";
}

View file

@ -1,100 +0,0 @@
/*
* Copyright (C) 2008 Apple Inc. All rights reserved.
* Copyright (C) 1999-2001 Harri Porten (porten@kde.org)
* Copyright (C) 2001 Peter Kelly (pmk@post.com)
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
#include "Platform.h"
#include "Debugger.h"
#include "CollectorHeapIterator.h"
#include "Error.h"
#include "Interpreter.h"
#include "JSFunction.h"
#include "JSGlobalObject.h"
#include "Parser.h"
#include "Protect.h"
namespace JSC {
Debugger::~Debugger()
{
HashSet<JSGlobalObject*>::iterator end = m_globalObjects.end();
for (HashSet<JSGlobalObject*>::iterator it = m_globalObjects.begin(); it != end; ++it)
(*it)->setDebugger(0);
}
void Debugger::attach(JSGlobalObject* globalObject)
{
Q_ASSERT(!globalObject->debugger());
globalObject->setDebugger(this);
m_globalObjects.add(globalObject);
}
void Debugger::detach(JSGlobalObject* globalObject)
{
Q_ASSERT(m_globalObjects.contains(globalObject));
m_globalObjects.remove(globalObject);
globalObject->setDebugger(0);
}
void Debugger::recompileAllJSFunctions(JSGlobalData* globalData)
{
// If JavaScript is running, it's not safe to recompile, since we'll end
// up throwing away code that is live on the stack.
Q_ASSERT(!globalData->dynamicGlobalObject);
if (globalData->dynamicGlobalObject)
return;
typedef HashSet<FunctionExecutable*> FunctionExecutableSet;
typedef HashMap<SourceProvider*, ExecState*> SourceProviderMap;
FunctionExecutableSet functionExecutables;
SourceProviderMap sourceProviders;
LiveObjectIterator it = globalData->heap.primaryHeapBegin();
LiveObjectIterator heapEnd = globalData->heap.primaryHeapEnd();
for ( ; it != heapEnd; ++it) {
if (!(*it)->inherits(&JSFunction::info))
continue;
JSFunction* function = asFunction(*it);
if (function->executable()->isHostFunction())
continue;
FunctionExecutable* executable = function->jsExecutable();
// Check if the function is already in the set - if so,
// we've already retranslated it, nothing to do here.
if (!functionExecutables.add(executable).second)
continue;
ExecState* exec = function->scope().globalObject()->JSGlobalObject::globalExec();
executable->recompile(exec);
if (function->scope().globalObject()->debugger() == this)
sourceProviders.add(executable->source().provider(), exec);
}
// Call sourceParsed() after reparsing all functions because it will execute
// JavaScript in the inspector.
SourceProviderMap::const_iterator end = sourceProviders.end();
for (SourceProviderMap::const_iterator iter = sourceProviders.begin(); iter != end; ++iter)
sourceParsed(iter->second, SourceCode(iter->first), -1, 0);
}
} // namespace JSC

View file

@ -1,104 +0,0 @@
/*
* Copyright (C) 1999-2001 Harri Porten (porten@kde.org)
* Copyright (C) 2001 Peter Kelly (pmk@post.com)
* Copyright (C) 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 Lesser 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
#ifndef Debugger_h
#define Debugger_h
#include <debugger/DebuggerCallFrame.h>
#include <wtf/HashSet.h>
namespace JSC {
class ExecState;
class JSGlobalData;
class JSGlobalObject;
class JSValue;
class SourceCode;
class UString;
class Debugger {
public:
virtual ~Debugger();
void attach(JSGlobalObject*);
virtual void detach(JSGlobalObject*);
virtual void scriptUnload(QT_PREPEND_NAMESPACE(qint64) id)
{
Q_UNUSED(id);
};
virtual void scriptLoad(QT_PREPEND_NAMESPACE(qint64) id, const UString &program,
const UString &fileName, int baseLineNumber)
{
Q_UNUSED(id);
Q_UNUSED(program);
Q_UNUSED(fileName);
Q_UNUSED(baseLineNumber);
};
virtual void contextPush() {};
virtual void contextPop() {};
virtual void evaluateStart(intptr_t sourceID)
{
Q_UNUSED(sourceID);
}
virtual void evaluateStop(const JSC::JSValue& returnValue, intptr_t sourceID)
{
Q_UNUSED(sourceID);
Q_UNUSED(returnValue);
}
virtual void exceptionThrow(const JSC::DebuggerCallFrame& frame, intptr_t sourceID, bool hasHandler)
{
Q_UNUSED(frame);
Q_UNUSED(sourceID);
Q_UNUSED(hasHandler);
};
virtual void exceptionCatch(const JSC::DebuggerCallFrame& frame, intptr_t sourceID)
{
Q_UNUSED(frame);
Q_UNUSED(sourceID);
};
virtual void functionExit(const JSC::JSValue& returnValue, intptr_t sourceID)
{
Q_UNUSED(returnValue);
Q_UNUSED(sourceID);
};
virtual void sourceParsed(ExecState*, const SourceCode&, int errorLineNumber, const UString& errorMessage) = 0;
virtual void exception(const DebuggerCallFrame&, intptr_t sourceID, int lineNumber, bool hasHandler) = 0;
virtual void atStatement(const DebuggerCallFrame&, intptr_t sourceID, int lineNumber) = 0;
virtual void callEvent(const DebuggerCallFrame&, intptr_t sourceID, int lineNumber) = 0;
virtual void returnEvent(const DebuggerCallFrame&, intptr_t sourceID, int lineNumber) = 0;
virtual void willExecuteProgram(const DebuggerCallFrame&, intptr_t sourceID, int lineNumber) = 0;
virtual void didExecuteProgram(const DebuggerCallFrame&, intptr_t sourceID, int lineNumber) = 0;
virtual void didReachBreakpoint(const DebuggerCallFrame&, intptr_t sourceID, int lineNumber) = 0;
void recompileAllJSFunctions(JSGlobalData*);
private:
HashSet<JSGlobalObject*> m_globalObjects;
};
} // namespace JSC
#endif // Debugger_h

View file

@ -1,90 +0,0 @@
/*
* Copyright (C) 2008 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "Platform.h"
#include "DebuggerCallFrame.h"
#include "JSFunction.h"
#include "CodeBlock.h"
#include "Interpreter.h"
#include "Parser.h"
namespace JSC {
const UString* DebuggerCallFrame::functionName() const
{
if (!m_callFrame->codeBlock())
return 0;
JSFunction* function = asFunction(m_callFrame->callee());
if (!function)
return 0;
return &function->name(m_callFrame);
}
UString DebuggerCallFrame::calculatedFunctionName() const
{
if (!m_callFrame->codeBlock())
return 0;
JSFunction* function = asFunction(m_callFrame->callee());
if (!function)
return 0;
return function->calculatedDisplayName(m_callFrame);
}
DebuggerCallFrame::Type DebuggerCallFrame::type() const
{
if (m_callFrame->callee())
return FunctionType;
return ProgramType;
}
JSObject* DebuggerCallFrame::thisObject() const
{
if (!m_callFrame->codeBlock())
return 0;
return asObject(m_callFrame->thisValue());
}
JSValue DebuggerCallFrame::evaluate(const UString& script, JSValue& exception) const
{
if (!m_callFrame->codeBlock())
return JSValue();
RefPtr<EvalExecutable> eval = EvalExecutable::create(m_callFrame, makeSource(script));
JSObject* error = eval->compile(m_callFrame, m_callFrame->scopeChain());
if (error)
return error;
return m_callFrame->scopeChain()->globalData->interpreter->execute(eval.get(), m_callFrame, thisObject(), m_callFrame->scopeChain(), &exception);
}
} // namespace JSC

View file

@ -1,68 +0,0 @@
/*
* Copyright (C) 2008 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef DebuggerCallFrame_h
#define DebuggerCallFrame_h
#include "CallFrame.h"
namespace JSC {
class DebuggerCallFrame {
public:
enum Type { ProgramType, FunctionType };
DebuggerCallFrame(CallFrame* callFrame)
: m_callFrame(callFrame)
{
}
DebuggerCallFrame(CallFrame* callFrame, JSValue exception)
: m_callFrame(callFrame)
, m_exception(exception)
{
}
JSGlobalObject* dynamicGlobalObject() const { return m_callFrame->dynamicGlobalObject(); }
const ScopeChainNode* scopeChain() const { return m_callFrame->scopeChain(); }
const UString* functionName() const;
UString calculatedFunctionName() const;
Type type() const;
JSObject* thisObject() const;
JSValue evaluate(const UString&, JSValue& exception) const;
JSValue exception() const { return m_exception; }
CallFrame* callFrame() const { return m_callFrame; }
private:
CallFrame* m_callFrame;
JSValue m_exception;
};
} // namespace JSC
#endif // DebuggerCallFrame_h

View file

@ -1,34 +0,0 @@
// Automatically generated from ../runtime/ArrayPrototype.cpp using ../create_hash_table. DO NOT EDIT!
#include "Lookup.h"
namespace JSC {
static const struct HashTableValue arrayTableValues[22] = {
{ "toString", DontEnum|Function, (intptr_t)arrayProtoFuncToString, (intptr_t)0 },
{ "toLocaleString", DontEnum|Function, (intptr_t)arrayProtoFuncToLocaleString, (intptr_t)0 },
{ "concat", DontEnum|Function, (intptr_t)arrayProtoFuncConcat, (intptr_t)1 },
{ "join", DontEnum|Function, (intptr_t)arrayProtoFuncJoin, (intptr_t)1 },
{ "pop", DontEnum|Function, (intptr_t)arrayProtoFuncPop, (intptr_t)0 },
{ "push", DontEnum|Function, (intptr_t)arrayProtoFuncPush, (intptr_t)1 },
{ "reverse", DontEnum|Function, (intptr_t)arrayProtoFuncReverse, (intptr_t)0 },
{ "shift", DontEnum|Function, (intptr_t)arrayProtoFuncShift, (intptr_t)0 },
{ "slice", DontEnum|Function, (intptr_t)arrayProtoFuncSlice, (intptr_t)2 },
{ "sort", DontEnum|Function, (intptr_t)arrayProtoFuncSort, (intptr_t)1 },
{ "splice", DontEnum|Function, (intptr_t)arrayProtoFuncSplice, (intptr_t)2 },
{ "unshift", DontEnum|Function, (intptr_t)arrayProtoFuncUnShift, (intptr_t)1 },
{ "every", DontEnum|Function, (intptr_t)arrayProtoFuncEvery, (intptr_t)1 },
{ "forEach", DontEnum|Function, (intptr_t)arrayProtoFuncForEach, (intptr_t)1 },
{ "some", DontEnum|Function, (intptr_t)arrayProtoFuncSome, (intptr_t)1 },
{ "indexOf", DontEnum|Function, (intptr_t)arrayProtoFuncIndexOf, (intptr_t)1 },
{ "lastIndexOf", DontEnum|Function, (intptr_t)arrayProtoFuncLastIndexOf, (intptr_t)1 },
{ "filter", DontEnum|Function, (intptr_t)arrayProtoFuncFilter, (intptr_t)1 },
{ "reduce", DontEnum|Function, (intptr_t)arrayProtoFuncReduce, (intptr_t)1 },
{ "reduceRight", DontEnum|Function, (intptr_t)arrayProtoFuncReduceRight, (intptr_t)1 },
{ "map", DontEnum|Function, (intptr_t)arrayProtoFuncMap, (intptr_t)1 },
{ 0, 0, 0, 0 }
};
extern const HashTable arrayTable =
{ 65, 63, arrayTableValues, 0 };
} // namespace

View file

@ -1,59 +0,0 @@
// Automatically generated from ../runtime/DatePrototype.cpp using ../create_hash_table. DO NOT EDIT!
#include "Lookup.h"
namespace JSC {
static const struct HashTableValue dateTableValues[47] = {
{ "toString", DontEnum|Function, (intptr_t)dateProtoFuncToString, (intptr_t)0 },
{ "toISOString", DontEnum|Function, (intptr_t)dateProtoFuncToISOString, (intptr_t)0 },
{ "toUTCString", DontEnum|Function, (intptr_t)dateProtoFuncToUTCString, (intptr_t)0 },
{ "toDateString", DontEnum|Function, (intptr_t)dateProtoFuncToDateString, (intptr_t)0 },
{ "toTimeString", DontEnum|Function, (intptr_t)dateProtoFuncToTimeString, (intptr_t)0 },
{ "toLocaleString", DontEnum|Function, (intptr_t)dateProtoFuncToLocaleString, (intptr_t)0 },
{ "toLocaleDateString", DontEnum|Function, (intptr_t)dateProtoFuncToLocaleDateString, (intptr_t)0 },
{ "toLocaleTimeString", DontEnum|Function, (intptr_t)dateProtoFuncToLocaleTimeString, (intptr_t)0 },
{ "valueOf", DontEnum|Function, (intptr_t)dateProtoFuncGetTime, (intptr_t)0 },
{ "getTime", DontEnum|Function, (intptr_t)dateProtoFuncGetTime, (intptr_t)0 },
{ "getFullYear", DontEnum|Function, (intptr_t)dateProtoFuncGetFullYear, (intptr_t)0 },
{ "getUTCFullYear", DontEnum|Function, (intptr_t)dateProtoFuncGetUTCFullYear, (intptr_t)0 },
{ "toGMTString", DontEnum|Function, (intptr_t)dateProtoFuncToGMTString, (intptr_t)0 },
{ "getMonth", DontEnum|Function, (intptr_t)dateProtoFuncGetMonth, (intptr_t)0 },
{ "getUTCMonth", DontEnum|Function, (intptr_t)dateProtoFuncGetUTCMonth, (intptr_t)0 },
{ "getDate", DontEnum|Function, (intptr_t)dateProtoFuncGetDate, (intptr_t)0 },
{ "getUTCDate", DontEnum|Function, (intptr_t)dateProtoFuncGetUTCDate, (intptr_t)0 },
{ "getDay", DontEnum|Function, (intptr_t)dateProtoFuncGetDay, (intptr_t)0 },
{ "getUTCDay", DontEnum|Function, (intptr_t)dateProtoFuncGetUTCDay, (intptr_t)0 },
{ "getHours", DontEnum|Function, (intptr_t)dateProtoFuncGetHours, (intptr_t)0 },
{ "getUTCHours", DontEnum|Function, (intptr_t)dateProtoFuncGetUTCHours, (intptr_t)0 },
{ "getMinutes", DontEnum|Function, (intptr_t)dateProtoFuncGetMinutes, (intptr_t)0 },
{ "getUTCMinutes", DontEnum|Function, (intptr_t)dateProtoFuncGetUTCMinutes, (intptr_t)0 },
{ "getSeconds", DontEnum|Function, (intptr_t)dateProtoFuncGetSeconds, (intptr_t)0 },
{ "getUTCSeconds", DontEnum|Function, (intptr_t)dateProtoFuncGetUTCSeconds, (intptr_t)0 },
{ "getMilliseconds", DontEnum|Function, (intptr_t)dateProtoFuncGetMilliSeconds, (intptr_t)0 },
{ "getUTCMilliseconds", DontEnum|Function, (intptr_t)dateProtoFuncGetUTCMilliseconds, (intptr_t)0 },
{ "getTimezoneOffset", DontEnum|Function, (intptr_t)dateProtoFuncGetTimezoneOffset, (intptr_t)0 },
{ "setTime", DontEnum|Function, (intptr_t)dateProtoFuncSetTime, (intptr_t)1 },
{ "setMilliseconds", DontEnum|Function, (intptr_t)dateProtoFuncSetMilliSeconds, (intptr_t)1 },
{ "setUTCMilliseconds", DontEnum|Function, (intptr_t)dateProtoFuncSetUTCMilliseconds, (intptr_t)1 },
{ "setSeconds", DontEnum|Function, (intptr_t)dateProtoFuncSetSeconds, (intptr_t)2 },
{ "setUTCSeconds", DontEnum|Function, (intptr_t)dateProtoFuncSetUTCSeconds, (intptr_t)2 },
{ "setMinutes", DontEnum|Function, (intptr_t)dateProtoFuncSetMinutes, (intptr_t)3 },
{ "setUTCMinutes", DontEnum|Function, (intptr_t)dateProtoFuncSetUTCMinutes, (intptr_t)3 },
{ "setHours", DontEnum|Function, (intptr_t)dateProtoFuncSetHours, (intptr_t)4 },
{ "setUTCHours", DontEnum|Function, (intptr_t)dateProtoFuncSetUTCHours, (intptr_t)4 },
{ "setDate", DontEnum|Function, (intptr_t)dateProtoFuncSetDate, (intptr_t)1 },
{ "setUTCDate", DontEnum|Function, (intptr_t)dateProtoFuncSetUTCDate, (intptr_t)1 },
{ "setMonth", DontEnum|Function, (intptr_t)dateProtoFuncSetMonth, (intptr_t)2 },
{ "setUTCMonth", DontEnum|Function, (intptr_t)dateProtoFuncSetUTCMonth, (intptr_t)2 },
{ "setFullYear", DontEnum|Function, (intptr_t)dateProtoFuncSetFullYear, (intptr_t)3 },
{ "setUTCFullYear", DontEnum|Function, (intptr_t)dateProtoFuncSetUTCFullYear, (intptr_t)3 },
{ "setYear", DontEnum|Function, (intptr_t)dateProtoFuncSetYear, (intptr_t)1 },
{ "getYear", DontEnum|Function, (intptr_t)dateProtoFuncGetYear, (intptr_t)0 },
{ "toJSON", DontEnum|Function, (intptr_t)dateProtoFuncToJSON, (intptr_t)0 },
{ 0, 0, 0, 0 }
};
extern const HashTable dateTable =
{ 134, 127, dateTableValues, 0 };
} // namespace

File diff suppressed because it is too large Load diff

View file

@ -1,184 +0,0 @@
/* A Bison parser, made by GNU Bison 3.7.6. */
/* Bison interface for Yacc-like parsers in C
Copyright (C) 1984, 1989-1990, 2000-2015, 2018-2021 Free Software Foundation,
Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>. */
/* As a special exception, you may create a larger work that contains
part or all of the Bison parser skeleton and distribute that work
under terms of your choice, so long as that work isn't itself a
parser generator using the skeleton or a modified version thereof
as a parser skeleton. Alternatively, if you modify or redistribute
the parser skeleton itself, you may (at your option) remove this
special exception, which will cause the skeleton and the resulting
Bison output files to be licensed under the GNU General Public
License without this special exception.
This special exception was added by the Free Software Foundation in
version 2.2 of Bison. */
/* DO NOT RELY ON FEATURES THAT ARE NOT DOCUMENTED in the manual,
especially those whose name start with YY_ or yy_. They are
private implementation details that can be changed or removed. */
#ifndef YY_JSCYY_GRAMMAR_HPP_INCLUDED
# define YY_JSCYY_GRAMMAR_HPP_INCLUDED
/* Debug traces. */
#ifndef YYDEBUG
# define YYDEBUG 0
#endif
#if YYDEBUG
extern int jscyydebug;
#endif
/* Token kinds. */
#ifndef YYTOKENTYPE
# define YYTOKENTYPE
enum yytokentype
{
YYEMPTY = -2,
YYEOF = 0, /* "end of file" */
YYerror = 256, /* error */
YYUNDEF = 257, /* "invalid token" */
NULLTOKEN = 258, /* NULLTOKEN */
TRUETOKEN = 259, /* TRUETOKEN */
FALSETOKEN = 260, /* FALSETOKEN */
BREAK = 261, /* BREAK */
CASE = 262, /* CASE */
DEFAULT = 263, /* DEFAULT */
FOR = 264, /* FOR */
NEW = 265, /* NEW */
VAR = 266, /* VAR */
CONSTTOKEN = 267, /* CONSTTOKEN */
CONTINUE = 268, /* CONTINUE */
FUNCTION = 269, /* FUNCTION */
RETURN = 270, /* RETURN */
VOIDTOKEN = 271, /* VOIDTOKEN */
DELETETOKEN = 272, /* DELETETOKEN */
IF = 273, /* IF */
THISTOKEN = 274, /* THISTOKEN */
DO = 275, /* DO */
WHILE = 276, /* WHILE */
INTOKEN = 277, /* INTOKEN */
INSTANCEOF = 278, /* INSTANCEOF */
TYPEOF = 279, /* TYPEOF */
SWITCH = 280, /* SWITCH */
WITH = 281, /* WITH */
RESERVED = 282, /* RESERVED */
THROW = 283, /* THROW */
TRY = 284, /* TRY */
CATCH = 285, /* CATCH */
FINALLY = 286, /* FINALLY */
DEBUGGER = 287, /* DEBUGGER */
IF_WITHOUT_ELSE = 288, /* IF_WITHOUT_ELSE */
ELSE = 289, /* ELSE */
EQEQ = 290, /* EQEQ */
NE = 291, /* NE */
STREQ = 292, /* STREQ */
STRNEQ = 293, /* STRNEQ */
LE = 294, /* LE */
GE = 295, /* GE */
OR = 296, /* OR */
AND = 297, /* AND */
PLUSPLUS = 298, /* PLUSPLUS */
MINUSMINUS = 299, /* MINUSMINUS */
LSHIFT = 300, /* LSHIFT */
RSHIFT = 301, /* RSHIFT */
URSHIFT = 302, /* URSHIFT */
PLUSEQUAL = 303, /* PLUSEQUAL */
MINUSEQUAL = 304, /* MINUSEQUAL */
MULTEQUAL = 305, /* MULTEQUAL */
DIVEQUAL = 306, /* DIVEQUAL */
LSHIFTEQUAL = 307, /* LSHIFTEQUAL */
RSHIFTEQUAL = 308, /* RSHIFTEQUAL */
URSHIFTEQUAL = 309, /* URSHIFTEQUAL */
ANDEQUAL = 310, /* ANDEQUAL */
MODEQUAL = 311, /* MODEQUAL */
XOREQUAL = 312, /* XOREQUAL */
OREQUAL = 313, /* OREQUAL */
OPENBRACE = 314, /* OPENBRACE */
CLOSEBRACE = 315, /* CLOSEBRACE */
NUMBER = 316, /* NUMBER */
IDENT = 317, /* IDENT */
STRING = 318, /* STRING */
AUTOPLUSPLUS = 319, /* AUTOPLUSPLUS */
AUTOMINUSMINUS = 320 /* AUTOMINUSMINUS */
};
typedef enum yytokentype yytoken_kind_t;
#endif
/* Value type. */
#if ! defined YYSTYPE && ! defined YYSTYPE_IS_DECLARED
union YYSTYPE
{
int intValue;
double doubleValue;
const Identifier* ident;
// expression subtrees
ExpressionNodeInfo expressionNode;
FuncDeclNodeInfo funcDeclNode;
PropertyNodeInfo propertyNode;
ArgumentsNodeInfo argumentsNode;
ConstDeclNodeInfo constDeclNode;
CaseBlockNodeInfo caseBlockNode;
CaseClauseNodeInfo caseClauseNode;
FuncExprNodeInfo funcExprNode;
// statement nodes
StatementNodeInfo statementNode;
FunctionBodyNode* functionBodyNode;
ProgramNode* programNode;
SourceElementsInfo sourceElements;
PropertyListInfo propertyList;
ArgumentListInfo argumentList;
VarDeclListInfo varDeclList;
ConstDeclListInfo constDeclList;
ClauseListInfo clauseList;
ElementListInfo elementList;
ParameterListInfo parameterList;
Operator op;
};
typedef union YYSTYPE YYSTYPE;
# define YYSTYPE_IS_TRIVIAL 1
# define YYSTYPE_IS_DECLARED 1
#endif
/* Location type. */
#if ! defined YYLTYPE && ! defined YYLTYPE_IS_DECLARED
typedef struct YYLTYPE YYLTYPE;
struct YYLTYPE
{
int first_line;
int first_column;
int last_line;
int last_column;
};
# define YYLTYPE_IS_DECLARED 1
# define YYLTYPE_IS_TRIVIAL 1
#endif
int jscyyparse (void *globalPtr);
#endif /* !YY_JSCYY_GRAMMAR_HPP_INCLUDED */

View file

@ -1,15 +0,0 @@
// Automatically generated from ../runtime/JSONObject.cpp using ../create_hash_table. DO NOT EDIT!
#include "Lookup.h"
namespace JSC {
static const struct HashTableValue jsonTableValues[3] = {
{ "parse", DontEnum|Function, (intptr_t)JSONProtoFuncParse, (intptr_t)1 },
{ "stringify", DontEnum|Function, (intptr_t)JSONProtoFuncStringify, (intptr_t)1 },
{ 0, 0, 0, 0 }
};
extern const HashTable jsonTable =
{ 4, 3, jsonTableValues, 0 };
} // namespace

View file

@ -1,47 +0,0 @@
// Automatically generated from ../parser/Keywords.table using ../create_hash_table. DO NOT EDIT!
namespace JSC {
static const struct HashTableValue mainTableValues[37] = {
{ "null", 0, (intptr_t)NULLTOKEN, (intptr_t)0 },
{ "true", 0, (intptr_t)TRUETOKEN, (intptr_t)0 },
{ "false", 0, (intptr_t)FALSETOKEN, (intptr_t)0 },
{ "break", 0, (intptr_t)BREAK, (intptr_t)0 },
{ "case", 0, (intptr_t)CASE, (intptr_t)0 },
{ "catch", 0, (intptr_t)CATCH, (intptr_t)0 },
{ "const", 0, (intptr_t)CONSTTOKEN, (intptr_t)0 },
{ "default", 0, (intptr_t)DEFAULT, (intptr_t)0 },
{ "finally", 0, (intptr_t)FINALLY, (intptr_t)0 },
{ "for", 0, (intptr_t)FOR, (intptr_t)0 },
{ "instanceof", 0, (intptr_t)INSTANCEOF, (intptr_t)0 },
{ "new", 0, (intptr_t)NEW, (intptr_t)0 },
{ "var", 0, (intptr_t)VAR, (intptr_t)0 },
{ "continue", 0, (intptr_t)CONTINUE, (intptr_t)0 },
{ "function", 0, (intptr_t)FUNCTION, (intptr_t)0 },
{ "return", 0, (intptr_t)RETURN, (intptr_t)0 },
{ "void", 0, (intptr_t)VOIDTOKEN, (intptr_t)0 },
{ "delete", 0, (intptr_t)DELETETOKEN, (intptr_t)0 },
{ "if", 0, (intptr_t)IF, (intptr_t)0 },
{ "this", 0, (intptr_t)THISTOKEN, (intptr_t)0 },
{ "do", 0, (intptr_t)DO, (intptr_t)0 },
{ "while", 0, (intptr_t)WHILE, (intptr_t)0 },
{ "else", 0, (intptr_t)ELSE, (intptr_t)0 },
{ "in", 0, (intptr_t)INTOKEN, (intptr_t)0 },
{ "switch", 0, (intptr_t)SWITCH, (intptr_t)0 },
{ "throw", 0, (intptr_t)THROW, (intptr_t)0 },
{ "try", 0, (intptr_t)TRY, (intptr_t)0 },
{ "typeof", 0, (intptr_t)TYPEOF, (intptr_t)0 },
{ "with", 0, (intptr_t)WITH, (intptr_t)0 },
{ "debugger", 0, (intptr_t)DEBUGGER, (intptr_t)0 },
{ "class", 0, (intptr_t)RESERVED, (intptr_t)0 },
{ "enum", 0, (intptr_t)RESERVED, (intptr_t)0 },
{ "export", 0, (intptr_t)RESERVED, (intptr_t)0 },
{ "extends", 0, (intptr_t)RESERVED, (intptr_t)0 },
{ "import", 0, (intptr_t)RESERVED, (intptr_t)0 },
{ "super", 0, (intptr_t)RESERVED, (intptr_t)0 },
{ 0, 0, 0, 0 }
};
extern const HashTable mainTable =
{ 133, 127, mainTableValues, 0 };
} // namespace

View file

@ -1,31 +0,0 @@
// Automatically generated from ../runtime/MathObject.cpp using ../create_hash_table. DO NOT EDIT!
#include "Lookup.h"
namespace JSC {
static const struct HashTableValue mathTableValues[19] = {
{ "abs", DontEnum|Function, (intptr_t)mathProtoFuncAbs, (intptr_t)1 },
{ "acos", DontEnum|Function, (intptr_t)mathProtoFuncACos, (intptr_t)1 },
{ "asin", DontEnum|Function, (intptr_t)mathProtoFuncASin, (intptr_t)1 },
{ "atan", DontEnum|Function, (intptr_t)mathProtoFuncATan, (intptr_t)1 },
{ "atan2", DontEnum|Function, (intptr_t)mathProtoFuncATan2, (intptr_t)2 },
{ "ceil", DontEnum|Function, (intptr_t)mathProtoFuncCeil, (intptr_t)1 },
{ "cos", DontEnum|Function, (intptr_t)mathProtoFuncCos, (intptr_t)1 },
{ "exp", DontEnum|Function, (intptr_t)mathProtoFuncExp, (intptr_t)1 },
{ "floor", DontEnum|Function, (intptr_t)mathProtoFuncFloor, (intptr_t)1 },
{ "log", DontEnum|Function, (intptr_t)mathProtoFuncLog, (intptr_t)1 },
{ "max", DontEnum|Function, (intptr_t)mathProtoFuncMax, (intptr_t)2 },
{ "min", DontEnum|Function, (intptr_t)mathProtoFuncMin, (intptr_t)2 },
{ "pow", DontEnum|Function, (intptr_t)mathProtoFuncPow, (intptr_t)2 },
{ "random", DontEnum|Function, (intptr_t)mathProtoFuncRandom, (intptr_t)0 },
{ "round", DontEnum|Function, (intptr_t)mathProtoFuncRound, (intptr_t)1 },
{ "sin", DontEnum|Function, (intptr_t)mathProtoFuncSin, (intptr_t)1 },
{ "sqrt", DontEnum|Function, (intptr_t)mathProtoFuncSqrt, (intptr_t)1 },
{ "tan", DontEnum|Function, (intptr_t)mathProtoFuncTan, (intptr_t)1 },
{ 0, 0, 0, 0 }
};
extern const HashTable mathTable =
{ 67, 63, mathTableValues, 0 };
} // namespace

View file

@ -1,18 +0,0 @@
// Automatically generated from ../runtime/NumberConstructor.cpp using ../create_hash_table. DO NOT EDIT!
#include "Lookup.h"
namespace JSC {
static const struct HashTableValue numberTableValues[6] = {
{ "NaN", DontEnum|DontDelete|ReadOnly, (intptr_t)numberConstructorNaNValue, (intptr_t)0 },
{ "NEGATIVE_INFINITY", DontEnum|DontDelete|ReadOnly, (intptr_t)numberConstructorNegInfinity, (intptr_t)0 },
{ "POSITIVE_INFINITY", DontEnum|DontDelete|ReadOnly, (intptr_t)numberConstructorPosInfinity, (intptr_t)0 },
{ "MAX_VALUE", DontEnum|DontDelete|ReadOnly, (intptr_t)numberConstructorMaxValue, (intptr_t)0 },
{ "MIN_VALUE", DontEnum|DontDelete|ReadOnly, (intptr_t)numberConstructorMinValue, (intptr_t)0 },
{ 0, 0, 0, 0 }
};
extern const HashTable numberTable =
{ 16, 15, numberTableValues, 0 };
} // namespace

View file

@ -1,34 +0,0 @@
// Automatically generated from ../runtime/RegExpConstructor.cpp using ../create_hash_table. DO NOT EDIT!
#include "Lookup.h"
namespace JSC {
static const struct HashTableValue regExpConstructorTableValues[22] = {
{ "input", None, (intptr_t)regExpConstructorInput, (intptr_t)setRegExpConstructorInput },
{ "$_", DontEnum, (intptr_t)regExpConstructorInput, (intptr_t)setRegExpConstructorInput },
{ "multiline", None, (intptr_t)regExpConstructorMultiline, (intptr_t)setRegExpConstructorMultiline },
{ "$*", DontEnum, (intptr_t)regExpConstructorMultiline, (intptr_t)setRegExpConstructorMultiline },
{ "lastMatch", DontDelete|ReadOnly, (intptr_t)regExpConstructorLastMatch, (intptr_t)0 },
{ "$&", DontDelete|ReadOnly|DontEnum, (intptr_t)regExpConstructorLastMatch, (intptr_t)0 },
{ "lastParen", DontDelete|ReadOnly, (intptr_t)regExpConstructorLastParen, (intptr_t)0 },
{ "$+", DontDelete|ReadOnly|DontEnum, (intptr_t)regExpConstructorLastParen, (intptr_t)0 },
{ "leftContext", DontDelete|ReadOnly, (intptr_t)regExpConstructorLeftContext, (intptr_t)0 },
{ "$`", DontDelete|ReadOnly|DontEnum, (intptr_t)regExpConstructorLeftContext, (intptr_t)0 },
{ "rightContext", DontDelete|ReadOnly, (intptr_t)regExpConstructorRightContext, (intptr_t)0 },
{ "$'", DontDelete|ReadOnly|DontEnum, (intptr_t)regExpConstructorRightContext, (intptr_t)0 },
{ "$1", DontDelete|ReadOnly, (intptr_t)regExpConstructorDollar1, (intptr_t)0 },
{ "$2", DontDelete|ReadOnly, (intptr_t)regExpConstructorDollar2, (intptr_t)0 },
{ "$3", DontDelete|ReadOnly, (intptr_t)regExpConstructorDollar3, (intptr_t)0 },
{ "$4", DontDelete|ReadOnly, (intptr_t)regExpConstructorDollar4, (intptr_t)0 },
{ "$5", DontDelete|ReadOnly, (intptr_t)regExpConstructorDollar5, (intptr_t)0 },
{ "$6", DontDelete|ReadOnly, (intptr_t)regExpConstructorDollar6, (intptr_t)0 },
{ "$7", DontDelete|ReadOnly, (intptr_t)regExpConstructorDollar7, (intptr_t)0 },
{ "$8", DontDelete|ReadOnly, (intptr_t)regExpConstructorDollar8, (intptr_t)0 },
{ "$9", DontDelete|ReadOnly, (intptr_t)regExpConstructorDollar9, (intptr_t)0 },
{ 0, 0, 0, 0 }
};
extern const HashTable regExpConstructorTable =
{ 65, 63, regExpConstructorTableValues, 0 };
} // namespace

View file

@ -1,18 +0,0 @@
// Automatically generated from ../runtime/RegExpObject.cpp using ../create_hash_table. DO NOT EDIT!
#include "Lookup.h"
namespace JSC {
static const struct HashTableValue regExpTableValues[6] = {
{ "global", DontDelete|ReadOnly|DontEnum, (intptr_t)regExpObjectGlobal, (intptr_t)0 },
{ "ignoreCase", DontDelete|ReadOnly|DontEnum, (intptr_t)regExpObjectIgnoreCase, (intptr_t)0 },
{ "multiline", DontDelete|ReadOnly|DontEnum, (intptr_t)regExpObjectMultiline, (intptr_t)0 },
{ "source", DontDelete|ReadOnly|DontEnum, (intptr_t)regExpObjectSource, (intptr_t)0 },
{ "lastIndex", DontDelete|DontEnum, (intptr_t)regExpObjectLastIndex, (intptr_t)setRegExpObjectLastIndex },
{ 0, 0, 0, 0 }
};
extern const HashTable regExpTable =
{ 17, 15, regExpTableValues, 0 };
} // namespace

View file

@ -1,35 +0,0 @@
// Automatically generated from ../runtime/StringPrototype.cpp using ../create_hash_table. DO NOT EDIT!
#include "Lookup.h"
namespace JSC {
static const struct HashTableValue stringTableValues[23] = {
{ "toString", DontEnum|Function, (intptr_t)stringProtoFuncToString, (intptr_t)0 },
{ "valueOf", DontEnum|Function, (intptr_t)stringProtoFuncToString, (intptr_t)0 },
{ "charAt", DontEnum|Function, (intptr_t)stringProtoFuncCharAt, (intptr_t)1 },
{ "charCodeAt", DontEnum|Function, (intptr_t)stringProtoFuncCharCodeAt, (intptr_t)1 },
{ "concat", DontEnum|Function, (intptr_t)stringProtoFuncConcat, (intptr_t)1 },
{ "indexOf", DontEnum|Function, (intptr_t)stringProtoFuncIndexOf, (intptr_t)1 },
{ "lastIndexOf", DontEnum|Function, (intptr_t)stringProtoFuncLastIndexOf, (intptr_t)1 },
{ "match", DontEnum|Function, (intptr_t)stringProtoFuncMatch, (intptr_t)1 },
{ "replace", DontEnum|Function, (intptr_t)stringProtoFuncReplace, (intptr_t)2 },
{ "search", DontEnum|Function, (intptr_t)stringProtoFuncSearch, (intptr_t)1 },
{ "slice", DontEnum|Function, (intptr_t)stringProtoFuncSlice, (intptr_t)2 },
{ "split", DontEnum|Function, (intptr_t)stringProtoFuncSplit, (intptr_t)2 },
{ "substr", DontEnum|Function, (intptr_t)stringProtoFuncSubstr, (intptr_t)2 },
{ "substring", DontEnum|Function, (intptr_t)stringProtoFuncSubstring, (intptr_t)2 },
{ "toLowerCase", DontEnum|Function, (intptr_t)stringProtoFuncToLowerCase, (intptr_t)0 },
{ "toUpperCase", DontEnum|Function, (intptr_t)stringProtoFuncToUpperCase, (intptr_t)0 },
{ "localeCompare", DontEnum|Function, (intptr_t)stringProtoFuncLocaleCompare, (intptr_t)1 },
{ "toLocaleLowerCase", DontEnum|Function, (intptr_t)stringProtoFuncToLowerCase, (intptr_t)0 },
{ "toLocaleUpperCase", DontEnum|Function, (intptr_t)stringProtoFuncToUpperCase, (intptr_t)0 },
{ "trim", DontEnum|Function, (intptr_t)stringProtoFuncTrim, (intptr_t)0 },
{ "trimLeft", DontEnum|Function, (intptr_t)stringProtoFuncTrimLeft, (intptr_t)0 },
{ "trimRight", DontEnum|Function, (intptr_t)stringProtoFuncTrimRight, (intptr_t)0 },
{ 0, 0, 0, 0 }
};
extern const HashTable stringTable =
{ 66, 63, stringTableValues, 0 };
} // namespace

View file

@ -1,78 +0,0 @@
/*
* Copyright (C) 2009 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef CachedCall_h
#define CachedCall_h
#include "CallFrameClosure.h"
#include "JSFunction.h"
#include "JSGlobalObject.h"
#include "Interpreter.h"
namespace JSC {
class CachedCall : public Noncopyable {
public:
CachedCall(CallFrame* callFrame, JSFunction* function, int argCount, JSValue* exception)
: m_valid(false)
, m_interpreter(callFrame->interpreter())
, m_exception(exception)
, m_globalObjectScope(callFrame, function->scope().globalObject())
{
Q_ASSERT(!function->isHostFunction());
m_closure = m_interpreter->prepareForRepeatCall(function->jsExecutable(), callFrame, function, argCount, function->scope().node(), exception);
m_valid = !*exception;
}
JSValue call()
{
Q_ASSERT(m_valid);
return m_interpreter->execute(m_closure, m_exception);
}
void setThis(JSValue v) { m_closure.setArgument(0, v); }
void setArgument(int n, JSValue v) { m_closure.setArgument(n + 1, v); }
CallFrame* newCallFrame(ExecState* exec)
{
CallFrame* callFrame = m_closure.newCallFrame;
callFrame->setScopeChain(exec->scopeChain());
return callFrame;
}
~CachedCall()
{
if (m_valid)
m_interpreter->endRepeatCall(m_closure);
}
private:
bool m_valid;
Interpreter* m_interpreter;
JSValue* m_exception;
DynamicGlobalObjectScope m_globalObjectScope;
CallFrameClosure m_closure;
};
}
#endif

View file

@ -1,52 +0,0 @@
/*
* Copyright (C) 2008 Apple Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "Platform.h"
#include "CallFrame.h"
#include "CodeBlock.h"
#include "Interpreter.h"
namespace JSC {
JSValue CallFrame::thisValue()
{
return this[codeBlock()->thisRegister()].jsValue();
}
#ifndef QT_NO_DEBUG
void CallFrame::dumpCaller()
{
int signedLineNumber;
intptr_t sourceID;
UString urlString;
JSValue function;
interpreter()->retrieveLastCaller(this, signedLineNumber, sourceID, urlString, function);
printf("Callpoint => %s:%d\n", urlString.ascii(), signedLineNumber);
}
#endif
}

View file

@ -1,155 +0,0 @@
/*
* Copyright (C) 1999-2001 Harri Porten (porten@kde.org)
* Copyright (C) 2001 Peter Kelly (pmk@post.com)
* Copyright (C) 2003, 2007, 2008 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 CallFrame_h
#define CallFrame_h
#include "JSGlobalData.h"
#include "RegisterFile.h"
#include "ScopeChain.h"
namespace JSC {
class Arguments;
class JSActivation;
class Interpreter;
// Represents the current state of script execution.
// Passed as the first argument to most functions.
class ExecState : private Register {
public:
JSObject* callee() const { return this[RegisterFile::Callee].object(); }
CodeBlock* codeBlock() const { return this[RegisterFile::CodeBlock].Register::codeBlock(); }
ScopeChainNode* scopeChain() const
{
Q_ASSERT(this[RegisterFile::ScopeChain].Register::scopeChain());
return this[RegisterFile::ScopeChain].Register::scopeChain();
}
int argumentCount() const { return this[RegisterFile::ArgumentCount].i(); }
JSValue thisValue();
// Global object in which execution began.
JSGlobalObject* dynamicGlobalObject();
// Global object in which the currently executing code was defined.
// Differs from dynamicGlobalObject() during function calls across web browser frames.
JSGlobalObject* lexicalGlobalObject() const
{
return scopeChain()->globalObject;
}
// Differs from lexicalGlobalObject because this will have DOM window shell rather than
// the actual DOM window, which can't be "this" for security reasons.
JSObject* globalThisValue() const
{
return scopeChain()->globalThis;
}
// FIXME: Elsewhere, we use JSGlobalData* rather than JSGlobalData&.
// We should make this more uniform and either use a reference everywhere
// or a pointer everywhere.
JSGlobalData& globalData() const
{
Q_ASSERT(scopeChain()->globalData);
return *scopeChain()->globalData;
}
// Convenience functions for access to global data.
// It takes a few memory references to get from a call frame to the global data
// pointer, so these are inefficient, and should be used sparingly in new code.
// But they're used in many places in legacy code, so they're not going away any time soon.
void setException(JSValue exception) { globalData().exception = exception; }
void clearException() { globalData().exception = JSValue(); }
JSValue exception() const { return globalData().exception; }
JSValue* exceptionSlot() { return &globalData().exception; }
bool hadException() const { return globalData().exception; }
const CommonIdentifiers& propertyNames() const { return *globalData().propertyNames; }
const MarkedArgumentBuffer& emptyList() const { return *globalData().emptyList; }
Interpreter* interpreter() { return globalData().interpreter; }
Heap* heap() { return &globalData().heap; }
#ifndef QT_NO_DEBUG
void dumpCaller();
#endif
static const HashTable* arrayTable(CallFrame* callFrame) { return callFrame->globalData().arrayTable; }
static const HashTable* dateTable(CallFrame* callFrame) { return callFrame->globalData().dateTable; }
static const HashTable* jsonTable(CallFrame* callFrame) { return callFrame->globalData().jsonTable; }
static const HashTable* mathTable(CallFrame* callFrame) { return callFrame->globalData().mathTable; }
static const HashTable* numberTable(CallFrame* callFrame) { return callFrame->globalData().numberTable; }
static const HashTable* regExpTable(CallFrame* callFrame) { return callFrame->globalData().regExpTable; }
static const HashTable* regExpConstructorTable(CallFrame* callFrame) { return callFrame->globalData().regExpConstructorTable; }
static const HashTable* stringTable(CallFrame* callFrame) { return callFrame->globalData().stringTable; }
static CallFrame* create(Register* callFrameBase) { return static_cast<CallFrame*>(callFrameBase); }
Register* registers() { return this; }
CallFrame& operator=(const Register& r) { *static_cast<Register*>(this) = r; return *this; }
CallFrame* callerFrame() const { return this[RegisterFile::CallerFrame].callFrame(); }
Arguments* optionalCalleeArguments() const { return this[RegisterFile::OptionalCalleeArguments].arguments(); }
Instruction* returnPC() const { return this[RegisterFile::ReturnPC].vPC(); }
void setCalleeArguments(JSValue arguments) { static_cast<Register*>(this)[RegisterFile::OptionalCalleeArguments] = arguments; }
void setCallerFrame(CallFrame* callerFrame) { static_cast<Register*>(this)[RegisterFile::CallerFrame] = callerFrame; }
void setScopeChain(ScopeChainNode* scopeChain) { static_cast<Register*>(this)[RegisterFile::ScopeChain] = scopeChain; }
ALWAYS_INLINE void init(CodeBlock* codeBlock, Instruction* vPC, ScopeChainNode* scopeChain,
CallFrame* callerFrame, int returnValueRegister, int argc, JSObject* callee)
{
Q_ASSERT(callerFrame); // Use noCaller() rather than 0 for the outer host call frame caller.
setCodeBlock(codeBlock);
setScopeChain(scopeChain);
setCallerFrame(callerFrame);
static_cast<Register*>(this)[RegisterFile::ReturnPC] = vPC; // This is either an Instruction* or a pointer into JIT generated code stored as an Instruction*.
static_cast<Register*>(this)[RegisterFile::ReturnValueRegister] = Register::withInt(returnValueRegister);
setArgumentCount(argc); // original argument count (for the sake of the "arguments" object)
setCallee(callee);
setCalleeArguments(JSValue());
}
// Read a register from the codeframe (or constant from the CodeBlock).
inline Register& r(int);
static CallFrame* noCaller() { return reinterpret_cast<CallFrame*>(HostCallFrameFlag); }
int returnValueRegister() const { return this[RegisterFile::ReturnValueRegister].i(); }
bool hasHostCallFrameFlag() const { return reinterpret_cast<intptr_t>(this) & HostCallFrameFlag; }
CallFrame* addHostCallFrameFlag() const { return reinterpret_cast<CallFrame*>(reinterpret_cast<intptr_t>(this) | HostCallFrameFlag); }
CallFrame* removeHostCallFrameFlag() { return reinterpret_cast<CallFrame*>(reinterpret_cast<intptr_t>(this) & ~HostCallFrameFlag); }
private:
void setArgumentCount(int count) { static_cast<Register*>(this)[RegisterFile::ArgumentCount] = Register::withInt(count); }
void setCallee(JSObject* callee) { static_cast<Register*>(this)[RegisterFile::Callee] = callee; }
void setCodeBlock(CodeBlock* codeBlock) { static_cast<Register*>(this)[RegisterFile::CodeBlock] = codeBlock; }
static const intptr_t HostCallFrameFlag = 1;
ExecState();
~ExecState();
};
} // namespace JSC
#endif // CallFrame_h

View file

@ -1,60 +0,0 @@
/*
* Copyright (C) 2009 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef CallFrameClosure_h
#define CallFrameClosure_h
namespace JSC {
struct CallFrameClosure {
CallFrame* oldCallFrame;
CallFrame* newCallFrame;
JSFunction* function;
FunctionExecutable* functionExecutable;
JSGlobalData* globalData;
Register* oldEnd;
ScopeChainNode* scopeChain;
int expectedParams;
int providedParams;
void setArgument(int arg, JSValue value)
{
if (arg < expectedParams)
newCallFrame[arg - RegisterFile::CallFrameHeaderSize - expectedParams] = value;
else
newCallFrame[arg - RegisterFile::CallFrameHeaderSize - expectedParams - providedParams] = value;
}
void resetCallFrame()
{
newCallFrame->setScopeChain(scopeChain);
newCallFrame->setCalleeArguments(JSValue());
for (int i = providedParams; i < expectedParams; ++i)
newCallFrame[i - RegisterFile::CallFrameHeaderSize - expectedParams] = jsUndefined();
}
};
}
#endif

File diff suppressed because it is too large Load diff

View file

@ -1,142 +0,0 @@
/*
* Copyright (C) 2008 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef Interpreter_h
#define Interpreter_h
#include "ArgList.h"
#include "FastAllocBase.h"
#include "JSCell.h"
#include "JSValue.h"
#include "JSObject.h"
#include "Opcode.h"
#include "RegisterFile.h"
#include <wtf/HashMap.h>
namespace JSC {
class CodeBlock;
class EvalExecutable;
class FunctionExecutable;
class InternalFunction;
class JSFunction;
class JSGlobalObject;
class ProgramExecutable;
class Register;
class ScopeChainNode;
class SamplingTool;
struct CallFrameClosure;
struct HandlerInfo;
struct Instruction;
enum DebugHookID {
WillExecuteProgram,
DidExecuteProgram,
DidEnterCallFrame,
DidReachBreakpoint,
WillLeaveCallFrame,
WillExecuteStatement
};
enum { MaxMainThreadReentryDepth = 256, MaxSecondaryThreadReentryDepth = 32 };
class Interpreter : public FastAllocBase {
friend class CachedCall;
public:
Interpreter();
RegisterFile& registerFile() { return m_registerFile; }
inline bool isOpcode(OpcodeID opcode) { return opcode >= 0 && opcode <= op_end; };
JSValue execute(ProgramExecutable*, CallFrame*, ScopeChainNode*, JSObject* thisObj, JSValue* exception);
JSValue execute(FunctionExecutable*, CallFrame*, JSFunction*, JSObject* thisObj, const ArgList& args, ScopeChainNode*, JSValue* exception);
JSValue execute(EvalExecutable* evalNode, CallFrame* exec, JSObject* thisObj, ScopeChainNode* scopeChain, JSValue* exception);
JSValue retrieveArguments(CallFrame*, JSFunction*) const;
JSValue retrieveCaller(CallFrame*, InternalFunction*) const;
void retrieveLastCaller(CallFrame*, int& lineNumber, intptr_t& sourceID, UString& sourceURL, JSValue& function) const;
void getArgumentsData(CallFrame*, JSFunction*&, ptrdiff_t& firstParameterIndex, Register*& argv, int& argc);
SamplingTool* sampler() { return m_sampler.get(); }
NEVER_INLINE JSValue callEval(CallFrame*, RegisterFile*, Register* argv, int argc, int registerOffset, JSValue& exceptionValue);
NEVER_INLINE HandlerInfo* throwException(CallFrame*&, JSValue&, unsigned bytecodeOffset, bool);
NEVER_INLINE void debug(CallFrame*, DebugHookID, int firstLine, int lastLine);
void dumpSampleData(ExecState* exec);
void startSampling();
void stopSampling();
private:
enum ExecutionFlag { Normal, InitializeAndReturn };
CallFrameClosure prepareForRepeatCall(FunctionExecutable*, CallFrame*, JSFunction*, int argCount, ScopeChainNode*, JSValue* exception);
void endRepeatCall(CallFrameClosure&);
JSValue execute(CallFrameClosure&, JSValue* exception);
JSValue execute(EvalExecutable*, CallFrame*, JSObject* thisObject, int globalRegisterOffset, ScopeChainNode*, JSValue* exception);
NEVER_INLINE bool resolve(CallFrame*, Instruction*, JSValue& exceptionValue);
NEVER_INLINE bool resolveSkip(CallFrame*, Instruction*, JSValue& exceptionValue);
NEVER_INLINE bool resolveGlobal(CallFrame*, Instruction*, JSValue& exceptionValue);
NEVER_INLINE void resolveBase(CallFrame*, Instruction* vPC);
NEVER_INLINE bool resolveBaseAndProperty(CallFrame*, Instruction*, JSValue& exceptionValue);
NEVER_INLINE ScopeChainNode* createExceptionScope(CallFrame*, const Instruction* vPC);
void tryCacheGetByID(CallFrame*, CodeBlock*, Instruction*, JSValue baseValue, const Identifier& propertyName, const PropertySlot&);
void uncacheGetByID(CodeBlock*, Instruction* vPC);
void tryCachePutByID(CallFrame*, CodeBlock*, Instruction*, JSValue baseValue, const PutPropertySlot&);
void uncachePutByID(CodeBlock*, Instruction* vPC);
NEVER_INLINE bool unwindCallFrame(CallFrame*&, JSValue, unsigned& bytecodeOffset, CodeBlock*&);
static ALWAYS_INLINE CallFrame* slideRegisterWindowForCall(CodeBlock*, RegisterFile*, CallFrame*, size_t registerOffset, int argc);
static CallFrame* findFunctionCallFrame(CallFrame*, InternalFunction*);
JSValue privateExecute(ExecutionFlag, RegisterFile*, CallFrame*, JSValue* exception);
void dumpCallFrame(CallFrame*);
void dumpRegisters(CallFrame*);
bool isCallBytecode(OpcodeID opcode) { return opcode == op_call || opcode == op_construct || opcode == op_call_eval; }
void enableSampler();
int m_sampleEntryDepth;
OwnPtr<SamplingTool> m_sampler;
int m_reentryDepth;
RegisterFile m_registerFile;
};
} // namespace JSC
#endif // Interpreter_h

View file

@ -1,219 +0,0 @@
/*
* Copyright (C) 2008, 2009 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef Register_h
#define Register_h
#include "JSValue.h"
#include <wtf/Assertions.h>
#include <wtf/FastAllocBase.h>
#include <wtf/VectorTraits.h>
namespace JSC {
class Arguments;
class CodeBlock;
class ExecState;
class JSActivation;
class JSPropertyNameIterator;
class ScopeChainNode;
struct Instruction;
typedef ExecState CallFrame;
class Register : public WTF::FastAllocBase {
public:
Register();
Register(const JSValue&);
Register& operator=(const JSValue&);
JSValue jsValue() const;
Register& operator=(JSActivation*);
Register& operator=(CallFrame*);
Register& operator=(CodeBlock*);
Register& operator=(JSObject*);
Register& operator=(JSPropertyNameIterator*);
Register& operator=(ScopeChainNode*);
Register& operator=(Instruction*);
int32_t i() const;
JSActivation* activation() const;
Arguments* arguments() const;
CallFrame* callFrame() const;
CodeBlock* codeBlock() const;
JSObject* object() const;
JSPropertyNameIterator* propertyNameIterator() const;
ScopeChainNode* scopeChain() const;
Instruction* vPC() const;
static Register withInt(int32_t i)
{
Register r;
r.u.i = i;
return r;
}
private:
union {
int32_t i;
EncodedJSValue value;
JSActivation* activation;
CallFrame* callFrame;
CodeBlock* codeBlock;
JSObject* object;
JSPropertyNameIterator* propertyNameIterator;
ScopeChainNode* scopeChain;
Instruction* vPC;
} u;
};
ALWAYS_INLINE Register::Register()
{
#ifndef QT_NO_DEBUG
*this = JSValue();
#endif
}
ALWAYS_INLINE Register::Register(const JSValue& v)
{
#if ENABLE(JSC_ZOMBIES)
Q_ASSERT(!v.isZombie());
#endif
u.value = JSValue::encode(v);
}
ALWAYS_INLINE Register& Register::operator=(const JSValue& v)
{
#if ENABLE(JSC_ZOMBIES)
Q_ASSERT(!v.isZombie());
#endif
u.value = JSValue::encode(v);
return *this;
}
ALWAYS_INLINE JSValue Register::jsValue() const
{
return JSValue::decode(u.value);
}
// Interpreter functions
ALWAYS_INLINE Register& Register::operator=(JSActivation* activation)
{
u.activation = activation;
return *this;
}
ALWAYS_INLINE Register& Register::operator=(CallFrame* callFrame)
{
u.callFrame = callFrame;
return *this;
}
ALWAYS_INLINE Register& Register::operator=(CodeBlock* codeBlock)
{
u.codeBlock = codeBlock;
return *this;
}
ALWAYS_INLINE Register& Register::operator=(JSObject* object)
{
u.object = object;
return *this;
}
ALWAYS_INLINE Register& Register::operator=(Instruction* vPC)
{
u.vPC = vPC;
return *this;
}
ALWAYS_INLINE Register& Register::operator=(ScopeChainNode* scopeChain)
{
u.scopeChain = scopeChain;
return *this;
}
ALWAYS_INLINE Register& Register::operator=(JSPropertyNameIterator* propertyNameIterator)
{
u.propertyNameIterator = propertyNameIterator;
return *this;
}
ALWAYS_INLINE int32_t Register::i() const
{
return u.i;
}
ALWAYS_INLINE JSActivation* Register::activation() const
{
return u.activation;
}
ALWAYS_INLINE CallFrame* Register::callFrame() const
{
return u.callFrame;
}
ALWAYS_INLINE CodeBlock* Register::codeBlock() const
{
return u.codeBlock;
}
ALWAYS_INLINE JSObject* Register::object() const
{
return u.object;
}
ALWAYS_INLINE JSPropertyNameIterator* Register::propertyNameIterator() const
{
return u.propertyNameIterator;
}
ALWAYS_INLINE ScopeChainNode* Register::scopeChain() const
{
return u.scopeChain;
}
ALWAYS_INLINE Instruction* Register::vPC() const
{
return u.vPC;
}
} // namespace JSC
namespace WTF {
template<> struct VectorTraits<JSC::Register> : VectorTraitsBase<true, JSC::Register> { };
} // namespace WTF
#endif // Register_h

View file

@ -1,48 +0,0 @@
/*
* Copyright (C) 2008 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "Platform.h"
#include "RegisterFile.h"
namespace JSC {
RegisterFile::~RegisterFile()
{
::munmap(reinterpret_cast<char*>(m_buffer), ((m_max - m_start) + m_maxGlobals) * sizeof(Register));
}
void RegisterFile::releaseExcessCapacity()
{
// Hurd does not have MAD_FREE
#if defined(QT_HAVE_MADVISE) && defined(MADV_FREE)
while (::madvise(m_start, (m_max - m_start) * sizeof(Register), MADV_FREE) == -1 && errno == EAGAIN) { }
#endif
m_maxUsed = m_start;
}
} // namespace JSC

View file

@ -1,208 +0,0 @@
/*
* Copyright (C) 2008, 2009 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef RegisterFile_h
#define RegisterFile_h
#include "Collector.h"
#include "Register.h"
#include <wtf/Noncopyable.h>
#include <stdio.h>
#include <errno.h>
#include <sys/mman.h>
#include <qplatformdefs.h>
namespace JSC {
/*
A register file is a stack of register frames. We represent a register
frame by its offset from "base", the logical first entry in the register
file. The bottom-most register frame's offset from base is 0.
In a program where function "a" calls function "b" (global code -> a -> b),
the register file might look like this:
| global frame | call frame | call frame | spare capacity |
-----------------------------------------------------------------------------------------------------
| 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | | | | | | <-- index in buffer
-----------------------------------------------------------------------------------------------------
| -3 | -2 | -1 | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | | | | | | <-- index relative to base
-----------------------------------------------------------------------------------------------------
| <-globals | temps-> | <-vars | temps-> | <-vars |
^ ^ ^ ^
| | | |
buffer base (frame 0) frame 1 frame 2
Since all variables, including globals, are accessed by negative offsets
from their register frame pointers, to keep old global offsets correct, new
globals must appear at the beginning of the register file, shifting base
to the right.
If we added one global variable to the register file depicted above, it
would look like this:
| global frame |< >
-------------------------------> <
| 0 | 1 | 2 | 3 | 4 | 5 |< >snip< > <-- index in buffer
-------------------------------> <
| -4 | -3 | -2 | -1 | 0 | 1 |< > <-- index relative to base
-------------------------------> <
| <-globals | temps-> |
^ ^
| |
buffer base (frame 0)
As you can see, global offsets relative to base have stayed constant,
but base itself has moved. To keep up with possible changes to base,
clients keep an indirect pointer, so their calculations update
automatically when base changes.
For client simplicity, the RegisterFile measures size and capacity from
"base", not "buffer".
*/
class JSGlobalObject;
class RegisterFile : public Noncopyable {
public:
enum CallFrameHeaderEntry {
CallFrameHeaderSize = 8,
CodeBlock = -8,
ScopeChain = -7,
CallerFrame = -6,
ReturnPC = -5, // This is either an Instruction* or a pointer into JIT generated code stored as an Instruction*.
ReturnValueRegister = -4,
ArgumentCount = -3,
Callee = -2,
OptionalCalleeArguments = -1
};
enum { ProgramCodeThisRegister = -CallFrameHeaderSize - 1 };
enum { ArgumentsRegister = 0 };
static const size_t defaultCapacity = 524288;
static const size_t defaultMaxGlobals = 8192;
static const size_t commitSize = 1 << 14;
// Allow 8k of excess registers before we start trying to reap the registerfile
static const ptrdiff_t maxExcessCapacity = 8 * 1024;
RegisterFile(size_t capacity = defaultCapacity, size_t maxGlobals = defaultMaxGlobals);
~RegisterFile();
Register* start() const { return m_start; }
Register* end() const { return m_end; }
size_t size() const { return m_end - m_start; }
void setGlobalObject(JSGlobalObject* globalObject) { m_globalObject = globalObject; }
JSGlobalObject* globalObject() { return m_globalObject; }
bool grow(Register* newEnd);
void shrink(Register* newEnd);
void setNumGlobals(size_t numGlobals) { m_numGlobals = numGlobals; }
int numGlobals() const { return m_numGlobals; }
size_t maxGlobals() const { return m_maxGlobals; }
Register* lastGlobal() const { return m_start - m_numGlobals; }
void markGlobals(MarkStack& markStack, Heap* heap) { heap->markConservatively(markStack, lastGlobal(), m_start); }
void markCallFrames(MarkStack& markStack, Heap* heap) { heap->markConservatively(markStack, m_start, m_end); }
private:
void releaseExcessCapacity();
size_t m_numGlobals;
const size_t m_maxGlobals;
Register* m_start;
Register* m_end;
Register* m_max;
Register* m_buffer;
Register* m_maxUsed;
JSGlobalObject* m_globalObject; // The global object whose vars are currently stored in the register file.
};
// FIXME: Add a generic getpagesize() to WTF, then move this function to WTF as well.
// This is still a hack that should be fixed later. We know that a Symbian page size is 4K.
inline bool isPageAligned(size_t size) { return size && !(size % (8 * 1024)); }
inline RegisterFile::RegisterFile(size_t capacity, size_t maxGlobals)
: m_numGlobals(0)
, m_maxGlobals(maxGlobals)
, m_start(0)
, m_end(0)
, m_max(0)
, m_buffer(0)
, m_globalObject(0)
{
// Verify that our values will play nice with mmap.
Q_ASSERT(isPageAligned(maxGlobals));
Q_ASSERT(isPageAligned(capacity));
size_t bufferLength = (capacity + maxGlobals) * sizeof(Register);
m_buffer = reinterpret_cast<Register*>(QT_MMAP(0, bufferLength, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANON, -1, 0));
if (m_buffer == MAP_FAILED) {
fprintf(stderr, "Could not allocate register file: %d\n", errno);
CRASH();
}
m_start = m_buffer + maxGlobals;
m_end = m_start;
m_maxUsed = m_end;
m_max = m_start + capacity;
}
inline void RegisterFile::shrink(Register* newEnd)
{
if (newEnd >= m_end)
return;
m_end = newEnd;
if (m_end == m_start && (m_maxUsed - m_start) > maxExcessCapacity) {
releaseExcessCapacity();
}
}
inline bool RegisterFile::grow(Register* newEnd)
{
if (newEnd < m_end)
return true;
if (newEnd > m_max)
return false;
if (newEnd > m_maxUsed)
m_maxUsed = newEnd;
m_end = newEnd;
return true;
}
} // namespace JSC
#endif // RegisterFile_h

View file

@ -1,8 +0,0 @@
#!/bin/sh
rm -rf generated
mkdir generated
cd generated
make -f ../DerivedSources.make JavaScriptCore=.. V=1
cd ..

File diff suppressed because it is too large Load diff

View file

@ -1,72 +0,0 @@
# main keywords
@begin mainTable 41
# types
null NULLTOKEN
true TRUETOKEN
false FALSETOKEN
# keywords
break BREAK
case CASE
catch CATCH
const CONSTTOKEN
default DEFAULT
finally FINALLY
for FOR
instanceof INSTANCEOF
new NEW
var VAR
continue CONTINUE
function FUNCTION
return RETURN
void VOIDTOKEN
delete DELETETOKEN
if IF
this THISTOKEN
do DO
while WHILE
else ELSE
in INTOKEN
switch SWITCH
throw THROW
try TRY
typeof TYPEOF
with WITH
debugger DEBUGGER
# reserved for future use
class RESERVED
enum RESERVED
export RESERVED
extends RESERVED
import RESERVED
super RESERVED
# these words are reserved for future use in the ECMA spec, but not in WinIE
# (see http://bugs.webkit.org/show_bug.cgi?id=6179)
# abstract RESERVED
# boolean RESERVED
# byte RESERVED
# char RESERVED
# double RESERVED
# final RESERVED
# float RESERVED
# goto RESERVED
# implements RESERVED
# int RESERVED
# interface RESERVED
# long RESERVED
# native RESERVED
# package RESERVED
# private RESERVED
# protected RESERVED
# public RESERVED
# short RESERVED
# static RESERVED
# synchronized RESERVED
# throws RESERVED
# transient RESERVED
# volatile RESERVED
@end

File diff suppressed because it is too large Load diff

View file

@ -1,144 +0,0 @@
/*
* Copyright (C) 1999-2000 Harri Porten (porten@kde.org)
* Copyright (C) 2002, 2003, 2004, 2005, 2006, 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 Lexer_h
#define Lexer_h
#include "Lookup.h"
#include "ParserArena.h"
#include "SourceCode.h"
#include <wtf/ASCIICType.h>
#include <wtf/Vector.h>
#include <wtf/unicode/Unicode.h>
namespace JSC {
class RegExp;
class Lexer : public Noncopyable {
public:
// Character manipulation functions.
static bool isWhiteSpace(int character);
static bool isLineTerminator(int character);
static unsigned char convertHex(int c1, int c2);
static UChar convertUnicode(int c1, int c2, int c3, int c4);
// Functions to set up parsing.
void setCode(const SourceCode&, ParserArena&);
void setIsReparsing() { m_isReparsing = true; }
// Functions for the parser itself.
int lex(void* lvalp, void* llocp);
int lineNumber() const { return m_lineNumber; }
bool prevTerminator() const { return m_terminator; }
SourceCode sourceCode(int openBrace, int closeBrace, int firstLine);
bool scanRegExp(const Identifier*& pattern, const Identifier*& flags, UChar patternPrefix = 0);
bool skipRegExp();
// Functions for use after parsing.
bool sawError() const { return m_error; }
void clear();
private:
friend class JSGlobalData;
Lexer(JSGlobalData*);
~Lexer();
void shift1();
void shift2();
void shift3();
void shift4();
void shiftLineTerminator();
void record8(int);
void record16(int);
void record16(UChar);
int currentOffset() const;
const UChar* currentCharacter() const;
const Identifier* makeIdentifier(const UChar* characters, size_t length);
bool lastTokenWasRestrKeyword() const;
static const size_t initialReadBufferCapacity = 32;
int m_lineNumber;
Vector<char> m_buffer8;
Vector<UChar> m_buffer16;
bool m_terminator;
bool m_delimited; // encountered delimiter like "'" and "}" on last run
int m_lastToken;
const SourceCode* m_source;
const UChar* m_code;
const UChar* m_codeStart;
const UChar* m_codeEnd;
bool m_isReparsing;
bool m_atLineStart;
bool m_error;
// current and following unicode characters (int to allow for -1 for end-of-file marker)
int m_current;
int m_next1;
int m_next2;
int m_next3;
IdentifierArena* m_arena;
JSGlobalData* m_globalData;
const HashTable m_keywordTable;
Vector<UChar> m_codeWithoutBOMs;
};
inline bool Lexer::isWhiteSpace(int ch)
{
return isASCII(ch) ? (ch == ' ' || ch == '\t' || ch == 0xB || ch == 0xC) : WTF::Unicode::isSeparatorSpace(ch);
}
inline bool Lexer::isLineTerminator(int ch)
{
return ch == '\r' || ch == '\n' || (ch & ~1) == 0x2028;
}
inline unsigned char Lexer::convertHex(int c1, int c2)
{
return (toASCIIHexValue(c1) << 4) | toASCIIHexValue(c2);
}
inline UChar Lexer::convertUnicode(int c1, int c2, int c3, int c4)
{
return (convertHex(c1, c2) << 8) | convertHex(c3, c4);
}
// A bridge for yacc from the C world to the C++ world.
inline int jscyylex(void* lvalp, void* llocp, void* globalData)
{
return static_cast<JSGlobalData*>(globalData)->lexer->lex(lvalp, llocp);
}
} // namespace JSC
#endif // Lexer_h

View file

@ -1,895 +0,0 @@
/*
* Copyright (C) 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 NodeConstructors_h
#define NodeConstructors_h
#include "Nodes.h"
#include "Lexer.h"
#include "Parser.h"
namespace JSC {
inline ParserArenaRefCounted::ParserArenaRefCounted(JSGlobalData* globalData)
{
globalData->parser->arena().derefWithArena(adoptRef(this));
}
inline Node::Node(JSGlobalData* globalData)
: m_line(globalData->lexer->lineNumber())
{
}
inline ExpressionNode::ExpressionNode(JSGlobalData* globalData, ResultType resultType)
: Node(globalData)
, m_resultType(resultType)
{
}
inline StatementNode::StatementNode(JSGlobalData* globalData)
: Node(globalData)
, m_lastLine(-1)
{
}
inline NullNode::NullNode(JSGlobalData* globalData)
: ExpressionNode(globalData, ResultType::nullType())
{
}
inline BooleanNode::BooleanNode(JSGlobalData* globalData, bool value)
: ExpressionNode(globalData, ResultType::booleanType())
, m_value(value)
{
}
inline NumberNode::NumberNode(JSGlobalData* globalData, double value)
: ExpressionNode(globalData, ResultType::numberType())
, m_value(value)
{
}
inline StringNode::StringNode(JSGlobalData* globalData, const Identifier& value)
: ExpressionNode(globalData, ResultType::stringType())
, m_value(value)
{
}
inline RegExpNode::RegExpNode(JSGlobalData* globalData, const Identifier& pattern, const Identifier& flags)
: ExpressionNode(globalData)
, m_pattern(pattern)
, m_flags(flags)
{
}
inline ThisNode::ThisNode(JSGlobalData* globalData)
: ExpressionNode(globalData)
{
}
inline ResolveNode::ResolveNode(JSGlobalData* globalData, const Identifier& ident, int startOffset)
: ExpressionNode(globalData)
, m_ident(ident)
, m_startOffset(startOffset)
{
}
inline ElementNode::ElementNode(JSGlobalData*, int elision, ExpressionNode* node)
: m_next(0)
, m_elision(elision)
, m_node(node)
{
}
inline ElementNode::ElementNode(JSGlobalData*, ElementNode* l, int elision, ExpressionNode* node)
: m_next(0)
, m_elision(elision)
, m_node(node)
{
l->m_next = this;
}
inline ArrayNode::ArrayNode(JSGlobalData* globalData, int elision)
: ExpressionNode(globalData)
, m_element(0)
, m_elision(elision)
, m_optional(true)
{
}
inline ArrayNode::ArrayNode(JSGlobalData* globalData, ElementNode* element)
: ExpressionNode(globalData)
, m_element(element)
, m_elision(0)
, m_optional(false)
{
}
inline ArrayNode::ArrayNode(JSGlobalData* globalData, int elision, ElementNode* element)
: ExpressionNode(globalData)
, m_element(element)
, m_elision(elision)
, m_optional(true)
{
}
inline PropertyNode::PropertyNode(JSGlobalData*, const Identifier& name, ExpressionNode* assign, Type type)
: m_name(name)
, m_assign(assign)
, m_type(type)
{
}
inline PropertyNode::PropertyNode(JSGlobalData* globalData, double name, ExpressionNode* assign, Type type)
: m_name(globalData->parser->arena().identifierArena().makeNumericIdentifier(globalData, name))
, m_assign(assign)
, m_type(type)
{
}
inline PropertyListNode::PropertyListNode(JSGlobalData* globalData, PropertyNode* node)
: Node(globalData)
, m_node(node)
, m_next(0)
{
}
inline PropertyListNode::PropertyListNode(JSGlobalData* globalData, PropertyNode* node, PropertyListNode* list)
: Node(globalData)
, m_node(node)
, m_next(0)
{
list->m_next = this;
}
inline ObjectLiteralNode::ObjectLiteralNode(JSGlobalData* globalData)
: ExpressionNode(globalData)
, m_list(0)
{
}
inline ObjectLiteralNode::ObjectLiteralNode(JSGlobalData* globalData, PropertyListNode* list)
: ExpressionNode(globalData)
, m_list(list)
{
}
inline BracketAccessorNode::BracketAccessorNode(JSGlobalData* globalData, ExpressionNode* base, ExpressionNode* subscript, bool subscriptHasAssignments)
: ExpressionNode(globalData)
, m_base(base)
, m_subscript(subscript)
, m_subscriptHasAssignments(subscriptHasAssignments)
{
}
inline DotAccessorNode::DotAccessorNode(JSGlobalData* globalData, ExpressionNode* base, const Identifier& ident)
: ExpressionNode(globalData)
, m_base(base)
, m_ident(ident)
{
}
inline ArgumentListNode::ArgumentListNode(JSGlobalData* globalData, ExpressionNode* expr)
: Node(globalData)
, m_next(0)
, m_expr(expr)
{
}
inline ArgumentListNode::ArgumentListNode(JSGlobalData* globalData, ArgumentListNode* listNode, ExpressionNode* expr)
: Node(globalData)
, m_next(0)
, m_expr(expr)
{
listNode->m_next = this;
}
inline ArgumentsNode::ArgumentsNode(JSGlobalData*)
: m_listNode(0)
{
}
inline ArgumentsNode::ArgumentsNode(JSGlobalData*, ArgumentListNode* listNode)
: m_listNode(listNode)
{
}
inline NewExprNode::NewExprNode(JSGlobalData* globalData, ExpressionNode* expr)
: ExpressionNode(globalData)
, m_expr(expr)
, m_args(0)
{
}
inline NewExprNode::NewExprNode(JSGlobalData* globalData, ExpressionNode* expr, ArgumentsNode* args)
: ExpressionNode(globalData)
, m_expr(expr)
, m_args(args)
{
}
inline EvalFunctionCallNode::EvalFunctionCallNode(JSGlobalData* globalData, ArgumentsNode* args, unsigned divot, unsigned startOffset, unsigned endOffset)
: ExpressionNode(globalData)
, ThrowableExpressionData(divot, startOffset, endOffset)
, m_args(args)
{
}
inline FunctionCallValueNode::FunctionCallValueNode(JSGlobalData* globalData, ExpressionNode* expr, ArgumentsNode* args, unsigned divot, unsigned startOffset, unsigned endOffset)
: ExpressionNode(globalData)
, ThrowableExpressionData(divot, startOffset, endOffset)
, m_expr(expr)
, m_args(args)
{
}
inline FunctionCallResolveNode::FunctionCallResolveNode(JSGlobalData* globalData, const Identifier& ident, ArgumentsNode* args, unsigned divot, unsigned startOffset, unsigned endOffset)
: ExpressionNode(globalData)
, ThrowableExpressionData(divot, startOffset, endOffset)
, m_ident(ident)
, m_args(args)
{
}
inline FunctionCallBracketNode::FunctionCallBracketNode(JSGlobalData* globalData, ExpressionNode* base, ExpressionNode* subscript, ArgumentsNode* args, unsigned divot, unsigned startOffset, unsigned endOffset)
: ExpressionNode(globalData)
, ThrowableSubExpressionData(divot, startOffset, endOffset)
, m_base(base)
, m_subscript(subscript)
, m_args(args)
{
}
inline FunctionCallDotNode::FunctionCallDotNode(JSGlobalData* globalData, ExpressionNode* base, const Identifier& ident, ArgumentsNode* args, unsigned divot, unsigned startOffset, unsigned endOffset)
: ExpressionNode(globalData)
, ThrowableSubExpressionData(divot, startOffset, endOffset)
, m_base(base)
, m_ident(ident)
, m_args(args)
{
}
inline CallFunctionCallDotNode::CallFunctionCallDotNode(JSGlobalData* globalData, ExpressionNode* base, const Identifier& ident, ArgumentsNode* args, unsigned divot, unsigned startOffset, unsigned endOffset)
: FunctionCallDotNode(globalData, base, ident, args, divot, startOffset, endOffset)
{
}
inline ApplyFunctionCallDotNode::ApplyFunctionCallDotNode(JSGlobalData* globalData, ExpressionNode* base, const Identifier& ident, ArgumentsNode* args, unsigned divot, unsigned startOffset, unsigned endOffset)
: FunctionCallDotNode(globalData, base, ident, args, divot, startOffset, endOffset)
{
}
inline PrePostResolveNode::PrePostResolveNode(JSGlobalData* globalData, const Identifier& ident, unsigned divot, unsigned startOffset, unsigned endOffset)
: ExpressionNode(globalData, ResultType::numberType()) // could be reusable for pre?
, ThrowableExpressionData(divot, startOffset, endOffset)
, m_ident(ident)
{
}
inline PostfixResolveNode::PostfixResolveNode(JSGlobalData* globalData, const Identifier& ident, Operator oper, unsigned divot, unsigned startOffset, unsigned endOffset)
: PrePostResolveNode(globalData, ident, divot, startOffset, endOffset)
, m_operator(oper)
{
}
inline PostfixBracketNode::PostfixBracketNode(JSGlobalData* globalData, ExpressionNode* base, ExpressionNode* subscript, Operator oper, unsigned divot, unsigned startOffset, unsigned endOffset)
: ExpressionNode(globalData)
, ThrowableSubExpressionData(divot, startOffset, endOffset)
, m_base(base)
, m_subscript(subscript)
, m_operator(oper)
{
}
inline PostfixDotNode::PostfixDotNode(JSGlobalData* globalData, ExpressionNode* base, const Identifier& ident, Operator oper, unsigned divot, unsigned startOffset, unsigned endOffset)
: ExpressionNode(globalData)
, ThrowableSubExpressionData(divot, startOffset, endOffset)
, m_base(base)
, m_ident(ident)
, m_operator(oper)
{
}
inline PostfixErrorNode::PostfixErrorNode(JSGlobalData* globalData, ExpressionNode* expr, Operator oper, unsigned divot, unsigned startOffset, unsigned endOffset)
: ExpressionNode(globalData)
, ThrowableSubExpressionData(divot, startOffset, endOffset)
, m_expr(expr)
, m_operator(oper)
{
}
inline DeleteResolveNode::DeleteResolveNode(JSGlobalData* globalData, const Identifier& ident, unsigned divot, unsigned startOffset, unsigned endOffset)
: ExpressionNode(globalData)
, ThrowableExpressionData(divot, startOffset, endOffset)
, m_ident(ident)
{
}
inline DeleteBracketNode::DeleteBracketNode(JSGlobalData* globalData, ExpressionNode* base, ExpressionNode* subscript, unsigned divot, unsigned startOffset, unsigned endOffset)
: ExpressionNode(globalData)
, ThrowableExpressionData(divot, startOffset, endOffset)
, m_base(base)
, m_subscript(subscript)
{
}
inline DeleteDotNode::DeleteDotNode(JSGlobalData* globalData, ExpressionNode* base, const Identifier& ident, unsigned divot, unsigned startOffset, unsigned endOffset)
: ExpressionNode(globalData)
, ThrowableExpressionData(divot, startOffset, endOffset)
, m_base(base)
, m_ident(ident)
{
}
inline DeleteValueNode::DeleteValueNode(JSGlobalData* globalData, ExpressionNode* expr)
: ExpressionNode(globalData)
, m_expr(expr)
{
}
inline VoidNode::VoidNode(JSGlobalData* globalData, ExpressionNode* expr)
: ExpressionNode(globalData)
, m_expr(expr)
{
}
inline TypeOfResolveNode::TypeOfResolveNode(JSGlobalData* globalData, const Identifier& ident)
: ExpressionNode(globalData, ResultType::stringType())
, m_ident(ident)
{
}
inline TypeOfValueNode::TypeOfValueNode(JSGlobalData* globalData, ExpressionNode* expr)
: ExpressionNode(globalData, ResultType::stringType())
, m_expr(expr)
{
}
inline PrefixResolveNode::PrefixResolveNode(JSGlobalData* globalData, const Identifier& ident, Operator oper, unsigned divot, unsigned startOffset, unsigned endOffset)
: PrePostResolveNode(globalData, ident, divot, startOffset, endOffset)
, m_operator(oper)
{
}
inline PrefixBracketNode::PrefixBracketNode(JSGlobalData* globalData, ExpressionNode* base, ExpressionNode* subscript, Operator oper, unsigned divot, unsigned startOffset, unsigned endOffset)
: ExpressionNode(globalData)
, ThrowablePrefixedSubExpressionData(divot, startOffset, endOffset)
, m_base(base)
, m_subscript(subscript)
, m_operator(oper)
{
}
inline PrefixDotNode::PrefixDotNode(JSGlobalData* globalData, ExpressionNode* base, const Identifier& ident, Operator oper, unsigned divot, unsigned startOffset, unsigned endOffset)
: ExpressionNode(globalData)
, ThrowablePrefixedSubExpressionData(divot, startOffset, endOffset)
, m_base(base)
, m_ident(ident)
, m_operator(oper)
{
}
inline PrefixErrorNode::PrefixErrorNode(JSGlobalData* globalData, ExpressionNode* expr, Operator oper, unsigned divot, unsigned startOffset, unsigned endOffset)
: ExpressionNode(globalData)
, ThrowableExpressionData(divot, startOffset, endOffset)
, m_expr(expr)
, m_operator(oper)
{
}
inline UnaryOpNode::UnaryOpNode(JSGlobalData* globalData, ResultType type, ExpressionNode* expr, OpcodeID opcodeID)
: ExpressionNode(globalData, type)
, m_expr(expr)
, m_opcodeID(opcodeID)
{
}
inline UnaryPlusNode::UnaryPlusNode(JSGlobalData* globalData, ExpressionNode* expr)
: UnaryOpNode(globalData, ResultType::numberType(), expr, op_to_jsnumber)
{
}
inline NegateNode::NegateNode(JSGlobalData* globalData, ExpressionNode* expr)
: UnaryOpNode(globalData, ResultType::numberTypeCanReuse(), expr, op_negate)
{
}
inline BitwiseNotNode::BitwiseNotNode(JSGlobalData* globalData, ExpressionNode* expr)
: UnaryOpNode(globalData, ResultType::forBitOp(), expr, op_bitnot)
{
}
inline LogicalNotNode::LogicalNotNode(JSGlobalData* globalData, ExpressionNode* expr)
: UnaryOpNode(globalData, ResultType::booleanType(), expr, op_not)
{
}
inline BinaryOpNode::BinaryOpNode(JSGlobalData* globalData, ExpressionNode* expr1, ExpressionNode* expr2, OpcodeID opcodeID, bool rightHasAssignments)
: ExpressionNode(globalData)
, m_expr1(expr1)
, m_expr2(expr2)
, m_opcodeID(opcodeID)
, m_rightHasAssignments(rightHasAssignments)
{
}
inline BinaryOpNode::BinaryOpNode(JSGlobalData* globalData, ResultType type, ExpressionNode* expr1, ExpressionNode* expr2, OpcodeID opcodeID, bool rightHasAssignments)
: ExpressionNode(globalData, type)
, m_expr1(expr1)
, m_expr2(expr2)
, m_opcodeID(opcodeID)
, m_rightHasAssignments(rightHasAssignments)
{
}
inline ReverseBinaryOpNode::ReverseBinaryOpNode(JSGlobalData* globalData, ExpressionNode* expr1, ExpressionNode* expr2, OpcodeID opcodeID, bool rightHasAssignments)
: BinaryOpNode(globalData, expr1, expr2, opcodeID, rightHasAssignments)
{
}
inline ReverseBinaryOpNode::ReverseBinaryOpNode(JSGlobalData* globalData, ResultType type, ExpressionNode* expr1, ExpressionNode* expr2, OpcodeID opcodeID, bool rightHasAssignments)
: BinaryOpNode(globalData, type, expr1, expr2, opcodeID, rightHasAssignments)
{
}
inline MultNode::MultNode(JSGlobalData* globalData, ExpressionNode* expr1, ExpressionNode* expr2, bool rightHasAssignments)
: BinaryOpNode(globalData, ResultType::numberTypeCanReuse(), expr1, expr2, op_mul, rightHasAssignments)
{
}
inline DivNode::DivNode(JSGlobalData* globalData, ExpressionNode* expr1, ExpressionNode* expr2, bool rightHasAssignments)
: BinaryOpNode(globalData, ResultType::numberTypeCanReuse(), expr1, expr2, op_div, rightHasAssignments)
{
}
inline ModNode::ModNode(JSGlobalData* globalData, ExpressionNode* expr1, ExpressionNode* expr2, bool rightHasAssignments)
: BinaryOpNode(globalData, ResultType::numberTypeCanReuse(), expr1, expr2, op_mod, rightHasAssignments)
{
}
inline AddNode::AddNode(JSGlobalData* globalData, ExpressionNode* expr1, ExpressionNode* expr2, bool rightHasAssignments)
: BinaryOpNode(globalData, ResultType::forAdd(expr1->resultDescriptor(), expr2->resultDescriptor()), expr1, expr2, op_add, rightHasAssignments)
{
}
inline SubNode::SubNode(JSGlobalData* globalData, ExpressionNode* expr1, ExpressionNode* expr2, bool rightHasAssignments)
: BinaryOpNode(globalData, ResultType::numberTypeCanReuse(), expr1, expr2, op_sub, rightHasAssignments)
{
}
inline LeftShiftNode::LeftShiftNode(JSGlobalData* globalData, ExpressionNode* expr1, ExpressionNode* expr2, bool rightHasAssignments)
: BinaryOpNode(globalData, ResultType::forBitOp(), expr1, expr2, op_lshift, rightHasAssignments)
{
}
inline RightShiftNode::RightShiftNode(JSGlobalData* globalData, ExpressionNode* expr1, ExpressionNode* expr2, bool rightHasAssignments)
: BinaryOpNode(globalData, ResultType::forBitOp(), expr1, expr2, op_rshift, rightHasAssignments)
{
}
inline UnsignedRightShiftNode::UnsignedRightShiftNode(JSGlobalData* globalData, ExpressionNode* expr1, ExpressionNode* expr2, bool rightHasAssignments)
: BinaryOpNode(globalData, ResultType::numberTypeCanReuse(), expr1, expr2, op_urshift, rightHasAssignments)
{
}
inline LessNode::LessNode(JSGlobalData* globalData, ExpressionNode* expr1, ExpressionNode* expr2, bool rightHasAssignments)
: BinaryOpNode(globalData, ResultType::booleanType(), expr1, expr2, op_less, rightHasAssignments)
{
}
inline GreaterNode::GreaterNode(JSGlobalData* globalData, ExpressionNode* expr1, ExpressionNode* expr2, bool rightHasAssignments)
: ReverseBinaryOpNode(globalData, ResultType::booleanType(), expr1, expr2, op_less, rightHasAssignments)
{
}
inline LessEqNode::LessEqNode(JSGlobalData* globalData, ExpressionNode* expr1, ExpressionNode* expr2, bool rightHasAssignments)
: BinaryOpNode(globalData, ResultType::booleanType(), expr1, expr2, op_lesseq, rightHasAssignments)
{
}
inline GreaterEqNode::GreaterEqNode(JSGlobalData* globalData, ExpressionNode* expr1, ExpressionNode* expr2, bool rightHasAssignments)
: ReverseBinaryOpNode(globalData, ResultType::booleanType(), expr1, expr2, op_lesseq, rightHasAssignments)
{
}
inline ThrowableBinaryOpNode::ThrowableBinaryOpNode(JSGlobalData* globalData, ResultType type, ExpressionNode* expr1, ExpressionNode* expr2, OpcodeID opcodeID, bool rightHasAssignments)
: BinaryOpNode(globalData, type, expr1, expr2, opcodeID, rightHasAssignments)
{
}
inline ThrowableBinaryOpNode::ThrowableBinaryOpNode(JSGlobalData* globalData, ExpressionNode* expr1, ExpressionNode* expr2, OpcodeID opcodeID, bool rightHasAssignments)
: BinaryOpNode(globalData, expr1, expr2, opcodeID, rightHasAssignments)
{
}
inline InstanceOfNode::InstanceOfNode(JSGlobalData* globalData, ExpressionNode* expr1, ExpressionNode* expr2, bool rightHasAssignments)
: ThrowableBinaryOpNode(globalData, ResultType::booleanType(), expr1, expr2, op_instanceof, rightHasAssignments)
{
}
inline InNode::InNode(JSGlobalData* globalData, ExpressionNode* expr1, ExpressionNode* expr2, bool rightHasAssignments)
: ThrowableBinaryOpNode(globalData, expr1, expr2, op_in, rightHasAssignments)
{
}
inline EqualNode::EqualNode(JSGlobalData* globalData, ExpressionNode* expr1, ExpressionNode* expr2, bool rightHasAssignments)
: BinaryOpNode(globalData, ResultType::booleanType(), expr1, expr2, op_eq, rightHasAssignments)
{
}
inline NotEqualNode::NotEqualNode(JSGlobalData* globalData, ExpressionNode* expr1, ExpressionNode* expr2, bool rightHasAssignments)
: BinaryOpNode(globalData, ResultType::booleanType(), expr1, expr2, op_neq, rightHasAssignments)
{
}
inline StrictEqualNode::StrictEqualNode(JSGlobalData* globalData, ExpressionNode* expr1, ExpressionNode* expr2, bool rightHasAssignments)
: BinaryOpNode(globalData, ResultType::booleanType(), expr1, expr2, op_stricteq, rightHasAssignments)
{
}
inline NotStrictEqualNode::NotStrictEqualNode(JSGlobalData* globalData, ExpressionNode* expr1, ExpressionNode* expr2, bool rightHasAssignments)
: BinaryOpNode(globalData, ResultType::booleanType(), expr1, expr2, op_nstricteq, rightHasAssignments)
{
}
inline BitAndNode::BitAndNode(JSGlobalData* globalData, ExpressionNode* expr1, ExpressionNode* expr2, bool rightHasAssignments)
: BinaryOpNode(globalData, ResultType::forBitOp(), expr1, expr2, op_bitand, rightHasAssignments)
{
}
inline BitOrNode::BitOrNode(JSGlobalData* globalData, ExpressionNode* expr1, ExpressionNode* expr2, bool rightHasAssignments)
: BinaryOpNode(globalData, ResultType::forBitOp(), expr1, expr2, op_bitor, rightHasAssignments)
{
}
inline BitXOrNode::BitXOrNode(JSGlobalData* globalData, ExpressionNode* expr1, ExpressionNode* expr2, bool rightHasAssignments)
: BinaryOpNode(globalData, ResultType::forBitOp(), expr1, expr2, op_bitxor, rightHasAssignments)
{
}
inline LogicalOpNode::LogicalOpNode(JSGlobalData* globalData, ExpressionNode* expr1, ExpressionNode* expr2, LogicalOperator oper)
: ExpressionNode(globalData, ResultType::booleanType())
, m_expr1(expr1)
, m_expr2(expr2)
, m_operator(oper)
{
}
inline ConditionalNode::ConditionalNode(JSGlobalData* globalData, ExpressionNode* logical, ExpressionNode* expr1, ExpressionNode* expr2)
: ExpressionNode(globalData)
, m_logical(logical)
, m_expr1(expr1)
, m_expr2(expr2)
{
}
inline ReadModifyResolveNode::ReadModifyResolveNode(JSGlobalData* globalData, const Identifier& ident, Operator oper, ExpressionNode* right, bool rightHasAssignments, unsigned divot, unsigned startOffset, unsigned endOffset)
: ExpressionNode(globalData)
, ThrowableExpressionData(divot, startOffset, endOffset)
, m_ident(ident)
, m_right(right)
, m_operator(oper)
, m_rightHasAssignments(rightHasAssignments)
{
}
inline AssignResolveNode::AssignResolveNode(JSGlobalData* globalData, const Identifier& ident, ExpressionNode* right, bool rightHasAssignments)
: ExpressionNode(globalData)
, m_ident(ident)
, m_right(right)
, m_rightHasAssignments(rightHasAssignments)
{
}
inline ReadModifyBracketNode::ReadModifyBracketNode(JSGlobalData* globalData, ExpressionNode* base, ExpressionNode* subscript, Operator oper, ExpressionNode* right, bool subscriptHasAssignments, bool rightHasAssignments, unsigned divot, unsigned startOffset, unsigned endOffset)
: ExpressionNode(globalData)
, ThrowableSubExpressionData(divot, startOffset, endOffset)
, m_base(base)
, m_subscript(subscript)
, m_right(right)
, m_operator(oper)
, m_subscriptHasAssignments(subscriptHasAssignments)
, m_rightHasAssignments(rightHasAssignments)
{
}
inline AssignBracketNode::AssignBracketNode(JSGlobalData* globalData, ExpressionNode* base, ExpressionNode* subscript, ExpressionNode* right, bool subscriptHasAssignments, bool rightHasAssignments, unsigned divot, unsigned startOffset, unsigned endOffset)
: ExpressionNode(globalData)
, ThrowableExpressionData(divot, startOffset, endOffset)
, m_base(base)
, m_subscript(subscript)
, m_right(right)
, m_subscriptHasAssignments(subscriptHasAssignments)
, m_rightHasAssignments(rightHasAssignments)
{
}
inline AssignDotNode::AssignDotNode(JSGlobalData* globalData, ExpressionNode* base, const Identifier& ident, ExpressionNode* right, bool rightHasAssignments, unsigned divot, unsigned startOffset, unsigned endOffset)
: ExpressionNode(globalData)
, ThrowableExpressionData(divot, startOffset, endOffset)
, m_base(base)
, m_ident(ident)
, m_right(right)
, m_rightHasAssignments(rightHasAssignments)
{
}
inline ReadModifyDotNode::ReadModifyDotNode(JSGlobalData* globalData, ExpressionNode* base, const Identifier& ident, Operator oper, ExpressionNode* right, bool rightHasAssignments, unsigned divot, unsigned startOffset, unsigned endOffset)
: ExpressionNode(globalData)
, ThrowableSubExpressionData(divot, startOffset, endOffset)
, m_base(base)
, m_ident(ident)
, m_right(right)
, m_operator(oper)
, m_rightHasAssignments(rightHasAssignments)
{
}
inline AssignErrorNode::AssignErrorNode(JSGlobalData* globalData, ExpressionNode* left, Operator oper, ExpressionNode* right, unsigned divot, unsigned startOffset, unsigned endOffset)
: ExpressionNode(globalData)
, ThrowableExpressionData(divot, startOffset, endOffset)
, m_left(left)
, m_operator(oper)
, m_right(right)
{
}
inline CommaNode::CommaNode(JSGlobalData* globalData, ExpressionNode* expr1, ExpressionNode* expr2)
: ExpressionNode(globalData)
{
m_expressions.append(expr1);
m_expressions.append(expr2);
}
inline ConstStatementNode::ConstStatementNode(JSGlobalData* globalData, ConstDeclNode* next)
: StatementNode(globalData)
, m_next(next)
{
}
inline SourceElements::SourceElements(JSGlobalData*)
{
}
inline EmptyStatementNode::EmptyStatementNode(JSGlobalData* globalData)
: StatementNode(globalData)
{
}
inline DebuggerStatementNode::DebuggerStatementNode(JSGlobalData* globalData)
: StatementNode(globalData)
{
}
inline ExprStatementNode::ExprStatementNode(JSGlobalData* globalData, ExpressionNode* expr)
: StatementNode(globalData)
, m_expr(expr)
{
}
inline VarStatementNode::VarStatementNode(JSGlobalData* globalData, ExpressionNode* expr)
: StatementNode(globalData)
, m_expr(expr)
{
}
inline IfNode::IfNode(JSGlobalData* globalData, ExpressionNode* condition, StatementNode* ifBlock)
: StatementNode(globalData)
, m_condition(condition)
, m_ifBlock(ifBlock)
{
}
inline IfElseNode::IfElseNode(JSGlobalData* globalData, ExpressionNode* condition, StatementNode* ifBlock, StatementNode* elseBlock)
: IfNode(globalData, condition, ifBlock)
, m_elseBlock(elseBlock)
{
}
inline DoWhileNode::DoWhileNode(JSGlobalData* globalData, StatementNode* statement, ExpressionNode* expr)
: StatementNode(globalData)
, m_statement(statement)
, m_expr(expr)
{
}
inline WhileNode::WhileNode(JSGlobalData* globalData, ExpressionNode* expr, StatementNode* statement)
: StatementNode(globalData)
, m_expr(expr)
, m_statement(statement)
{
}
inline ForNode::ForNode(JSGlobalData* globalData, ExpressionNode* expr1, ExpressionNode* expr2, ExpressionNode* expr3, StatementNode* statement, bool expr1WasVarDecl)
: StatementNode(globalData)
, m_expr1(expr1)
, m_expr2(expr2)
, m_expr3(expr3)
, m_statement(statement)
{
Q_ASSERT(statement);
}
inline ContinueNode::ContinueNode(JSGlobalData* globalData)
: StatementNode(globalData)
, m_ident(globalData->propertyNames->nullIdentifier)
{
}
inline ContinueNode::ContinueNode(JSGlobalData* globalData, const Identifier& ident)
: StatementNode(globalData)
, m_ident(ident)
{
}
inline BreakNode::BreakNode(JSGlobalData* globalData)
: StatementNode(globalData)
, m_ident(globalData->propertyNames->nullIdentifier)
{
}
inline BreakNode::BreakNode(JSGlobalData* globalData, const Identifier& ident)
: StatementNode(globalData)
, m_ident(ident)
{
}
inline ReturnNode::ReturnNode(JSGlobalData* globalData, ExpressionNode* value)
: StatementNode(globalData)
, m_value(value)
{
}
inline WithNode::WithNode(JSGlobalData* globalData, ExpressionNode* expr, StatementNode* statement, uint32_t divot, uint32_t expressionLength)
: StatementNode(globalData)
, m_expr(expr)
, m_statement(statement)
, m_divot(divot)
, m_expressionLength(expressionLength)
{
}
inline LabelNode::LabelNode(JSGlobalData* globalData, const Identifier& name, StatementNode* statement)
: StatementNode(globalData)
, m_name(name)
, m_statement(statement)
{
}
inline ThrowNode::ThrowNode(JSGlobalData* globalData, ExpressionNode* expr)
: StatementNode(globalData)
, m_expr(expr)
{
}
inline TryNode::TryNode(JSGlobalData* globalData, StatementNode* tryBlock, const Identifier& exceptionIdent, bool catchHasEval, StatementNode* catchBlock, StatementNode* finallyBlock)
: StatementNode(globalData)
, m_tryBlock(tryBlock)
, m_exceptionIdent(exceptionIdent)
, m_catchBlock(catchBlock)
, m_finallyBlock(finallyBlock)
, m_catchHasEval(catchHasEval)
{
}
inline ParameterNode::ParameterNode(JSGlobalData*, const Identifier& ident)
: m_ident(ident)
, m_next(0)
{
}
inline ParameterNode::ParameterNode(JSGlobalData*, ParameterNode* l, const Identifier& ident)
: m_ident(ident)
, m_next(0)
{
l->m_next = this;
}
inline FuncExprNode::FuncExprNode(JSGlobalData* globalData, const Identifier& ident, FunctionBodyNode* body, const SourceCode& source, ParameterNode* parameter)
: ExpressionNode(globalData)
, m_body(body)
{
m_body->finishParsing(source, parameter, ident);
}
inline FuncDeclNode::FuncDeclNode(JSGlobalData* globalData, const Identifier& ident, FunctionBodyNode* body, const SourceCode& source, ParameterNode* parameter)
: StatementNode(globalData)
, m_body(body)
{
m_body->finishParsing(source, parameter, ident);
}
inline CaseClauseNode::CaseClauseNode(JSGlobalData*, ExpressionNode* expr, SourceElements* statements)
: m_expr(expr)
, m_statements(statements)
{
}
inline ClauseListNode::ClauseListNode(JSGlobalData*, CaseClauseNode* clause)
: m_clause(clause)
, m_next(0)
{
}
inline ClauseListNode::ClauseListNode(JSGlobalData*, ClauseListNode* clauseList, CaseClauseNode* clause)
: m_clause(clause)
, m_next(0)
{
clauseList->m_next = this;
}
inline CaseBlockNode::CaseBlockNode(JSGlobalData*, ClauseListNode* list1, CaseClauseNode* defaultClause, ClauseListNode* list2)
: m_list1(list1)
, m_defaultClause(defaultClause)
, m_list2(list2)
{
}
inline SwitchNode::SwitchNode(JSGlobalData* globalData, ExpressionNode* expr, CaseBlockNode* block)
: StatementNode(globalData)
, m_expr(expr)
, m_block(block)
{
}
inline ConstDeclNode::ConstDeclNode(JSGlobalData* globalData, const Identifier& ident, ExpressionNode* init)
: ExpressionNode(globalData)
, m_ident(ident)
, m_next(0)
, m_init(init)
{
}
inline BlockNode::BlockNode(JSGlobalData* globalData, SourceElements* statements)
: StatementNode(globalData)
, m_statements(statements)
{
}
inline ForInNode::ForInNode(JSGlobalData* globalData, ExpressionNode* l, ExpressionNode* expr, StatementNode* statement)
: StatementNode(globalData)
, m_ident(globalData->propertyNames->nullIdentifier)
, m_init(0)
, m_lexpr(l)
, m_expr(expr)
, m_statement(statement)
{
}
inline ForInNode::ForInNode(JSGlobalData* globalData, const Identifier& ident, ExpressionNode* in, ExpressionNode* expr, StatementNode* statement, int divot, int startOffset, int endOffset)
: StatementNode(globalData)
, m_ident(ident)
, m_init(0)
, m_lexpr(new (globalData) ResolveNode(globalData, ident, divot - startOffset))
, m_expr(expr)
, m_statement(statement)
{
if (in) {
AssignResolveNode* node = new (globalData) AssignResolveNode(globalData, ident, in, true);
node->setExceptionSourceCode(divot, divot - startOffset, endOffset - divot);
m_init = node;
}
// for( var foo = bar in baz )
}
} // namespace JSC
#endif // NodeConstructors_h

View file

@ -1,63 +0,0 @@
/*
* Copyright (C) 2007 Apple Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
#ifndef NodeInfo_h
#define NodeInfo_h
#include "Nodes.h"
#include "Parser.h"
namespace JSC {
template <typename T> struct NodeInfo {
T m_node;
CodeFeatures m_features;
int m_numConstants;
};
typedef NodeInfo<FuncDeclNode*> FuncDeclNodeInfo;
typedef NodeInfo<FuncExprNode*> FuncExprNodeInfo;
typedef NodeInfo<ExpressionNode*> ExpressionNodeInfo;
typedef NodeInfo<ArgumentsNode*> ArgumentsNodeInfo;
typedef NodeInfo<ConstDeclNode*> ConstDeclNodeInfo;
typedef NodeInfo<PropertyNode*> PropertyNodeInfo;
typedef NodeInfo<PropertyList> PropertyListInfo;
typedef NodeInfo<ElementList> ElementListInfo;
typedef NodeInfo<ArgumentList> ArgumentListInfo;
template <typename T> struct NodeDeclarationInfo {
T m_node;
ParserArenaData<DeclarationStacks::VarStack>* m_varDeclarations;
ParserArenaData<DeclarationStacks::FunctionStack>* m_funcDeclarations;
CodeFeatures m_features;
int m_numConstants;
};
typedef NodeDeclarationInfo<StatementNode*> StatementNodeInfo;
typedef NodeDeclarationInfo<CaseBlockNode*> CaseBlockNodeInfo;
typedef NodeDeclarationInfo<CaseClauseNode*> CaseClauseNodeInfo;
typedef NodeDeclarationInfo<SourceElements*> SourceElementsInfo;
typedef NodeDeclarationInfo<ClauseList> ClauseListInfo;
typedef NodeDeclarationInfo<ExpressionNode*> VarDeclListInfo;
typedef NodeDeclarationInfo<ConstDeclList> ConstDeclListInfo;
typedef NodeDeclarationInfo<ParameterList> ParameterListInfo;
} // namespace JSC
#endif // NodeInfo_h

View file

@ -1,192 +0,0 @@
/*
* Copyright (C) 1999-2002 Harri Porten (porten@kde.org)
* Copyright (C) 2001 Peter Kelly (pmk@post.com)
* Copyright (C) 2003, 2004, 2005, 2006, 2007, 2008, 2009 Apple Inc. All rights reserved.
* Copyright (C) 2007 Cameron Zwarich (cwzwarich@uwaterloo.ca)
* Copyright (C) 2007 Maks Orlovich
* Copyright (C) 2007 Eric Seidel <eric@webkit.org>
*
* 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.
*
*/
#include "Platform.h"
#include "Nodes.h"
#include "NodeConstructors.h"
#include "BytecodeGenerator.h"
#include "CallFrame.h"
#include "JSFunction.h"
#include "JSGlobalObject.h"
#include "JSStaticScopeObject.h"
#include "LabelScope.h"
#include "Lexer.h"
#include "Operations.h"
#include "Parser.h"
#include "PropertyNameArray.h"
#include "RegExpObject.h"
#include "SamplingTool.h"
#include <wtf/Assertions.h>
#include <wtf/Threading.h>
using namespace WTF;
namespace JSC {
// ------------------------------ StatementNode --------------------------------
void StatementNode::setLoc(int firstLine, int lastLine)
{
m_line = firstLine;
m_lastLine = lastLine;
}
// ------------------------------ SourceElements --------------------------------
void SourceElements::append(StatementNode* statement)
{
if (statement->isEmptyStatement())
return;
m_statements.append(statement);
}
inline StatementNode* SourceElements::singleStatement() const
{
size_t size = m_statements.size();
return size == 1 ? m_statements[0] : 0;
}
// -----------------------------ScopeNodeData ---------------------------
ScopeNodeData::ScopeNodeData(ParserArena& arena, SourceElements* statements, VarStack* varStack, FunctionStack* funcStack, int numConstants)
: m_numConstants(numConstants)
, m_statements(statements)
{
m_arena.swap(arena);
if (varStack)
m_varStack.swap(*varStack);
if (funcStack)
m_functionStack.swap(*funcStack);
}
// ------------------------------ ScopeNode -----------------------------
ScopeNode::ScopeNode(JSGlobalData* globalData)
: StatementNode(globalData)
, ParserArenaRefCounted(globalData)
, m_features(NoFeatures)
{
}
ScopeNode::ScopeNode(JSGlobalData* globalData, const SourceCode& source, SourceElements* children, VarStack* varStack, FunctionStack* funcStack, CodeFeatures features, int numConstants)
: StatementNode(globalData)
, ParserArenaRefCounted(globalData)
, m_data(new ScopeNodeData(globalData->parser->arena(), children, varStack, funcStack, numConstants))
, m_features(features)
, m_source(source)
{
}
StatementNode* ScopeNode::singleStatement() const
{
return m_data->m_statements ? m_data->m_statements->singleStatement() : 0;
}
// ------------------------------ ProgramNode -----------------------------
inline ProgramNode::ProgramNode(JSGlobalData* globalData, SourceElements* children, VarStack* varStack, FunctionStack* funcStack, const SourceCode& source, CodeFeatures features, int numConstants)
: ScopeNode(globalData, source, children, varStack, funcStack, features, numConstants)
{
}
PassRefPtr<ProgramNode> ProgramNode::create(JSGlobalData* globalData, SourceElements* children, VarStack* varStack, FunctionStack* funcStack, const SourceCode& source, CodeFeatures features, int numConstants)
{
RefPtr<ProgramNode> node = new ProgramNode(globalData, children, varStack, funcStack, source, features, numConstants);
Q_ASSERT(node->data()->m_arena.last() == node);
node->data()->m_arena.removeLast();
Q_ASSERT(!node->data()->m_arena.contains(node.get()));
return node.release();
}
// ------------------------------ EvalNode -----------------------------
inline EvalNode::EvalNode(JSGlobalData* globalData, SourceElements* children, VarStack* varStack, FunctionStack* funcStack, const SourceCode& source, CodeFeatures features, int numConstants)
: ScopeNode(globalData, source, children, varStack, funcStack, features, numConstants)
{
}
PassRefPtr<EvalNode> EvalNode::create(JSGlobalData* globalData, SourceElements* children, VarStack* varStack, FunctionStack* funcStack, const SourceCode& source, CodeFeatures features, int numConstants)
{
RefPtr<EvalNode> node = new EvalNode(globalData, children, varStack, funcStack, source, features, numConstants);
Q_ASSERT(node->data()->m_arena.last() == node);
node->data()->m_arena.removeLast();
Q_ASSERT(!node->data()->m_arena.contains(node.get()));
return node.release();
}
// ------------------------------ FunctionBodyNode -----------------------------
FunctionParameters::FunctionParameters(ParameterNode* firstParameter)
{
for (ParameterNode* parameter = firstParameter; parameter; parameter = parameter->nextParam())
append(parameter->ident());
}
inline FunctionBodyNode::FunctionBodyNode(JSGlobalData* globalData)
: ScopeNode(globalData)
{
}
inline FunctionBodyNode::FunctionBodyNode(JSGlobalData* globalData, SourceElements* children, VarStack* varStack, FunctionStack* funcStack, const SourceCode& sourceCode, CodeFeatures features, int numConstants)
: ScopeNode(globalData, sourceCode, children, varStack, funcStack, features, numConstants)
{
}
void FunctionBodyNode::finishParsing(const SourceCode& source, ParameterNode* firstParameter, const Identifier& ident)
{
setSource(source);
finishParsing(FunctionParameters::create(firstParameter), ident);
}
void FunctionBodyNode::finishParsing(PassRefPtr<FunctionParameters> parameters, const Identifier& ident)
{
Q_ASSERT(!source().isNull());
m_parameters = parameters;
m_ident = ident;
}
FunctionBodyNode* FunctionBodyNode::create(JSGlobalData* globalData)
{
return new FunctionBodyNode(globalData);
}
PassRefPtr<FunctionBodyNode> FunctionBodyNode::create(JSGlobalData* globalData, SourceElements* children, VarStack* varStack, FunctionStack* funcStack, const SourceCode& sourceCode, CodeFeatures features, int numConstants)
{
RefPtr<FunctionBodyNode> node = new FunctionBodyNode(globalData, children, varStack, funcStack, sourceCode, features, numConstants);
Q_ASSERT(node->data()->m_arena.last() == node);
node->data()->m_arena.removeLast();
Q_ASSERT(!node->data()->m_arena.contains(node.get()));
return node.release();
}
} // namespace JSC

File diff suppressed because it is too large Load diff

View file

@ -1,78 +0,0 @@
/*
* Copyright (C) 1999-2001 Harri Porten (porten@kde.org)
* Copyright (C) 2001 Peter Kelly (pmk@post.com)
* Copyright (C) 2003, 2006, 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.
*
*/
#include "Platform.h"
#include "Parser.h"
#include "Lexer.h"
#include <wtf/HashSet.h>
#include <wtf/Vector.h>
#include <memory>
#ifndef yyparse
extern int jscyyparse(void*);
#endif
namespace JSC {
void Parser::parse(JSGlobalData* globalData, int* errLine, UString* errMsg)
{
m_sourceElements = 0;
int defaultErrLine;
UString defaultErrMsg;
if (!errLine)
errLine = &defaultErrLine;
if (!errMsg)
errMsg = &defaultErrMsg;
*errLine = -1;
*errMsg = 0;
Lexer& lexer = *globalData->lexer;
lexer.setCode(*m_source, m_arena);
int parseError = jscyyparse(globalData);
bool lexError = lexer.sawError();
int lineNumber = lexer.lineNumber();
lexer.clear();
if (parseError || lexError) {
*errLine = lineNumber;
*errMsg = "Parse error";
m_sourceElements = 0;
}
}
void Parser::didFinishParsing(SourceElements* sourceElements, ParserArenaData<DeclarationStacks::VarStack>* varStack,
ParserArenaData<DeclarationStacks::FunctionStack>* funcStack, CodeFeatures features, int lastLine, int numConstants)
{
m_sourceElements = sourceElements;
m_varDeclarations = varStack;
m_funcDeclarations = funcStack;
m_features = features;
m_lastLine = lastLine;
m_numConstants = numConstants;
}
} // namespace JSC

View file

@ -1,103 +0,0 @@
/*
* Copyright (C) 1999-2001 Harri Porten (porten@kde.org)
* Copyright (C) 2001 Peter Kelly (pmk@post.com)
* Copyright (C) 2003, 2006, 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 Parser_h
#define Parser_h
#include "Debugger.h"
#include "Executable.h"
#include "JSGlobalObject.h"
#include "Lexer.h"
#include "Nodes.h"
#include "ParserArena.h"
#include "SourceProvider.h"
#include <wtf/Forward.h>
#include <wtf/Noncopyable.h>
#include <wtf/OwnPtr.h>
#include <wtf/RefPtr.h>
namespace JSC {
class FunctionBodyNode;
class ProgramNode;
class UString;
template <typename T> struct ParserArenaData : ParserArenaDeletable { T data; };
class Parser : public Noncopyable {
public:
template <class ParsedNode>
PassRefPtr<ParsedNode> parse(JSGlobalData* globalData, Debugger*, ExecState*, const SourceCode& source, int* errLine = 0, UString* errMsg = 0);
void didFinishParsing(SourceElements*, ParserArenaData<DeclarationStacks::VarStack>*,
ParserArenaData<DeclarationStacks::FunctionStack>*, CodeFeatures features, int lastLine, int numConstants);
ParserArena& arena() { return m_arena; }
private:
void parse(JSGlobalData*, int* errLine, UString* errMsg);
ParserArena m_arena;
const SourceCode* m_source;
SourceElements* m_sourceElements;
ParserArenaData<DeclarationStacks::VarStack>* m_varDeclarations;
ParserArenaData<DeclarationStacks::FunctionStack>* m_funcDeclarations;
CodeFeatures m_features;
int m_lastLine;
int m_numConstants;
};
template <class ParsedNode>
PassRefPtr<ParsedNode> Parser::parse(JSGlobalData* globalData, Debugger* debugger, ExecState* debuggerExecState, const SourceCode& source, int* errLine, UString* errMsg)
{
m_source = &source;
if (ParsedNode::scopeIsFunction)
globalData->lexer->setIsReparsing();
parse(globalData, errLine, errMsg);
RefPtr<ParsedNode> result;
if (m_sourceElements) {
result = ParsedNode::create(globalData,
m_sourceElements,
m_varDeclarations ? &m_varDeclarations->data : 0,
m_funcDeclarations ? &m_funcDeclarations->data : 0,
source,
m_features,
m_numConstants);
result->setLoc(m_source->firstLine(), m_lastLine);
}
m_arena.reset();
m_source = 0;
m_sourceElements = 0;
m_varDeclarations = 0;
m_funcDeclarations = 0;
if (debugger && !ParsedNode::scopeIsFunction)
debugger->sourceParsed(debuggerExecState, source, *errLine, *errMsg);
return result.release();
}
} // namespace JSC
#endif // Parser_h

View file

@ -1,135 +0,0 @@
/*
* Copyright (C) 2009 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "Platform.h"
#include "Parser.h"
#include "ParserArena.h"
#include "Nodes.h"
namespace JSC {
ParserArena::ParserArena()
: m_freeableMemory(0)
, m_freeablePoolEnd(0)
, m_identifierArena(new IdentifierArena)
{
}
inline void* ParserArena::freeablePool()
{
Q_ASSERT(m_freeablePoolEnd);
return m_freeablePoolEnd - freeablePoolSize;
}
inline void ParserArena::deallocateObjects()
{
if (m_freeablePoolEnd)
fastFree(freeablePool());
size_t size = m_freeablePools.size();
for (size_t i = 0; i < size; ++i)
fastFree(m_freeablePools[i]);
size = m_deletableObjects.size();
for (size_t i = 0; i < size; ++i) {
ParserArenaDeletable* object = m_deletableObjects[i];
object->~ParserArenaDeletable();
fastFree(object);
}
}
ParserArena::~ParserArena()
{
deallocateObjects();
}
bool ParserArena::contains(ParserArenaRefCounted* object) const
{
return m_refCountedObjects.find(object) != notFound;
}
ParserArenaRefCounted* ParserArena::last() const
{
return m_refCountedObjects.last().get();
}
void ParserArena::removeLast()
{
m_refCountedObjects.removeLast();
}
void ParserArena::reset()
{
// Since this code path is used only when parsing fails, it's not bothering to reuse
// any of the memory the arena allocated. We could improve that later if we want to
// efficiently reuse the same arena.
deallocateObjects();
m_freeableMemory = 0;
m_freeablePoolEnd = 0;
m_identifierArena->clear();
m_freeablePools.clear();
m_deletableObjects.clear();
m_refCountedObjects.clear();
}
void ParserArena::allocateFreeablePool()
{
if (m_freeablePoolEnd)
m_freeablePools.append(freeablePool());
char* pool = static_cast<char*>(fastMalloc(freeablePoolSize));
m_freeableMemory = pool;
m_freeablePoolEnd = pool + freeablePoolSize;
Q_ASSERT(freeablePool() == pool);
}
bool ParserArena::isEmpty() const
{
return !m_freeablePoolEnd
&& m_identifierArena->isEmpty()
&& m_freeablePools.isEmpty()
&& m_deletableObjects.isEmpty()
&& m_refCountedObjects.isEmpty();
}
void ParserArena::derefWithArena(PassRefPtr<ParserArenaRefCounted> object)
{
m_refCountedObjects.append(object);
}
void* ParserArenaFreeable::operator new(size_t size, JSGlobalData* globalData)
{
return globalData->parser->arena().allocateFreeable(size);
}
void* ParserArenaDeletable::operator new(size_t size, JSGlobalData* globalData)
{
return globalData->parser->arena().allocateDeletable(size);
}
}

View file

@ -1,123 +0,0 @@
/*
* Copyright (C) 2009 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef ParserArena_h
#define ParserArena_h
#include "Identifier.h"
#include <wtf/SegmentedVector.h>
namespace JSC {
class ParserArenaDeletable;
class ParserArenaRefCounted;
class IdentifierArena : public FastAllocBase {
public:
ALWAYS_INLINE const Identifier& makeIdentifier(JSGlobalData*, const UChar* characters, size_t length);
const Identifier& makeNumericIdentifier(JSGlobalData*, double number);
void clear() { m_identifiers.clear(); }
bool isEmpty() const { return m_identifiers.isEmpty(); }
private:
typedef SegmentedVector<Identifier, 64> IdentifierVector;
IdentifierVector m_identifiers;
};
ALWAYS_INLINE const Identifier& IdentifierArena::makeIdentifier(JSGlobalData* globalData, const UChar* characters, size_t length)
{
m_identifiers.append(Identifier(globalData, characters, length));
return m_identifiers.last();
}
inline const Identifier& IdentifierArena::makeNumericIdentifier(JSGlobalData* globalData, double number)
{
m_identifiers.append(Identifier(globalData, UString::from(number)));
return m_identifiers.last();
}
class ParserArena : Noncopyable {
public:
ParserArena();
~ParserArena();
void swap(ParserArena& otherArena)
{
std::swap(m_freeableMemory, otherArena.m_freeableMemory);
std::swap(m_freeablePoolEnd, otherArena.m_freeablePoolEnd);
m_identifierArena.swap(otherArena.m_identifierArena);
m_freeablePools.swap(otherArena.m_freeablePools);
m_deletableObjects.swap(otherArena.m_deletableObjects);
m_refCountedObjects.swap(otherArena.m_refCountedObjects);
}
void* allocateFreeable(size_t size)
{
Q_ASSERT(size);
Q_ASSERT(size <= freeablePoolSize);
if (Q_UNLIKELY(static_cast<size_t>(m_freeablePoolEnd - m_freeableMemory) < size))
allocateFreeablePool();
void* block = m_freeableMemory;
m_freeableMemory += size;
return block;
}
void* allocateDeletable(size_t size)
{
ParserArenaDeletable* deletable = static_cast<ParserArenaDeletable*>(fastMalloc(size));
m_deletableObjects.append(deletable);
return deletable;
}
void derefWithArena(PassRefPtr<ParserArenaRefCounted>);
bool contains(ParserArenaRefCounted*) const;
ParserArenaRefCounted* last() const;
void removeLast();
bool isEmpty() const;
void reset();
IdentifierArena& identifierArena() { return *m_identifierArena; }
private:
static const size_t freeablePoolSize = 8000;
void* freeablePool();
void allocateFreeablePool();
void deallocateObjects();
char* m_freeableMemory;
char* m_freeablePoolEnd;
OwnPtr<IdentifierArena> m_identifierArena;
Vector<void*> m_freeablePools;
Vector<ParserArenaDeletable*> m_deletableObjects;
Vector<RefPtr<ParserArenaRefCounted> > m_refCountedObjects;
};
}
#endif

View file

@ -1,182 +0,0 @@
/*
* Copyright (C) 2008 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef ResultType_h
#define ResultType_h
namespace JSC {
struct ResultType {
friend struct OperandTypes;
typedef char Type;
static const Type TypeReusable = 1;
static const Type TypeInt32 = 2;
static const Type TypeMaybeNumber = 0x04;
static const Type TypeMaybeString = 0x08;
static const Type TypeMaybeNull = 0x10;
static const Type TypeMaybeBool = 0x20;
static const Type TypeMaybeOther = 0x40;
static const Type TypeBits = TypeMaybeNumber | TypeMaybeString | TypeMaybeNull | TypeMaybeBool | TypeMaybeOther;
explicit ResultType(Type type)
: m_type(type)
{
}
bool isReusable()
{
return m_type & TypeReusable;
}
bool isInt32()
{
return m_type & TypeInt32;
}
bool definitelyIsNumber()
{
return (m_type & TypeBits) == TypeMaybeNumber;
}
bool definitelyIsString()
{
return (m_type & TypeBits) == TypeMaybeString;
}
bool mightBeNumber()
{
return m_type & TypeMaybeNumber;
}
bool isNotNumber()
{
return !mightBeNumber();
}
static ResultType nullType()
{
return ResultType(TypeMaybeNull);
}
static ResultType booleanType()
{
return ResultType(TypeMaybeBool);
}
static ResultType numberType()
{
return ResultType(TypeMaybeNumber);
}
static ResultType numberTypeCanReuse()
{
return ResultType(TypeReusable | TypeMaybeNumber);
}
static ResultType numberTypeCanReuseIsInt32()
{
return ResultType(TypeReusable | TypeInt32 | TypeMaybeNumber);
}
static ResultType stringOrNumberTypeCanReuse()
{
return ResultType(TypeReusable | TypeMaybeNumber | TypeMaybeString);
}
static ResultType stringType()
{
return ResultType(TypeMaybeString);
}
static ResultType unknownType()
{
return ResultType(TypeBits);
}
static ResultType forAdd(ResultType op1, ResultType op2)
{
if (op1.definitelyIsNumber() && op2.definitelyIsNumber())
return numberTypeCanReuse();
if (op1.definitelyIsString() || op2.definitelyIsString())
return stringType();
return stringOrNumberTypeCanReuse();
}
static ResultType forBitOp()
{
return numberTypeCanReuseIsInt32();
}
private:
Type m_type;
};
struct OperandTypes
{
OperandTypes(ResultType first = ResultType::unknownType(), ResultType second = ResultType::unknownType())
{
// We have to initialize one of the int to ensure that
// the entire struct is initialized.
m_u.i = 0;
m_u.rds.first = first.m_type;
m_u.rds.second = second.m_type;
}
union {
struct {
ResultType::Type first;
ResultType::Type second;
} rds;
int i;
} m_u;
ResultType first()
{
return ResultType(m_u.rds.first);
}
ResultType second()
{
return ResultType(m_u.rds.second);
}
int toInt()
{
return m_u.i;
}
static OperandTypes fromInt(int value)
{
OperandTypes types;
types.m_u.i = value;
return types;
}
};
} // namespace JSC
#endif // ResultType_h

View file

@ -1,92 +0,0 @@
/*
* Copyright (C) 2008 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef SourceCode_h
#define SourceCode_h
#include "SourceProvider.h"
#include <wtf/RefPtr.h>
namespace JSC {
class SourceCode {
public:
SourceCode()
: m_provider(0)
, m_startChar(0)
, m_endChar(0)
, m_firstLine(0)
{
}
SourceCode(PassRefPtr<SourceProvider> provider, int firstLine = 1)
: m_provider(provider)
, m_startChar(0)
, m_endChar(m_provider->length())
, m_firstLine(firstLine)
{
}
SourceCode(PassRefPtr<SourceProvider> provider, int start, int end, int firstLine)
: m_provider(provider)
, m_startChar(start)
, m_endChar(end)
, m_firstLine(firstLine)
{
}
UString toString() const
{
if (!m_provider)
return UString();
return m_provider->getRange(m_startChar, m_endChar);
}
bool isNull() const { return !m_provider; }
SourceProvider* provider() const { return m_provider.get(); }
int firstLine() const { return m_firstLine; }
int startOffset() const { return m_startChar; }
int endOffset() const { return m_endChar; }
const UChar* data() const { return m_provider->data() + m_startChar; }
int length() const { return m_endChar - m_startChar; }
private:
RefPtr<SourceProvider> m_provider;
int m_startChar;
int m_endChar;
int m_firstLine;
};
inline SourceCode makeSource(const UString& source, const UString& url = UString(), int firstLine = 1)
{
return SourceCode(UStringSourceProvider::create(source, url), firstLine);
}
} // namespace JSC
#endif // SourceCode_h

View file

@ -1,79 +0,0 @@
/*
* Copyright (C) 2008, 2009 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef SourceProvider_h
#define SourceProvider_h
#include "UString.h"
#include <wtf/RefCounted.h>
namespace JSC {
class SourceProvider : public RefCounted<SourceProvider> {
public:
SourceProvider(const UString& url)
: m_url(url)
{
}
virtual ~SourceProvider() { }
virtual UString getRange(int start, int end) const = 0;
virtual const UChar* data() const = 0;
virtual int length() const = 0;
const UString& url() { return m_url; }
intptr_t asID() { return reinterpret_cast<intptr_t>(this); }
private:
UString m_url;
};
class UStringSourceProvider : public SourceProvider {
public:
static PassRefPtr<UStringSourceProvider> create(const UString& source, const UString& url)
{
return adoptRef(new UStringSourceProvider(source, url));
}
UString getRange(int start, int end) const { return m_source.substr(start, end - start); }
const UChar* data() const { return m_source.data(); }
int length() const { return m_source.size(); }
protected:
UStringSourceProvider(const UString& source, const UString& url)
: SourceProvider(url)
, m_source(source)
{
}
UString m_source;
};
} // namespace JSC
#endif // SourceProvider_h

View file

@ -1,77 +0,0 @@
/*
* Copyright (C) 2003, 2004, 2005, 2006, 2007, 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.
*
*/
#include "Platform.h"
#include "ArgList.h"
#include "JSValue.h"
#include "JSCell.h"
namespace JSC {
void ArgList::getSlice(int startIndex, ArgList& result) const
{
if (startIndex <= 0 || static_cast<unsigned>(startIndex) >= m_argCount) {
result = ArgList(m_args, 0);
return;
}
result = ArgList(m_args + startIndex, m_argCount - startIndex);
}
void MarkedArgumentBuffer::markLists(MarkStack& markStack, ListSet& markSet)
{
ListSet::iterator end = markSet.end();
for (ListSet::iterator it = markSet.begin(); it != end; ++it) {
MarkedArgumentBuffer* list = *it;
markStack.appendValues(reinterpret_cast<JSValue*>(list->m_buffer), list->m_size);
}
}
void MarkedArgumentBuffer::slowAppend(JSValue v)
{
// As long as our size stays within our Vector's inline
// capacity, all our values are allocated on the stack, and
// therefore don't need explicit marking. Once our size exceeds
// our Vector's inline capacity, though, our values move to the
// heap, where they do need explicit marking.
if (!m_markSet) {
// We can only register for explicit marking once we know which heap
// is the current one, i.e., when a non-immediate value is appended.
if (Heap* heap = Heap::heap(v)) {
ListSet& markSet = heap->markListSet();
markSet.add(this);
m_markSet = &markSet;
}
}
if (m_vector.size() < m_vector.capacity()) {
m_vector.uncheckedAppend(v);
return;
}
// 4x growth would be excessive for a normal vector, but it's OK for Lists
// because they're short-lived.
m_vector.reserveCapacity(m_vector.capacity() * 4);
m_vector.uncheckedAppend(v);
m_buffer = m_vector.data();
}
} // namespace JSC

View file

@ -1,237 +0,0 @@
/*
* Copyright (C) 1999-2001 Harri Porten (porten@kde.org)
* Copyright (C) 2003, 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 ArgList_h
#define ArgList_h
#include "Register.h"
#include <wtf/HashSet.h>
#include <wtf/Noncopyable.h>
#include <wtf/Vector.h>
namespace JSC {
class MarkStack;
class MarkedArgumentBuffer : public Noncopyable {
private:
static const unsigned inlineCapacity = 8;
typedef Vector<Register, inlineCapacity> VectorType;
typedef HashSet<MarkedArgumentBuffer*> ListSet;
public:
typedef VectorType::iterator iterator;
typedef VectorType::const_iterator const_iterator;
// Constructor for a read-write list, to which you may append values.
// FIXME: Remove all clients of this API, then remove this API.
MarkedArgumentBuffer()
: m_isUsingInlineBuffer(true)
, m_markSet(nullptr)
#ifndef QT_NO_DEBUG
, m_isReadOnly(false)
#endif
{
m_buffer = m_vector.data();
m_size = 0;
}
// Constructor for a read-only list whose data has already been allocated elsewhere.
MarkedArgumentBuffer(Register* buffer, size_t size)
: m_buffer(buffer)
, m_size(size)
, m_isUsingInlineBuffer(true)
, m_markSet(nullptr)
#ifndef QT_NO_DEBUG
, m_isReadOnly(true)
#endif
{
}
void initialize(Register* buffer, size_t size)
{
Q_ASSERT(!m_markSet);
Q_ASSERT(isEmpty());
m_buffer = buffer;
m_size = size;
#ifndef QT_NO_DEBUG
m_isReadOnly = true;
#endif
}
~MarkedArgumentBuffer()
{
if (m_markSet)
m_markSet->remove(this);
}
size_t size() const { return m_size; }
bool isEmpty() const { return !m_size; }
JSValue at(size_t i) const
{
if (i < m_size)
return m_buffer[i].jsValue();
return jsUndefined();
}
void clear()
{
m_vector.clear();
m_buffer = nullptr;
m_size = 0;
}
void append(JSValue v)
{
Q_ASSERT(!m_isReadOnly);
#if ENABLE(JSC_ZOMBIES)
Q_ASSERT(!v.isZombie());
#endif
if (m_isUsingInlineBuffer && m_size < inlineCapacity) {
m_vector.uncheckedAppend(v);
++m_size;
} else {
// Putting this case all in one function measurably improves
// the performance of the fast "just append to inline buffer" case.
slowAppend(v);
++m_size;
m_isUsingInlineBuffer = false;
}
}
void removeLast()
{
Q_ASSERT(m_size);
m_size--;
m_vector.removeLast();
}
JSValue last()
{
Q_ASSERT(m_size);
return m_buffer[m_size - 1].jsValue();
}
iterator begin() { return m_buffer; }
iterator end() { return m_buffer + m_size; }
const_iterator begin() const { return m_buffer; }
const_iterator end() const { return m_buffer + m_size; }
static void markLists(MarkStack&, ListSet&);
private:
void slowAppend(JSValue);
Register* m_buffer;
size_t m_size;
bool m_isUsingInlineBuffer;
VectorType m_vector;
ListSet* m_markSet;
#ifndef QT_NO_DEBUG
bool m_isReadOnly;
#endif
private:
// Prohibits new / delete, which would break GC.
friend class JSGlobalData;
void* operator new(size_t size)
{
return fastMalloc(size);
}
void operator delete(void* p)
{
fastFree(p);
}
void* operator new[](size_t);
void operator delete[](void*);
void* operator new(size_t, void*);
void operator delete(void*, size_t);
};
class ArgList {
public:
typedef JSValue* iterator;
typedef const JSValue* const_iterator;
ArgList()
: m_args(0)
, m_argCount(0)
{
}
ArgList(JSValue* args, unsigned argCount)
: m_args(args)
, m_argCount(argCount)
{
#if ENABLE(JSC_ZOMBIES)
for (size_t i = 0; i < argCount; i++)
Q_ASSERT(!m_args[i].isZombie());
#endif
}
ArgList(Register* args, int argCount)
: m_args(reinterpret_cast<JSValue*>(args))
, m_argCount(argCount)
{
Q_ASSERT(argCount >= 0);
}
ArgList(const MarkedArgumentBuffer& args)
: m_args(reinterpret_cast<JSValue*>(const_cast<Register*>(args.begin())))
, m_argCount(args.size())
{
}
JSValue at(size_t idx) const
{
if (idx < m_argCount)
return m_args[idx];
return jsUndefined();
}
bool isEmpty() const { return !m_argCount; }
size_t size() const { return m_argCount; }
iterator begin() { return m_args; }
iterator end() { return m_args + m_argCount; }
const_iterator begin() const { return m_args; }
const_iterator end() const { return m_args + m_argCount; }
void getSlice(int startIndex, ArgList& result) const;
private:
JSValue* m_args;
size_t m_argCount;
};
} // namespace JSC
#endif // ArgList_h

Some files were not shown because too many files have changed in this diff Show more