From a065e04d529da1d847b5062a12c46d916408bf32 Mon Sep 17 00:00:00 2001 From: Peter Bengtsson Date: Tue, 8 Dec 2020 21:46:22 -0500 Subject: update based on https://github.com/mdn/yari/issues/2028 --- .../spidermonkey/build_documentation/index.html | 290 - .../projects/spidermonkey/bytecodes/index.html | 30 - .../creating_javascript_jstest_reftests/index.html | 9 - .../creating_javascript_tests/index.html | 77 - .../mozilla/projects/spidermonkey/foss/index.html | 97 - .../getting_spidermonkey_source_code/index.html | 90 - .../projects/spidermonkey/hacking_tips/index.html | 654 -- .../how_to_embed_the_javascript_engine/index.html | 474 -- files/ja/mozilla/projects/spidermonkey/index.html | 102 - .../mozilla/projects/spidermonkey/index/index.html | 10 - .../spidermonkey/internals/bytecode/index.html | 6855 -------------------- .../internals/garbage_collection/index.html | 131 - .../projects/spidermonkey/internals/index.html | 290 - .../internals/thread_safety/index.html | 56 - .../index.html | 376 -- .../spidermonkey/jsapi_cookbook/index.html | 514 -- .../jsapi_reference/alphabetical_list/index.html | 228 - .../spidermonkey/jsapi_reference/index.html | 926 --- .../jsapi_reference/js_compilefile/index.html | 66 - .../jsapi_reference/js_constructobject/index.html | 63 - .../jsapi_reference/js_defineobject/index.html | 126 - .../jsapi_reference/js_destroycontext/index.html | 55 - .../jsapi_reference/js_destroyruntime/index.html | 45 - .../jsapi_reference/js_dumpheap/index.html | 110 - .../jsapi_reference/js_evaluatescript/index.html | 93 - .../jsapi_reference/js_getgcparameter/index.html | 323 - .../jsapi_reference/js_getruntime/index.html | 47 - .../js_getruntimeprivate/index.html | 59 - .../jsapi_reference/js_init/index.html | 35 - .../jsapi_reference/js_lock/index.html | 37 - .../jsapi_reference/js_newcontext/index.html | 93 - .../jsapi_reference/js_newobject/index.html | 104 - .../jsapi_reference/js_newruntime/index.html | 52 - .../jsapi_reference/js_setgczeal/index.html | 141 - .../jsapi_reference/js_shutdown/index.html | 34 - .../jsapi_reference/js_threadsafe/index.html | 114 - .../spidermonkey/jsapi_reference/jsint/index.html | 42 - .../jsapi_reference/jsruntime/index.html | 23 - .../spidermonkey/jsapi_reference/jstype/index.html | 52 - .../spidermonkey/jsapi_user_guide/index.html | 6 - .../spidermonkey/jsdbgapi_reference/index.html | 150 - .../projects/spidermonkey/parser_api/index.html | 1698 ----- .../projects/spidermonkey/releases/52/index.html | 30 - .../projects/spidermonkey/releases/index.html | 34 - .../spidermonkey/shell_global_objects/index.html | 662 -- 45 files changed, 15503 deletions(-) delete mode 100644 files/ja/mozilla/projects/spidermonkey/build_documentation/index.html delete mode 100644 files/ja/mozilla/projects/spidermonkey/bytecodes/index.html delete mode 100644 files/ja/mozilla/projects/spidermonkey/creating_javascript_jstest_reftests/index.html delete mode 100644 files/ja/mozilla/projects/spidermonkey/creating_javascript_tests/index.html delete mode 100644 files/ja/mozilla/projects/spidermonkey/foss/index.html delete mode 100644 files/ja/mozilla/projects/spidermonkey/getting_spidermonkey_source_code/index.html delete mode 100644 files/ja/mozilla/projects/spidermonkey/hacking_tips/index.html delete mode 100644 files/ja/mozilla/projects/spidermonkey/how_to_embed_the_javascript_engine/index.html delete mode 100644 files/ja/mozilla/projects/spidermonkey/index.html delete mode 100644 files/ja/mozilla/projects/spidermonkey/index/index.html delete mode 100644 files/ja/mozilla/projects/spidermonkey/internals/bytecode/index.html delete mode 100644 files/ja/mozilla/projects/spidermonkey/internals/garbage_collection/index.html delete mode 100644 files/ja/mozilla/projects/spidermonkey/internals/index.html delete mode 100644 files/ja/mozilla/projects/spidermonkey/internals/thread_safety/index.html delete mode 100644 files/ja/mozilla/projects/spidermonkey/introduction_to_the_javascript_shell/index.html delete mode 100644 files/ja/mozilla/projects/spidermonkey/jsapi_cookbook/index.html delete mode 100644 files/ja/mozilla/projects/spidermonkey/jsapi_reference/alphabetical_list/index.html delete mode 100644 files/ja/mozilla/projects/spidermonkey/jsapi_reference/index.html delete mode 100644 files/ja/mozilla/projects/spidermonkey/jsapi_reference/js_compilefile/index.html delete mode 100644 files/ja/mozilla/projects/spidermonkey/jsapi_reference/js_constructobject/index.html delete mode 100644 files/ja/mozilla/projects/spidermonkey/jsapi_reference/js_defineobject/index.html delete mode 100644 files/ja/mozilla/projects/spidermonkey/jsapi_reference/js_destroycontext/index.html delete mode 100644 files/ja/mozilla/projects/spidermonkey/jsapi_reference/js_destroyruntime/index.html delete mode 100644 files/ja/mozilla/projects/spidermonkey/jsapi_reference/js_dumpheap/index.html delete mode 100644 files/ja/mozilla/projects/spidermonkey/jsapi_reference/js_evaluatescript/index.html delete mode 100644 files/ja/mozilla/projects/spidermonkey/jsapi_reference/js_getgcparameter/index.html delete mode 100644 files/ja/mozilla/projects/spidermonkey/jsapi_reference/js_getruntime/index.html delete mode 100644 files/ja/mozilla/projects/spidermonkey/jsapi_reference/js_getruntimeprivate/index.html delete mode 100644 files/ja/mozilla/projects/spidermonkey/jsapi_reference/js_init/index.html delete mode 100644 files/ja/mozilla/projects/spidermonkey/jsapi_reference/js_lock/index.html delete mode 100644 files/ja/mozilla/projects/spidermonkey/jsapi_reference/js_newcontext/index.html delete mode 100644 files/ja/mozilla/projects/spidermonkey/jsapi_reference/js_newobject/index.html delete mode 100644 files/ja/mozilla/projects/spidermonkey/jsapi_reference/js_newruntime/index.html delete mode 100644 files/ja/mozilla/projects/spidermonkey/jsapi_reference/js_setgczeal/index.html delete mode 100644 files/ja/mozilla/projects/spidermonkey/jsapi_reference/js_shutdown/index.html delete mode 100644 files/ja/mozilla/projects/spidermonkey/jsapi_reference/js_threadsafe/index.html delete mode 100644 files/ja/mozilla/projects/spidermonkey/jsapi_reference/jsint/index.html delete mode 100644 files/ja/mozilla/projects/spidermonkey/jsapi_reference/jsruntime/index.html delete mode 100644 files/ja/mozilla/projects/spidermonkey/jsapi_reference/jstype/index.html delete mode 100644 files/ja/mozilla/projects/spidermonkey/jsapi_user_guide/index.html delete mode 100644 files/ja/mozilla/projects/spidermonkey/jsdbgapi_reference/index.html delete mode 100644 files/ja/mozilla/projects/spidermonkey/parser_api/index.html delete mode 100644 files/ja/mozilla/projects/spidermonkey/releases/52/index.html delete mode 100644 files/ja/mozilla/projects/spidermonkey/releases/index.html delete mode 100644 files/ja/mozilla/projects/spidermonkey/shell_global_objects/index.html (limited to 'files/ja/mozilla/projects/spidermonkey') diff --git a/files/ja/mozilla/projects/spidermonkey/build_documentation/index.html b/files/ja/mozilla/projects/spidermonkey/build_documentation/index.html deleted file mode 100644 index dd5a4146c2..0000000000 --- a/files/ja/mozilla/projects/spidermonkey/build_documentation/index.html +++ /dev/null @@ -1,290 +0,0 @@ ---- -title: SpiderMonkey のビルド -slug: Mozilla/Projects/SpiderMonkey/Build_Documentation -tags: - - Build documentation - - Guide - - SpiderMonkey -translation_of: Mozilla/Projects/SpiderMonkey/Build_Documentation ---- -
{{SpiderMonkeySidebar("General")}}
- -

SpiderMonkey のビルド

- -

この文書は SpiderMonkey の最新版をソースコードからビルドする方法を解説します。

- -

ビルドを始める前に、必要なツールがインストールされていることを確認してくださいLinux, Windows, Mac, その他の環境 での準備は、それぞれのドキュメントをごらんください。28 より古いバージョンのビルドをする際は、NSPR が追加で必要となります。

- -

また SpiderMonkey 最新版のソースコード も必要です。

- -

非開発者向け (最適化) ビルド

- -

実運用用のために SpiderMonkey をインストールする場合、またはパフォーマンスベンチマークを実行する場合は、これらの手順を使用してください (SpiderMonkey を C++ アプリケーションのライブラリとして使用したい場合、または SpiderMonkey 自体の改善に取り組んでいる場合は、代わりに下記のように開発者/デバッグビルドを行ってください)。

- -
cd js/src
-autoconf2.13
-
-# この名前は、バージョン管理システムで無視させるために "_OPT.OBJ" で終わる必要があります。
-mkdir build_OPT.OBJ
-cd build_OPT.OBJ
-../configure
-# Windows では "mozmake" を使います。
-make
-
- -

これについてのいくつかのメモ:

- - - -
-

メモ: Mac を使用していて、次のようなエラーが表示される場合

- -

"checking whether the C compiler (gcc-4.2  ) works... no
- configure: error: installation or configuration problem: C compiler cannot create executables.
"

- -

次のように設定してみてください。

- -
CC=clang CXX=clang++  ../configure
- -

baldrdash がコンパイルに失敗する可能性もあります。

- -
/usr/local/Cellar/llvm/7.0.1/lib/clang/7.0.1/include/inttypes.h:30:15: fatal error: 'inttypes.h' file not found
-
-/usr/local/Cellar/llvm/7.0.1/lib/clang/7.0.1/include/inttypes.h:30:15: fatal error: 'inttypes.h' file not found, err: true
- -

これは Mohave 以降、ヘッダーが /usr/include にインストールされなくなったためです。コマンドラインツール -> 新機能の下のリリースノートを参照してください。

- -

リリースノートには、この互換性パッケージは近い将来提供されなくなると記載されているので、macOS 上のビルドシステムは SDK のヘッダを探すように適合させる必要があるでしょう。
-
- それまでは、次のことが役に立ちます。

- -
open /Library/Developer/CommandLineTools/Packages/macOS_SDK_headers_for_macOS_10.14.pk
-
-
- -

これにより build-release/dist/bin ディレクトリに js という実行可能ファイルが構築されます。ヘルプページを表示する dist/bin/js --help でテストできます。これで、シェルを実行して試す準備が整いました。

- -

Mac、Linux、または UNIX では、追加のコマンド make install を使用してシステムに SpiderMonkey をインストールできます。これは共有ライブラリを /usr/local/lib に、C ヘッダファイルを usr/local/include に、そして js 実行ファイルを /usr/local/bin にインストールします。

- -

開発者向け(デバッグ用)ビルド

- -

SpiderMonkey 自身の開発やデバッグを目的とする場合、日々のデバッグにはデバッグビルドを、パフォーマンステストには最適化ビルドを、それぞれ別のディレクトリで行うことになります。デバッグビルドを行うには、上記の手順に加えて以下の 3 ステップを行います:

- -
cd js/src
-autoconf-2.13
-
-# This name should end with "_DBG.OBJ" to make the version control system ignore it.
-mkdir build_DBG.OBJ
-cd build_DBG.OBJ
-../configure --enable-debug --disable-optimize
-# Use "mozmake" on Windows
-make
-
- -

JS_GC_ZEAL オプションをつけてビルドすると、zealous ガベージコレクションが有効になります。これはメモリリークに代表されるメモリ関連のデバッグを行う時に有用です。詳細は JS_SetGCZeal() をご覧ください。

- -

この他のビルドオプションについては、上記で作成したビルドディレクトリ内で次のコマンドを実行してください:

- -
../configure --help
-
- -

コンパイルデータベースの生成

- -

一部のツール (IDE、静的アナライザー、リファクタリングツールなど) は、ソフトウェアを構築するために必要なすべての要素の説明を含む compile_commands.json というファイルを使用するため、ツールは構築システムも理解する必要はありません。

- -

SpiderMonkey 設定スクリプトを使用して compile_commands.json を生成するには、次のように CompileDB バックエンドを有効にします。

- -
 ../configure <options> --enable-build-backends=CompileDB,RecursiveMake
-
- -

(RecursiveMake はあなたもビルドできるようになりたいと思うのでそこにあります!)

- -

Windows でのビルド

- -
-

バージョン 28 以降、スレッドセーフビルドがデフォルトとなり、すべての POSIX プラットフォームでそのまま使用できるはずです。したがって、次の手順は Windows を使用している場合、または古いバージョンの SpiderMonkey をコンパイルしている場合にのみ関係があります。

-
- -

The MozillaBuild batch file you used to open your shell (e.g. start-shell-msvc2013.bat or start-shell-msvc2013-x64.bat) determines whether the compiler toolchain will target 32-bit or 64-bit builds. To create a 64-bit build, note that you must configure with --target=x86_64-pc-mingw32 --host=x86_64-pc-mingw32.

- -

Since the POSIX NSPR emulation is not available for Windows, a working version of NSPR must be available to your build. The easiest option is to configure with --enable-nspr-build. This configure option builds the in-tree version of NSPR which is probably what you want; because SpiderMonkey uses newer NSPR symbols, the NSPR that ships with your operating system probably does not work.

- -

If --enable-nspr-build does not work, explicitly tell configure where to find NSPR using the --with-nspr-cflags and --with-nspr-libs configure options. For example, assuming your local NSPR has been installed to C:/mozilla-build/msys/local:

- -
./configure --with-nspr-cflags="-IC:/mozilla-build/msys/local/include" \
-            --with-nspr-libs="C:/mozilla-build/msys/local/lib/libnspr4.a \
-                              C:/mozilla-build/msys/local/lib/libplds4.a \
-                              C:/mozilla-build/msys/local/lib/libplc4.a"
-
- -

If you get symbol loading or dynamic library errors, you can force the correct NSPR to load with:

- -
PATH="$PATH;C:/mozilla-build/msys/local/lib/" ./js
- -

Specifying installation directories

- -

make install puts files in the following directories by default. You can override this by passing options to the configure script:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
What it isWhere it gets putconfigure option
executables, shell scripts/usr/local/bin--bindir
libraries, data/usr/local/lib--libdir
architecture-independent data/usr/local/share--sharedir
C header files/usr/local/include--includedir
- -

For convenience, you can pass the configure script an option of the form --prefix=<PREFIXDIR>, which substitutes <PREFIXDIR> for /usr/local in all the settings above, in one step. This is usually the least troublesome thing to do, as it preserves the typical arrangement of lib, bin, and the rest.

- -
Note: All directories you pass to configure are recorded in the generated makefile, so you don't need to specify them again until you re-run configure.
- -

Building SpiderMonkey as a static library

- -

By default, SpiderMonkey builds as a shared library. However, you can build SpiderMonkey as a static library by specifying the --disable-shared-js flag when you run configure.

- -

Specifying compilers and compiler flags

- -

If you want to use a compiler other than the one the configure script chooses for you by default, you can set the CXX variable in the environment when you run configure. This will save the values you specify in the generated makefile, so once you've set it, you don't need to do so again until you re-run configure.

- -

If you'd like to pass certain flags to the compiler, you can set the CXXFLAGS environment variable when you run configure. For example, if you're using the GNU toolchain, the following will pass the -g3 flag to the compiler, causing it to emit debug information about macros. Then you can use those macros in gdb commands:

- -
$ CXXFLAGS=-g3 $SRC/configure
-...
-checking whether the C++ compiler (c++ -g3 ) works... yes
-...
-$
- -

Cross-compiling options

- -

For cross-compiling you will need a cross-compiling compiler. That tends to be easier with clang as clang has cross-compiling support built in. You may need other libraries though.  For example on debian linux you'll need the following to cross compile from x86_64 to x86.

- -
apt install clang libstdc++-8-dev-i386-cross binutils-i686-gnu zlib1g-dev:i386
- -

You'll also need rust, in addition to having normal rust set up you'll need to add another target to your existing rust toolchain (don't add a new toolchain spidermonkey will use only one toolchain and use it for both host and target code:

- -
rustup target add i686-unknown-linux-gnu
- -

To build a 32-bit version on a 64-bit Linux system, you can use the following:

- -
PKG_CONFIG_LIBDIR=/usr/lib/pkgconfig CC="gcc -m32 -mfpmath=sse -msse -msse2" CXX="g++ -m32 -mfpmath=sse -msse -msse2" AR=ar \
-$SRC/configure --target=i686-pc-linux
- -

Or for clang.

- -
$SRC/configure --target=i686-pc-linux-gnu
- -

To build a 32-bit arm version on a 64-bit Linux system, that runs in the arm simulator, you can use the following:

- -
   AR=ar CC="gcc -m32 -mfpmath=sse -msse -msse2" CXX="g++ -m32 -mfpmath=sse -msse -msse2" \
-    $SRC/configure --target=i686-pc-linux --enable-simulator=arm
- -

To build a 32-bit version on a 64-bit Mac system (the target version is specific to your OS/X SDK), you can use the following:

- -
$SRC/configure --target=i386-apple-darwin16.7.0 # Choose the appropriate SDK version for your version of OS/X
- -

To build a 64-bit version on a 32-bit Mac system (e.g. Mac OS X 10.5), you can use the following:

- -
AR=ar CC="gcc -m64" CXX="g++ -m64" ../configure --target=x86_64-apple-darwin10.0.0
- -

To build a 64-bit Windows version, you can use the following:

- -
$SRC/configure --host=x86_64-pc-mingw32 --target=x86_64-pc-mingw32
- -
Note: You must have started your MozillaBuild shell with the proper -x64.bat script in order for the 64-bit compilers to be in your PATH.
- -

Whatever compiler and flags you pass to configure are recorded in the generated makefile, so you don't need to specify them again until you re-run configure.

- -

Building your application

- -

While "How to build your complete application" is clearly out of scope for this document, here are some tips that will help get you on your way:

- - - -

Using the js-config script

- -

In addition to the SpiderMonkey libraries, header files, and shell, the SpiderMonkey build also produces a shell script named js-config which other build systems can use to find out how to compile code using the SpiderMonkey APIs, and how to link with the SpiderMonkey libraries.

- -
Note: In SpiderMonkey 1.8.5, the js-config script is not generated properly on many platforms. If the instructions below do not work, you can try this workaround.
- -

When invoked with the --cflags option, js-config prints the flags that you should pass to the C compiler when compiling files that use the SpiderMonkey API. These flags ensure the compiler will find the SpiderMonkey header files.

- -
$ ./js-config --cflags # Example output: -I/usr/local/include/js -I/usr/include/nspr
- -

When invoked with the --libs option, js-config prints the flags that you should pass to the C compiler when linking an executable or shared library that uses SpiderMonkey. These flags ensure the compiler will find the SpiderMonkey libraries, along with any libraries that SpiderMonkey itself depends upon (like NSPR).

- -
$ ./js-config --libs # Example output: -L/usr/local/lib -lmozjs -L/usr/lib -lplds4 -lplc4 -lnspr4 -lpthread -ldl -ldl -lm  -lm -ldl
- -

Testing SpiderMonkey

- - - -

Building SpiderMonkey 1.8 or earlier

- -

Use these instructions to build SpiderMonkey from an official source release or from the old CVS repository. To build the latest SpiderMonkey sources from Mercurial, see Building SpiderMonkey above.

- -

SpiderMonkey is easy to build from source if you have the usual Mozilla build prerequisites installed. Before you begin, make sure you have right build tools for your computer: LinuxWindowsMacothers.

- -

First, download a SpiderMonkey source distribution, such as SpiderMonkey 1.8 Release Candidate 1.

- -

To build, use these commands:

- -
tar xvzf js-1.8.0-rc1.tar.gz
-cd js/src
-make -f Makefile.ref
- -

This builds a debug version of SpiderMonkey. All build files are created in a subdirectory named depending on your system (for example,Linux_All_DBG.OBJ if you are on Linux). To install this build on your system, see SpiderMonkey installation instructions.

- -

To build an optimized (non-debug) version of SpiderMonkey:

- -
make BUILD_OPT=1 -f Makefile.ref
- -

To build a thread-safe version of SpiderMonkey:

- -
make JS_DIST=/full/path/to/directory/containing/nspr JS_THREADSAFE=1 -f Makefile.ref
diff --git a/files/ja/mozilla/projects/spidermonkey/bytecodes/index.html b/files/ja/mozilla/projects/spidermonkey/bytecodes/index.html deleted file mode 100644 index a9ddaeee75..0000000000 --- a/files/ja/mozilla/projects/spidermonkey/bytecodes/index.html +++ /dev/null @@ -1,30 +0,0 @@ ---- -title: バイトコード -slug: Mozilla/Projects/SpiderMonkey/Bytecodes -tags: - - SpiderMonkey -translation_of: Mozilla/Projects/SpiderMonkey/Internals/Bytecodes ---- -
{{SpiderMonkeySidebar("Internals")}}
- -

バックグラウンド

- -

SpiderMonkey バイトコードは、JavaScript エンジンで使用される標準形式のコード表現です。JavaScript フロントエンドは、ソーステキストから AST を構築してから、その AST から JSScript データ構造の一部としてスタックベースのバイトコードを生成します。バイトコードは、JSScript データ構造にも含まれているアトムとオブジェクトを (通常は配列インデックスで) 参照できます。

- -

エンジン内では、すべてのバイトコードはスタックフレーム内で実行されます。グローバル (最上位) コードでも eval コードでもスタックフレームが関連付けられています。スタック上のフレームには、いくつかの異なるカテゴリの JavaScript 値 (タグ付き値形式) 用のスペースがあります。単一の JavaScript 値のスペースは「スロット」と呼ばれ、カテゴリは次のとおりです。

- - - -

this のような値と呼び出し先/戻り値を保持する、専用の機能のために予約されているいくつかのスロットもあります。

- -

式スタックにプッシュされた最新の値に対応する "Top of Stack" (TOS) が常にあります。すべてのバイトコードは、この場所に関して暗黙的に機能します。

- -

バイトコードリスト

- -

すべてのオペコードには、実行全体のスタック効果を表すために [-popcount, +pushcount] という注釈が付けられています。

- -

バイトコードのリストは SpiderMonkey の内部: バイトコードの説明ページに移動しました。

diff --git a/files/ja/mozilla/projects/spidermonkey/creating_javascript_jstest_reftests/index.html b/files/ja/mozilla/projects/spidermonkey/creating_javascript_jstest_reftests/index.html deleted file mode 100644 index 5a438b7932..0000000000 --- a/files/ja/mozilla/projects/spidermonkey/creating_javascript_jstest_reftests/index.html +++ /dev/null @@ -1,9 +0,0 @@ ---- -title: JavaScript jstest reftests を作成する -slug: Mozilla/Projects/SpiderMonkey/Creating_JavaScript_jstest_reftests -tags: - - Junk - - NeedsUpdate -translation_of: Mozilla/Projects/SpiderMonkey/Creating_JavaScript_jstest_reftests ---- -

このページにはすぐにコンテンツが表示されます。

diff --git a/files/ja/mozilla/projects/spidermonkey/creating_javascript_tests/index.html b/files/ja/mozilla/projects/spidermonkey/creating_javascript_tests/index.html deleted file mode 100644 index d093c38e42..0000000000 --- a/files/ja/mozilla/projects/spidermonkey/creating_javascript_tests/index.html +++ /dev/null @@ -1,77 +0,0 @@ ---- -title: JavaScript のテストを作成する -slug: Mozilla/Projects/SpiderMonkey/Creating_JavaScript_tests -translation_of: Mozilla/Projects/SpiderMonkey/Creating_JavaScript_tests ---- -
{{SpiderMonkeySidebar("Tests")}}
- -
-

主に 2 つの SpiderMonkey テストスイート: jstests (in js/src/tests) と jit-tests (in js/src/jit-test) があります。詳細については、自動 JavaScript テストの実行を参照してください。

-
- -

新しいテストはどのテストスイートに属しますか?

- -
    -
  1. jit-tests は JIT の実装をテストすることを目的としています。正当性や機能性をテストするテストのみをこれらのスイートに追加してください。
  2. -
  3. jstests is intended for tests of language-visible functionality. Please put tests of functionality into jstests even if related tests are in jit-tests, since jstests are closer to (and more easily converted to) test262 tests. (In fact, the test262 test suite is run as part of jstests.)
  4. -
- -

Practical differences between the two test suites:

- -
    -
- -

jstest

- -
    -
  1. New jstest files should be put the code in the appropriate subdirectory of js/src/tests/non262/, or, under some scenarios, contributed directly to the test262 repository.
  2. -
  3. jstests run in both the shell and the browser (although you can specify that the test should be run in only one of the two locations).
  4. -
  5. jstests automatically load js/src/tests/shell.js before they run, which creates a ton of functions.
  6. -
  7. Read more advice on jstests here.
  8. -
- -

jit-test

- -
    -
  1. New jit-test files should be put in js/src/jit-test/tests/basic or one of the other appropriate subdirectories of jit-test/tests. 
  2. -
  3. jit-tests run only in the shell.
  4. -
  5. jit-tests do not load extra test functionality automatically.
  6. -
- -

新しいテストファイルを書く

- -

Have a look at the existing files and follow what they do. All tests, in both suite, can use the assertEq function.

- -

assertEq(v1, v2[, message])

- -

Check that v1 and v2 are the same value. If they're not, throw an exception (which will cause the test to fail).

- -

If you are writing a jstests, additional testing functionality is provided for you in shell.js files. You can read about them here.

- -

Performance testing and general advice

- -

Do not attempt to test the performance of engine features in the test suite. 

- -

Please keep in mind that the JavaScript test suite is run on a wide variety of wildly varying hardware plaforms, from phones all the way up to servers. Even tests that check for polynomial time complexity will start to fail in a few years when they have sped up enough to run faster than the granularity of the OS scheduler or when run on platforms with higher latencies than your development workstation. These tests will also show up as infrequent oranges on our heavily loaded test machines, lowering the value of our test suite for everyone. Just don't do it, it's never worth it.

- -

Do not add performance tests to the test suite.

- -

It is not generally even possible to tell if the speed of any particular feature is going to be important in the real world without running a real-world benchmark. It is very hard to write a good real-world benchmark. For this reason, the best place to find out if a change is performance sensitive is on arewefastyet.com.

- -

Focus on writing fast, light tests that cover a single feature. There is basically no cost to adding a new test, so add as many feature tests as needed to cover each feature orthogonally. Remember that whenever a test fails, someone -- probably you -- is going to have to figure out what went wrong.

- -

Testing your test

- -

Run your new test locally before checking it in (or posting it for review). Nobody likes patches that include failing tests!

- -

See Running Automated Javascript Tests for instructions on how to run jstests or jit-tests.

- -

It's also a good sanity check to run each new test against an unpatched shell or browser. The test should fail if it's working properly.

- -

Checking in completed tests

- -

Tests are usually reviewed and pushed just like any other code change. Just include the test in your patch.

- -

Security-sensitive tests should not be committed until the corresponding bug has been made public. Instead, ask a SpiderMonkey peer how to proceed.

- -

It is OK under certain circumstances to push new tests to certain repositories without a code review. Don't do this unless you know what you're doing. Ask a SpiderMonkey peer for details.

diff --git a/files/ja/mozilla/projects/spidermonkey/foss/index.html b/files/ja/mozilla/projects/spidermonkey/foss/index.html deleted file mode 100644 index 70ad9afcb6..0000000000 --- a/files/ja/mozilla/projects/spidermonkey/foss/index.html +++ /dev/null @@ -1,97 +0,0 @@ ---- -title: FOSS -slug: Mozilla/Projects/SpiderMonkey/FOSS -tags: - - Guide - - SpiderMonkey -translation_of: Mozilla/Projects/SpiderMonkey/FOSS ---- -
{{SpiderMonkeySidebar}}
- -

自身の SpiderMonkey ベースのオープンソースプロジェクトを追加してください (必要ならばカテゴリを追加してください) !

- -

ラッパー/バインディング

- -

C++

- - - -

Rust

- - - -

GNOME

- - - -

Objective Caml

- - - -

Perl

- - - -

Python

- - - -

wxWidgets

- - - -

Code generators

- - - -

拡張機能

- - - -

その他

- - diff --git a/files/ja/mozilla/projects/spidermonkey/getting_spidermonkey_source_code/index.html b/files/ja/mozilla/projects/spidermonkey/getting_spidermonkey_source_code/index.html deleted file mode 100644 index 3296d837dc..0000000000 --- a/files/ja/mozilla/projects/spidermonkey/getting_spidermonkey_source_code/index.html +++ /dev/null @@ -1,90 +0,0 @@ ---- -title: SpiderMonkeyソースコードの取得 -slug: Mozilla/Projects/SpiderMonkey/Getting_SpiderMonkey_source_code -tags: - - Guide - - SpiderMonkey -translation_of: Mozilla/Projects/SpiderMonkey/Getting_SpiderMonkey_source_code ---- -
{{SpiderMonkeySidebar}}
- -

SpiderMonkey のソースコードは gzip 形式でも直接 Mercurial リポジトリからも入手できます。

- -

gzip で圧縮された SpiderMonkey のソースコードのダウンロード

- -

gzip で圧縮された SpiderMonkey のソースコードを次の URL からダウンロードできます:

- -
http://ftp.mozilla.org/pub/mozilla.org/js/
-
- -

コマンドラインから SpiderMonkey ソースコード ver24.2 をダウンロードして展開する例です:

- -
mkdir mozilla
-cd mozilla
-wget http://ftp.mozilla.org/pub/mozilla.org/js/mozjs-24.2.0.tar.bz2
-tar xjf mozjs-24.2.0.tar.bz2
-
- -

These commands should work on most platforms including Windows, as long as on Windows you are using the MozillaBuild bash shell.

- -

Mercurial から最新の SpiderMonkey ソースコードを入手する

- -

The Mercurial repository at http://hg.mozilla.org/mozilla-central/ hosts the latest SpiderMonkey sources. Mercurial is also known as hg.

- -

The following command line downloads the entire Mozilla repository, including the full change history and a lot of Gecko and Firefox source code that isn't part of SpiderMonkey. It also changes to the SpiderMonkey directory (js/src).

- -
hg clone http://hg.mozilla.org/mozilla-central/
-cd js/src
-
- -

To avoid getting the full change history, click the zip or gz links at http://hg.mozilla.org/index.cgi/mozilla-central/file/tip. This fetches a snapshot of the current Mozilla tree.

- -

If you have problems with the instructions above, you can read the full details of using Mercurial to get Mozilla code here. That page also contains links to several bundles, which can be useful if you have a poor network connection.

- -

Git で最新の SpiderMonkey のソースコードを取得する

- -

The following command line downloads the entire Mozilla repository, including the full change history and a lot of Gecko and Firefox source code that isn't part of SpiderMonkey. It also changes to the SpiderMonkey directory (js/src).

- -
git clone https://github.com/mozilla/gecko-dev.git
-cd gecko-dev/js/src
-
- -

If you want a faster (about 5 times as of January 2015) download, try doing a shallow clone (no version control history).

- -
git clone --depth 1 https://github.com/mozilla/gecko-dev.git
-
- -

If you have any problems check the https://wiki.mozilla.org/Github page.

- -

CVS から古い SpiderMonkey ソースを入手する

- -
Note: You will need to explicitly fetch the JavaScript shell sources even if you currently build another Mozilla project, as there are files specific to the shell that are not normally found in a Mozilla source tree.
- -

Just like when you're fetching any other Mozilla project from CVS, you need to log into the CVS server first. To do this, cd into the base directory you'd like to check out the code into, then enter the following command at your command line:

- -
cvs -d :pserver:anonymous@cvs-mirror.mozilla.org:/cvsroot login
-
- -

When prompted, enter the password anonymous.

- -

Once you've logged in, cd into the root of your CVS tree and enter the following command:

- -
cvs -d :pserver:anonymous@cvs-mirror.mozilla.org:/cvsroot co -l mozilla/js/src mozilla/js/src/config mozilla/js/src/editline mozilla/js/src/fdlibm
-
- -

This checks out all the files needed in order to build the JavaScript shell.

- -

If you also want the regression tests, add this command:

- -
cvs -d :pserver:anonymous@cvs-mirror.mozilla.org:/cvsroot co mozilla/js/tests
-
- -

SpiderMonkey の古いブランチバージョンを入手する

- -

If you want to experiment with a specific branch's version of SpiderMonkey, you need to check out js/src from branch but check out editline and config from trunk:

- -
cvs -d :pserver:anonymous@cvs-mirror.mozilla.org:/cvsroot co -l -r BRANCH_NAME mozilla/js/src mozilla/js/src/fdlibm
-cvs -d :pserver:anonymous@cvs-mirror.mozilla.org:/cvsroot co -l mozilla/js/src/config mozilla/js/src/editline
-
- -

Change BRANCH_NAME to the name of the branch you want to check out. You can use a JavaScript branch name (e.g. JS_1_7_ALPHA_BRANCH) or a Mozilla branch name (e.g. MOZILLA_1_8_BRANCH).

diff --git a/files/ja/mozilla/projects/spidermonkey/hacking_tips/index.html b/files/ja/mozilla/projects/spidermonkey/hacking_tips/index.html deleted file mode 100644 index 933d9d64a4..0000000000 --- a/files/ja/mozilla/projects/spidermonkey/hacking_tips/index.html +++ /dev/null @@ -1,654 +0,0 @@ ---- -title: ハッキングのヒント -slug: Mozilla/Projects/SpiderMonkey/Hacking_Tips -tags: - - SpiderMonkey -translation_of: Mozilla/Projects/SpiderMonkey/Hacking_Tips ---- -
{{SpiderMonkeySidebar("Getting_started")}}
- -

このページには、SpiderMonkey に関連する問題の調査に役立つヒントがいくつか掲載されています。ここに記載されているヒントはすべて、SpiderMonkey のビルドドキュメントの最後に取得された JavaScript シェルを扱っています。2つの部分に分かれており、1つはデバッグに関するセクション、もう1つはドラフト最適化に関するセクションです。これらのヒントの多くは、JS シェルのデバッグビルドにのみ適用されます。それらはリリースビルドでは機能しません。

- -

デバッグのヒント

- -

ヘルプの入手 (JS シェルから)

- -

help 関数を使用して、シェルのすべてのプリミティブ関数のリストを記述します。いくつかの関数は 'os' オブジェクトの下に移動されているので、help(os) はその "namespace" のメンバーだけを簡単に助けます。

- -

関数のバイトコードを取得する (JSシェルから)

- -

シェルには、関数のバイトコードをソースノートとともにダンプするための小さな関数 dis があります。引数がなければ、呼び出し元のバイトコードをダンプします。

- -
js> function f () {
-  return 1;
-}
-js> dis(f);
-flags:
-loc     op
------   --
-main:
-00000:  one
-00001:  return
-00002:  stop
-
-Source notes:
- ofs  line    pc  delta desc     args
----- ---- ----- ------ -------- ------
-  0:    1     0 [   0] newline
-  1:    2     0 [   0] colspan 2
-  3:    2     2 [   2] colspan 9
-
-
- -

関数のバイトコードを取得する (gdbから)

- -

jsopcode.cpp では、js::DisassembleAtPC という名前の関数が使用されています。PC はスクリプトのバイトコードを出力できます。js::DumpScript などのこの関数のいくつかの変種はデバッグに便利です。

- -

JS スタックのプリント (gdbから)

- -

jsobj.cppでは、js::DumpBacktrace という名前の関数が、JS スタックのバックトレース à la gdb を出力します。バックトレースには次の順序で、スタックの深さ、インタープリタフレームポインタ (js/src/vm/Stack.hStackFrame クラスを参照) または IonMonkeyでコンパイルした場合は (nil)、コールロケーションのファイルと行番号、およびカッコの下に実行された JSScript ポインタと jsbytecode ポインタ (pc) が含まれます。

- -
$ gdb --args js
-[…]
-(gdb) b js::ReportOverRecursed
-(gdb) r
-js> function f(i) {
-  if (i % 2) f(i + 1);
-  else f(i + 3);
-}
-js> f(0)
-
-Breakpoint 1, js::ReportOverRecursed (maybecx=0xfdca70) at /home/nicolas/mozilla/ionmonkey/js/src/jscntxt.cpp:495
-495         if (maybecx)
-(gdb) call js::DumpBacktrace(maybecx)
-#0          (nil)   typein:2 (0x7fffef1231c0 @ 0)
-#1          (nil)   typein:2 (0x7fffef1231c0 @ 24)
-#2          (nil)   typein:3 (0x7fffef1231c0 @ 47)
-#3          (nil)   typein:2 (0x7fffef1231c0 @ 24)
-#4          (nil)   typein:3 (0x7fffef1231c0 @ 47)
-[…]
-#25157 0x7fffefbbc250   typein:2 (0x7fffef1231c0 @ 24)
-#25158 0x7fffefbbc1c8   typein:3 (0x7fffef1231c0 @ 47)
-#25159 0x7fffefbbc140   typein:2 (0x7fffef1231c0 @ 24)
-#25160 0x7fffefbbc0b8   typein:3 (0x7fffef1231c0 @ 47)
-#25161 0x7fffefbbc030   typein:5 (0x7fffef123280 @ 9)
-
-
- -

Note, you can do the exact same exercise above using lldb (necessary on OSX after Apple removed gdb) by running lldb -f js then following the remaining steps.

- -

Since SpiderMonkey 48, we have a gdb unwinder.  This unwinder is able to read the frames created by the JIT, and to display the frames which are after these JIT frames.

- -
$ gdb --args out/dist/bin/js ./foo.js
-[…]
-SpiderMonkey unwinder is disabled by default, to enable it type:
-        enable unwinder .* SpiderMonkey
-(gdb) b js::math_cos
-(gdb) run
-[…]
-#0  js::math_cos (cx=0x14f2640, argc=1, vp=0x7fffffff6a88) at js/src/jsmath.cpp:338
-338         CallArgs args = CallArgsFromVp(argc, vp);
-(gdb) enable unwinder .* SpiderMonkey
-(gdb) backtrace 10
-#0  0x0000000000f89979 in js::math_cos(JSContext*, unsigned int, JS::Value*) (cx=0x14f2640, argc=1, vp=0x7fffffff6a88) at js/src/jsmath.cpp:338
-#1  0x0000000000ca9c6e in js::CallJSNative(JSContext*, bool (*)(JSContext*, unsigned int, JS::Value*), JS::CallArgs const&) (cx=0x14f2640, native=0xf89960 , args=...) at js/src/jscntxtinlines.h:235
-#2  0x0000000000c87625 in js::Invoke(JSContext*, JS::CallArgs const&, js::MaybeConstruct) (cx=0x14f2640, args=..., construct=js::NO_CONSTRUCT) at js/src/vm/Interpreter.cpp:476
-#3  0x000000000069bdcf in js::jit::DoCallFallback(JSContext*, js::jit::BaselineFrame*, js::jit::ICCall_Fallback*, uint32_t, JS::Value*, JS::MutableHandleValue) (cx=0x14f2640, frame=0x7fffffff6ad8, stub_=0x1798838, argc=1, vp=0x7fffffff6a88, res=JSVAL_VOID) at js/src/jit/BaselineIC.cpp:6113
-#4  0x00007ffff7f41395 in <<JitFrame_Exit>> ()
-#5  0x00007ffff7f42223 in <<JitFrame_BaselineStub>> ()
-#6  0x00007ffff7f4423d in <<JitFrame_BaselineJS>> ()
-#7  0x00007ffff7f4222e in <<JitFrame_BaselineStub>> ()
-#8  0x00007ffff7f4326a in <<JitFrame_BaselineJS>> ()
-#9  0x00007ffff7f38d5f in <<JitFrame_Entry>> ()
-#10 0x00000000006a86de in EnterBaseline(JSContext*, js::jit::EnterJitData&) (cx=0x14f2640, data=...) at js/src/jit/BaselineJIT.cpp:150
-
- -

Note, when you enable the unwinder, the current version of gdb (7.10.1) does not flush the backtrace. Therefore, the JIT frames do not appear until you settle on the next breakpoint. To work-around this issue you can use the recording feature of gdb, to step one instruction, and settle back to where you came from with the following set of gdb commands:

- -
(gdb) record full
-(gdb) si
-(gdb) record goto 0
-(gdb) record stop
-
- -

If you have a core file, you can use the gdb unwinder the same way, or do everything from the command line as follow:

- -
$ gdb -ex 'enable unwinder .* SpiderMonkey' -ex 'bt 0' -ex 'thread apply all backtrace' -ex 'quit' out/dist/bin/js corefile
-
- -

The gdb unwinder is supposed to be loaded by dist/bin/js-gdb.py and load python scripts which are located in js/src/gdb/mozilla under gdb. If gdb does not load the unwinder by default, you can force it to, by using the source command with the js-gdb.py file.

- -

生成されたコードにブレークポイントを設定する (gdb, x86 / x86-64, arm から)

- -

To set a breakpoint the generated code of a specific JSScript compiled with IonMonkey. Set a breakpoint on the instruction you are interested in. If you have no precise idea which function you are looking at, you can set a breakpoint on the js::ion::CodeGenerator::visitStart function.  Optionally, a condition on the ins->id() of the LIR instruction can be added to select precisely the instruction you are looking for. Once the breakpoint is on CodeGenerator function of the LIR instruction, add a command to generate a static breakpoint in the generated code.

- -
$ gdb --args js
-[…]
-(gdb) b js::ion::CodeGenerator::visitStart
-(gdb) command
->call masm.breakpoint()
->continue
->end
-(gdb) r
-js> function f(a, b) { return a + b; }
-js> for (var  i = 0; i < 100000; i++) f(i, i + 1);
-
-Breakpoint 1, js::ion::CodeGenerator::visitStart (this=0x101ed20, lir=0x10234e0)
-    at /home/nicolas/mozilla/ionmonkey/js/src/ion/CodeGenerator.cpp:609
-609     }
-
-Program received signal SIGTRAP, Trace/breakpoint trap.
-0x00007ffff7fb165a in ?? ()
-(gdb)
-
-
- -

Once you hit the generated breakpoint, you can replace it by a gdb breakpoint to make it conditional, the procedure is to first replace the generated breakpoint by a nop instruction, and to set a breakpoint at the address of the nop.

- -
(gdb) x /5i $pc - 1
-   0x7ffff7fb1659:      int3
-=> 0x7ffff7fb165a:      mov    0x28(%rsp),%rax
-   0x7ffff7fb165f:      mov    %eax,%ecx
-   0x7ffff7fb1661:      mov    0x30(%rsp),%rdx
-   0x7ffff7fb1666:      mov    %edx,%ebx
-
-(gdb) # replace the int3 by a nop
-(gdb) set *(unsigned char *) ($pc - 1) = 0x90
-(gdb) x /1i $pc - 1
-   0x7ffff7fb1659:      nop
-
-(gdb) # set a breakpoint at the previous location
-(gdb) b *0x7ffff7fb1659
-Breakpoint 2 at 0x7ffff7fb1659
-
-
- -

イオン生成アセンブリコードのプリント (gdb から)

- -

If you want to look at the assembly code generated by IonMonkey, you can follow this procedure:

- - - -

Here is an example. It might be simpler to use the CodeGenerator::link lineno instead of the full qualified name to put the breakpoint. Let's say that the line number of this function is 4780, for instance:

- -
(gdb) b CodeGenerator.cpp:4780
-Breakpoint 1 at 0x84cade0: file /home/code/mozilla-central/js/src/ion/CodeGenerator.cpp, line 4780.
-(gdb) r
-Starting program: /home/code/mozilla-central/js/src/32-release/js -f /home/code/jaeger.js
-[Thread debugging using libthread_db enabled]
-Using host libthread_db library "/lib/x86_64-linux-gnu/libthread_db.so.1".
-[New Thread 0xf7903b40 (LWP 12563)]
-[New Thread 0xf6bdeb40 (LWP 12564)]
-Run#0
-
-Breakpoint 1, js::ion::CodeGenerator::link (this=0x86badf8)
-    at /home/code/mozilla-central/js/src/ion/CodeGenerator.cpp:4780
-4780    {
-(gdb) n
-4781        JSContext *cx = GetIonContext()->cx;
-(gdb) n
-4783        Linker linker(masm);
-(gdb) n
-4784        IonCode *code = linker.newCode(cx, JSC::ION_CODE);
-(gdb) n
-4785        if (!code)
-(gdb) p code->code_
-$1 = (uint8_t *) 0xf7fd25a8 "\201", <incomplete sequence \354\200>
-(gdb) x/2i 0xf7fd25a8
-   0xf7fd25a8:    sub    $0x80,%esp
-   0xf7fd25ae:    mov    0x94(%esp),%ecx
-
-
- -

On arm, the compiled JS code will always be ARM machine code, whereas spidermonkey itself is frequently Thumb2.  Since there isn't debug info for the jitted code, you will need to tell gdb that you are looking at ARM code:

- -
(gdb) set arm force-mode arm
-
- -

Or you can wrap the x command in your own command:

- -
def xi
-    set arm force-mode arm
-    eval "x/%di %d", $arg0, $arg1
-    set arm force-mode auto
-end
-
-
- -

Printing asm.js/wasm generated assembly code (from gdb)

- - - -
// Call the per-exported-function trampoline created by GenerateEntry.                                                                   │
-auto funcPtr = JS_DATA_TO_FUNC_PTR(ExportFuncPtr, codeBase() + func.entryOffset());                                                      │
-if (!CALL_GENERATED_2(funcPtr, exportArgs.begin(), &tlsData_))                                                                           │
-    return false;   
- - - -
   0x7ffff7ff6000:    push   %r15
-   0x7ffff7ff6002:    push   %r14
-   0x7ffff7ff6004:    push   %r13
-   0x7ffff7ff6006:    push   %r12
-   0x7ffff7ff6008:    push   %rbp
-   0x7ffff7ff6009:    push   %rbx
-   0x7ffff7ff600a:    movabs $0xea4f80,%r10
-   0x7ffff7ff6014:    mov    0x178(%r10),%r10
-   0x7ffff7ff601b:    mov    %rsp,0x40(%r10)
-   0x7ffff7ff601f:    mov    (%rsi),%r15
-   0x7ffff7ff6022:    mov    %rdi,%r10
-   0x7ffff7ff6025:    push   %r10
-   0x7ffff7ff6027:    test   $0xf,%spl
-   0x7ffff7ff602b:    je     0x7ffff7ff6032
-   0x7ffff7ff6031:    int3
-   0x7ffff7ff6032:    callq  0x7ffff7ff5000     <------ right here
- - - -

Finding the script of Ion generated assembly (from gdb)

- -

When facing a bug in which you are in the middle of IonMonkey generated code, first thing to note, is that gdb's backtrace is not reliable, because the generated code does not keep a frame pointer. To figure it out you have to read the stack to infer the IonMonkey frame.

- -
(gdb) x /64a $sp
-[…]
-0x7fffffff9838: 0x7ffff7fad2da  0x141
-0x7fffffff9848: 0x7fffef134d40  0x2
-[…]
-(gdb) p (*(JSFunction**) 0x7fffffff9848)->u.i.script_->lineno
-$1 = 1
-(gdb) p (*(JSFunction**) 0x7fffffff9848)->u.i.script_->filename
-$2 = 0xff92d1 "typein"
-
- -

The stack is order as defined in js/src/ion/IonFrames-x86-shared.h, it is composed of the return address, a descriptor (a small value), the JSFunction (if it is even) or a JSScript (if the it is odd, remove it to dereference the pointer) and the frame ends with the number of actual arguments (a small value too). If you want to know at which LIR the code is failing at, the js::ion::CodeGenerator::generateBody function can be intrumented to dump the LIR id before each instruction.

- -
for (; iter != current->end(); iter++) {
-    IonSpew(IonSpew_Codegen, "instruction %s", iter->opName());
-    […]
-
-    masm.store16(Imm32(iter->id()), Address(StackPointer, -8)); // added
-    if (!iter->accept(this))
-        return false;
-
-    […]
-}
- -

This modification will add an instruction which abuse the stack pointer to store an immediate value (the LIR id) to a location which would never be generated by any sane compiler. Thus when dumping the assembly under gdb, this kind of instructions would be easily noticeable.

- -

Viewing the MIRGraph of Ion/Odin compilations (from gdb)

- -

With gdb instrumentation, we can call iongraph program within gdb when the execution is stopped.  This instrumentation adds an iongraph command when provided with an instance of a MIRGenerator*, will call iongraph, graphviz and your prefered png viewer to display the MIR graph at the precise time of the execution.  To find MIRGenetator* instances, is best is to look up into the stack for OptimizeMIR, or CodeGenerator::generateBodyOptimizeMIR function has a mir argument, and the CodeGenerator::generateBody function has a member this->gen.

- -
(gdb) bt
-#0  0x00000000007eaad4 in js::InlineList<js::jit::MBasicBlock>::begin() const (this=0x33dbbc0) at …/js/src/jit/InlineList.h:280
-#1  0x00000000007cb845 in js::jit::MIRGraph::begin() (this=0x33dbbc0) at …/js/src/jit/MIRGraph.h:787
-#2  0x0000000000837d25 in js::jit::BuildPhiReverseMapping(js::jit::MIRGraph&) (graph=...) at …/js/src/jit/IonAnalysis.cpp:2436
-#3  0x000000000083317f in js::jit::OptimizeMIR(js::jit::MIRGenerator*) (mir=0x33dbdf0) at …/js/src/jit/Ion.cpp:1570
-…
-(gdb) frame 3
-#3  0x000000000083317f in js::jit::OptimizeMIR(js::jit::MIRGenerator*) (mir=0x33dbdf0) at …/js/src/jit/Ion.cpp:1570
-(gdb) iongraph mir
- function 0 (asm.js compilation): success; 1 passes.
-/* open your png viewer with the result of iongraph */
- -

This gdb instrumentation is supposed to work with debug builds, or with optimized build compiled with --enable-jitspew configure flag. External programs such as iongraph, dot, and your png viewer are search into the PATH, otherwise custom one can either be configured with environment variables (GDB_IONGRAPH, GDB_DOT, GDB_PNGVIEWER) before starting gdb, or with gdb parameters  (set iongraph-bin <path>, set dot-bin <path>, set pngviewer-bin <path>) within gdb.

- -

Enabling GDB instrumentation may require launching a JS shell executable that shares a directory with a file name "js-gdb.py". If js/src/js does not provide the "iongraph" command, try js/src/shell/js. GDB may complain that ~/.gdbinit requires modification to authorize user scripts, and if so will print out directions.

- -

Break on valgrind errors

- -

Sometimes, a bug can be reproduced under valgrind but hardly under gdb.  One way to investigate is to let valgrind start gdb for you, the other way documented here is to let valgrind act as a gdb server which can be manipulated from the gdb remote.

- -
$ valgrind --smc-check=all-non-file --vex-iropt-register-updates=allregs-at-mem-access --vgdb-error=0 ./js …
- -

This command will tell you how to start gdb as a remote. Be aware that functions which are usually dumping some output will do it in the shell where valgrind is started and not in the shell where gdb is started. Thus functions such as js::DumpBacktrace, when called from gdb, will print their output in the shell containing valgrind.

- -

Adding spew for Compilations & Bailouts & Invalidations (from gdb)

- -

If you are in rr, and forgot to record with the spew enabled with IONFLAGS or because this is an optimized build, then you can add similar spew with extra breakpoints within gdb.  gdb has the ability to set breakpoints with commands, but a simpler / friendlier version is to use dprintf, with a location, and followed by printf-like arguments.

- -
(gdb) dprintf js::jit::IonBuilder::IonBuilder, "Compiling %s:%d:%d-%d\n", info->script_->scriptSource()->filename_.mTuple.mFirstA, info->script_->lineno_, info->script_->sourceStart_, info->script_->sourceEnd_
-Dprintf 1 at 0x7fb4f6a104eb: file /home/nicolas/mozilla/contrib-push/js/src/jit/IonBuilder.cpp, line 159.
-(gdb) cond 1 inliningDepth == 0
-(gdb) dprintf js::jit::BailoutIonToBaseline, "Bailout from %s:%d:%d-%d\n", iter.script()->scriptSource()->filename_.mTuple.mFirstA, iter.script()->lineno_, iter.script()->sourceStart_, iter.script()->sourceEnd_
-Dprintf 2 at 0x7fb4f6fe43dc: js::jit::BailoutIonToBaseline. (2 locations)
-(gdb) dprintf Ion.cpp:3196, "Invalidate %s:%d:%d-%d\n", co->script_->scriptSource()->filename_.mTuple.mFirstA, co->script_->lineno_, co->script_->sourceStart_, co->script_->sourceEnd_
-Dprintf 3 at 0x7fb4f6a0b62a: file /home/nicolas/mozilla/contrib-push/js/src/jit/Ion.cpp, line 3196.
-(gdb) continue
-Compiling self-hosted:650:20470-21501
-Bailout from self-hosted:20:403-500
-Invalidate self-hosted:20:403-500
-
- -

Note: the line 3196, listed above, corresponds to the location of the Jit spew inside jit::Invalidate function.

- -

ハッキングのヒント

- -

Benchmarking (shell)

- -

AreWeFastYet.com display the benchmark results of the JavaScript shell, and browser for B2G.  These benchmarks are publicly recognized benchmarks suggested by other companies and are used as a metric to evaluate how fast JavaScript engines.  This tool is maintained by the JavaScript Team, to find regressions and to compare SpiderMonkey with other JavaScript engines when possible.  To run these benchmarks localy, you can clone AreWeFastYet sources and look inside the benchmarks directory to run individual benchmarks with your JS shell.

- -

Using the Gecko Profiler (browser / xpcshell)

- -

see the section dedicated to profiling with the gecko profiler. This method of profiling has the advantage of mixing the JavaScript stack with the C++ stack, which is useful to analyze library function issues.  One tip is to start looking at a script with an inverted JS stack to locate the most expensive JS function, then to focus on the frame of this JS function, and to remove the inverted stack and look at C++ part of this function to determine from where the cost is coming from.

- -

Using the JIT Inspector (browser)

- -

Install the JIT Inspector addon in your browser. This addon provides estimated cost of IonMonkey , the Baseline compiler, and the interpreter. In addition it provides a clean way to analyze if instructions are inferred as being monomorphic or polymorphic in addition to the number of time each category of type has been observed.

- -

Using the TraceLogger (JS shell / browser)

- -

Create graphs showing time spent in which engine and which function like this.

- -

Whenever running a testcase the file "tl-data.json" and several "tl-*" files get created in the "/tmp" directory. (Per proces a "tl-data-*PID*.json" file and per thread a "tl-tree.*PID*.*ID*.tl", "tl-event.*PID*.*ID*.tl" and "tl-dict.*PID*.*ID*.json" file). These files contain all information to create a tracelogger graph. On https://github.com/h4writer/tracelogger you can find the instructions to create the graph (Tools V2 > 1. Creating a tracelogging graph).

- -

Note 1: when you are doing this from "file:///" you will probably get a security warning in the console. This is because firefox doesn't allow loading files from the harddisk using httprequest, even when the file loading the file is on the harddisk. There are two solutions. One is to create a localhost server and serving the files there. The simplest way to do this is to run python -m SimpleHTTPServer from within the above directory. The other being disable this check in "about:config", by temporarily switching "security.fileuri.strict_origin_policy" to false

- -

Note 2: The files can be very big and take a long time to load in the browser. Therefore it might be good to reduce the logged file. This will remove entries that took only a minor time (=entries that will only show up with les than 1px). This can be done with the reduce.py script in  https://github.com/haytjes/tracelogger/tree/master/tools_v2. You need to download "engine.js", "reduce.py", "reduce.js", "reduce-tree.js" and "reduce-corrections.js". Running this tool is a matter of running "python reduce.py JS_SHELL /tmp/tl-data.json tl-reduced". Where JS_SHELL is a real shell.

- -

Using callgrind (JS shell)

- -

As SpiderMonkey just-in-time compiler are rewriting the executed program, valgrind should be informed from the command line by adding --smc-check=all-non-file.

- -
$ valgrind --tool=callgrind --callgrind-out-file=bench.clg \
-     --smc-check=all-non-file --vex-iropt-register-updates=allregs-at-mem-access ./js ./run.js
-
- -

The output file can then be use with kcachegrind which provides a graphical view of the call graph.

- -

Using IonMonkey spew (JS shell)

- -

IonMonkey spew is extremely verbose (not as much as the INFER spew), but you can filter it to focus on the list of compiled scripts or channels, IonMonkey spew channels can be selected with the IONFLAGS environment variable, and compilation spew can be filtered with IONFILTER.

- -

IONFLAGS contains the names of each channel separated by commas. The logs channel produces 2 files in /tmp/, one (/tmp/ion.json) made to be used with iongraph (made by Sean Stangl) and another one (/tmp/ion.cfg) made to be used with c1visualizer. These tools will show the MIR & LIR steps done by IonMonkey during the compilation. If you would like to use iongraph, you must install Graphviz.

- -

Compilation logs and spew can be filtered with the IONFILTER environment variable which contains locations as output in other spew channels. Multiple locations can be separated with comma as a separator of locations.

- -
$ IONFILTER=pdfjs.js:16934 IONFLAGS=logs,scripts,osi,bailouts ./js --ion-offthread-compile=off ./run.js 2>&1 | less
- -

The bailouts channel is likely to be the first thing you should focus on, because this means that something does not stay in IonMonkey and fallback to the interpreter. This channel output locations (as returned by the id() function of both instructions) of the latest MIR and the latest LIR phases. These locations should correspond to phases of the logs and a filter can be used to remove uninteresting functions.

- -

Using the ARM simulator

- -

The ARM simulator can be used to test the ARM JIT backend on x86/x64 hardware. An ARM simulator build is an x86 shell (or browser) with the ARM JIT backend. Instead of entering JIT code, it runs it in a simulator (interpreter) for ARM code. To use the simulator, compile an x86 shell (32-bit, x64 doesn't work as we use a different Value format there), and pass --enable-arm-simulator to configure. For instance, on a 64-bit Linux host you can use the following configure command to get an ARM simulator build:

- -
AR=ar CC="gcc -m32" CXX="g++ -m32" ../configure --target=i686-pc-linux --enable-debug --disable-optimize --enable-threadsafe --enable-simulator=arm
- -

Or on OS X:

- -
  $ AR=ar CC="clang -m32" CXX="clang++ -m32" ../configure --target=i686-apple-darwin10.0.0 --enable-debug --disable-optimize --enable-threadsafe --enable-arm-simulator
- -

An --enable-debug --enable-optimize build is recommended if you want to run jit-tests or jstests.

- -

Use the VIXL Debugger in the simulator (arm64)

- -

Set a breakpoint (see the comments above about masm.breakpoint()) and run with the environment variable USE_DEBUGGER=1. This will then drop you into a simple debugger provided with VIXL, the ARM simulator technology used for arm64 simulation.

- -

Use the Simulator Debugger for arm32

- -

The same instructions for arm64 in the preceeding section apply, but the environment variable differs: Use ARM_SIM_DEBUGGER=1.

- -

Building the browser with the ARM simulator

- -

You can also build the entire browser with the ARM simulator backend, for instance to reproduce browser-only JS failures on ARM. Make sure to build a browser for x86 (32-bits) and add this option to your mozconfig file:

- -
ac_add_options --enable-arm-simulator
-
- -

If you are under an Ubuntu or Debian 64-bits distribution and you want to build a 32-bits browser, it might be hard to find the relevant 32-bits dependencies. You can use padenot's scripts which will magically setup a chrooted 32-bits environment and do All The Things (c) for you (you just need to modify the mozconfig file).

- -

Using rr on a test

- -

Get the command line for your test run using -s:

- -
./jit_test.py -s $JS_SHELL saved-stacks/async.js
- -

Insert 'rr' before the shell invocation:

- -
rr $JS_SHELL -f $JS_SRC/jit-test/lib/prolog.js --js-cache $JS_SRC/jit-test/.js-cache -e "const platform='linux2'; const libdir='$JS_SRC/jit-test/lib/'; const scriptdir='$JS_SRC/jit-test/tests/saved-stacks/'" -f $JS_SRC/jit-test/tests/saved-stacks/async.js
- -

(note that the above is an example; simply setting JS_SHELL and JS_SRC will not work). Or if this is an intermittent, run it in a loop capturing an rr log for every one until it fails:

- -
n=1; while rr ...same.as.above...; do echo passed $n; n=$(( $n + 1 )); done
- -

Wait until it hits a failure. Now you can run rr replay to replay that last (failed) run under gdb.

- -

rr with reftest

- -

To break on the write of a differing pixel:

- -
    -
  1. Find the X/Y of a pixel that differs
  2. -
  3. Use 'run Z' where Z is the mark in the log for TEST-START. For example in '[rr 28496 607198]REFTEST TEST-START | file:///home/bgirard/mozilla-central/tree/image/test/reftest/bmp/bmpsuite/b/wrapper.html?badpalettesize.bmp' Z would be 607198.
  4. -
  5. break 'mozilla::dom::CanvasRenderingContext2D::DrawWindow(nsGlobalWindow&, double, double, double, double, nsAString_internal const&, unsigned int, mozilla::ErrorResult&)'
  6. -
  7. cont
  8. -
  9. break 'PresShell::RenderDocument(nsRect const&, unsigned int, unsigned int, gfxContext*)'
  10. -
  11. set print object on
  12. -
  13. set $x = <YOUR X VALUE>
  14. -
  15. set $y = <YOUR Y VALUE>
  16. -
  17. print &((cairo_image_surface_t*)aThebesContext->mDT.mRawPtr->mSurface).data[$y * ((cairo_image_surface_t*)aThebesContext->mDT.mRawPtr->mSurface).stride + $x * ((cairo_image_surface_t*)aThebesContext->mDT.mRawPtr->mSurface).depth / 8]
  18. -
  19. -

    watch *(char*)<ADDRESS OF PREVIOUS COMMAND> (NOTE: If you set a watch on the previous expression gdb will watch the expression and run out of watchpoint)

    -
  20. -
- -

rr with emacs

- -

Within emacs, do M-x gud-gdb and replace the command line with rr replay. When gdb comes up, enter

- -
set annot 1
- -

to get it to emit file location information so that emacs will pop up the corresponding source. Note that if you reverse-continue over a SIGSEGV and you're using the standard .gdbinit that sets a catchpoint for that signal, you'll get an additional stop at the catchpoint. Just reverse-continue again to continue to your breakpoints or whatever.

- -

[Hack] Replacing one instruction

- -

To replace one specific instruction, you can use in visit function of each instruction the JSScript filename in lineno fields as well as the id() of the LIR / MIR instructions.  The JSScript can be obtained from info().script().

- -
bool
-CodeGeneratorX86Shared::visitGuardShape(LGuardShape *guard)
-{
-    if (info().script()->lineno == 16934 && guard->id() == 522) {
-        [… another impl only for this one …]
-        return true;
-    }
-    [… old impl …]
-
- -

[Hack] Spewing all compiled code

- -

I usually just add this to the apropriate executableCopy.

- -
    if (getenv("INST_DUMP")) {
-        char buf[4096];
-        sprintf(buf, "gdb /proc/%d/exe %d -batch -ex 'set pagination off' -ex 'set arm force-mode arm' -ex 'x/%di %p' -ex 'set arm force-mode auto'", getpid(), getpid(), m_buffer.size() / 4, buffer);
-        system(buf);
-    }
-
-
- -

If you aren't running on arm, you should omit the -ex 'set arm force-mode arm' and -ex 'set arm force-mode auto'.  And you should change the size()/4 to be something more apropriate for your architecture.

- -

Benchmarking with sub-milliseconds (JS shell)

- -

In the shell we have 2 simple ways to benchmark a script, we can either use the -b shell option (--print-timing) which will evaluate a script given on the command line without any need to instrument the benchmark and print an extra line showing the run-time of the script.  The other way is to wrap the section that you want to measure with the dateNow() function call which returns the number of milliseconds, with a decimal part for sub-milliseconds.

- -
js> dateNow() - dateNow()
--0.0009765625
-
- -

Benchmarking with sub-milliseconds (browser)

- -

In a simillar way as dateNow() in the JS shell, you can use performance.now() in the JavaScript code of a page.

- -

Dumping the JavaScript heap

- -

From the shell, you can call the dumpHeap before Firefox  function to dump out all GC things (reachable and unreachable) that are present in the heap. By default the function writes to stdout, but a filename can be specified as an argument.

- -

Example output might look as follows:

- -
0x1234abcd B global object
-==========
-# zone 0x56789123
-# compartment http://gmail.com [in zone 0x56789123]
-# compartment http://gmail.com/iframe [in zone 0x56789123]
-# arena allockind=3 size=64
-0x1234abcd B object
-> 0x1234abcd B prop1
-> 0xabcd1234 W prop2
-0xabcd1234 W object
-> 0xdeadbeef B prop3
-# arena allockind=5 size=72
-0xdeadbeef W object
-> 0xabcd1234 W prop4 
- -

The output is textual. The first section of the file contains a list of roots, one per line. Each root has the form "0xabcd1234 <color> <description>", where <color> is the color of the given GC thing (B for black, G for gray, W for white) and <description> is a string. The list of roots ends with a line containing "==========".

- -

After the roots come a series of zones. A zone starts with several "comment lines" that start with hashes. The first comment declares the zone. It is followed by lines listing each compartment within the zone. After all the compartments come arenas, which is where the GC things are actually stored. Each arena is followed by all the GC things in the arena. A GC thing starts with a line giving its address, its color, and the thing kind (object, function, whatever). After this come a list of addresses that the GC thing points to, each one starting with ">".

- -

It's also possible to dump the JavaScript heap from C++ code (or from gdb) using the js::DumpHeap function. It is part of jsfriendapi.h and it is available in release builds.

- -

Inspecting MIR objects within a debugger

- -

For MIRGraph, MBasicBlock, and MDefinition and its subclasses (MInstruction, MConstant, etc.), call the dump member function.

- -
  (gdb) call graph->dump()
-
-  (gdb) call block->dump()
-
-  (gdb) call def->dump()
-
-
- -

Benchmarking without a Phone

- -

If you do not have a mobile device or prefer to test on your desktop first, you will need to downgrade your computer such as it is able to run programs as fast as-if they were running on a phone.

- -

On Linux, you can manage the resources available to one program by using cgroup, and to do you can install libcgroup which provides some convenient tools such as cgexec to wrap the program that you want to benchmark.

- -

The following list of commands is used to create 3 control groups. The top-level control group is just to group the mask and the negate-mask. The mask control group is used to run the program that we want to benchmark. The negate-mask control group is used to reserve resources which might be used by the other program if not reserved.

- -
  $ sudo cgcreate -a nicolas:users -t nicolas:users -g cpuset,cpu,memory:/benchmarks
-  $ cgcreate -a nicolas:users -t nicolas:users -g cpuset,cpu,memory:/benchmarks/mask
-  $ cgcreate -a nicolas:users -t nicolas:users -g cpuset,cpu,memory:/benchmarks/negate-mask
-
- -

Then we restrict programs of these groups to the first core of the CPU. This is a list of cpu, which means that we can allocate 2 cores by doing 0-1 instead of 0.

- -
  $ cgset -r cpuset.cpus=0 /benchmarks
-  $ cgset -r cpuset.cpus=0 /benchmarks/mask
-  $ cgset -r cpuset.cpus=0 /benchmarks/negate-mask
-
- -

Then we restrict programs of these groups to the first memory node. Most of the time you will only have one, otherwise you should read what is the best setting to set here. If this is not set, you will have some error when you will try to write a pid in /sys/fs/cgroup/cpuset/benchmarks/mask/tasks while running cgexec.

- -
  $ cgset -r cpuset.mems=0 /benchmarks
-  $ cgset -r cpuset.mems=0 /benchmarks/mask
-  $ cgset -r cpuset.mems=0 /benchmarks/negate-mask
-
- -

Then we limit the performance of the CPU, as a proportion such as the result approximately correspond to what you might have if you were running on a phone. For example an Unagi is approximately 40 times slower than my computer. So I allocate 1/40 for the mask, and 39/40 for the negate-mask.

- -
  $ cgset -r cpu.shares=1 /benchmarks/mask
-  $ cgset -r cpu.shares=39 /benchmarks/negate-mask
-
- -

Then we limit the memory available, to what would be available on the phone. For example an Unagi you want to limit this to 512 MB. As there is no swap, on this device, we set the memsw (Memory+Swap) to the same value.

- -
  $ cgset -r memory.limit_in_bytes=$((512*1024*1024)) /benchmarks/mask
-  $ cgset -r memory.memsw.limit_in_bytes=$((512*1024*1024)) /benchmarks/mask
-
- -

And finally, we run the program that we want to benchmark after the one which is consuming resources. In case of the JS Shell we might also want to set the amount of memory available to change the GC settings as if we were running on a Firefox OS device.

- -
  $ cgexec -g 'cpuset,cpu,memory:/benchmarks/negate-mask' yes > /dev/null &
-  $ cgexec -g 'cpuset,cpu,memory:/benchmarks/mask' ./js --available-memory=512 ./run.js
-
- -

How to debug oomTest() failures

- -

The oomTest() function executes a piece of code many times, simulating an OOM failure at each successive allocation it makes.  It's designed to highlight incorrect OOM handling and this may show up as a crash or assertion failure at some later point.

- -

When debugging such a crash the most useful thing is to locate the last simulated alloction failure, as it's usually this that has caused the subsequent crash.

- -

My workflow for doing this is as follows:

- -
    -
  1. Build a version of the engine with --enable-debug and --enable-oom-breakpoint configure flags.
  2. -
  3. Set the environment variable OOM_VERBOSE=1 and reproduce the failure.  This will print an allocation count at each simulated failure.  Note the count of the last allocation.
  4. -
  5. Run the engine under a debugger and set a breakpoint on the function js_failedAllocBreakpoint.
  6. -
  7. Run the program and continue the necessary number of times until you reach the final allocation. -
      -
    • e.g. in lldb, if the allocation failure number shown is 1500, run `continue -i 1498` (subtracted 2 because we've already hit it once and don't want to skip the last). Drop "-i" for gdb.
    • -
    -
  8. -
  9. Dump a backtrace.  This should show you the point at which the OOM is incorrectly handled, which will be a few frames up from the breakpoint.
  10. -
- -

Note: if you are on linux it may be simpler to use rr.

- -

Some guidelines for handling OOM that lead to failures when they are not followed:

- -
    -
  1. Check for allocation failure! -
      -
    • Fallible allocations should always must be checked and handled, at a minimum by returning a status indicating failure to the caller.
    • -
    -
  2. -
  3. Report OOM to the context if you have one -
      -
    • If a function has a JSContext* argument, usually it should call js::ReportOutOfMemory(cx) on allocation failure to report this to the context.
    • -
    -
  4. -
  5. Sometimes it's OK to ignore OOM -
      -
    • For example if you are performing a speculative optimisation you might abandon it and continue anyway.  But in this case you may have to call cx->recoverFromOutOfMemory() if something further down the stack has already reported the failure.
    • -
    -
  6. -
- -

Debugging GC marking/rooting

- -

The js::debug namespace contains some functions that are useful for watching mark bits for an individual JSObject* (or any Cell*). js/src/gc/Heap.h contains a comment describing an example usage. Reproduced here:

- -
// Sample usage from gdb:
-//
-//   (gdb) p $word = js::debug::GetMarkWordAddress(obj)
-//   $1 = (uintptr_t *) 0x7fa56d5fe360
-//   (gdb) p/x $mask = js::debug::GetMarkMask(obj, js::gc::GRAY)
-//   $2 = 0x200000000
-//   (gdb) watch *$word
-//   Hardware watchpoint 7: *$word
-//   (gdb) cond 7 *$word & $mask
-//   (gdb) cont
-//
-// Note that this is *not* a watchpoint on a single bit. It is a watchpoint on
-// the whole word, which will trigger whenever the word changes and the
-// selected bit is set after the change.
-//
-// So if the bit changing is the desired one, this is exactly what you want.
-// But if a different bit changes (either set or cleared), you may still stop
-// execution if the $mask bit happened to already be set. gdb does not expose
-// enough information to restrict the watchpoint to just a single bit.
-
- -

Most of the time, you will want js::gc::BLACK (or you can just use 0) for the 2nd param to js::debug::GetMarkMask.

diff --git a/files/ja/mozilla/projects/spidermonkey/how_to_embed_the_javascript_engine/index.html b/files/ja/mozilla/projects/spidermonkey/how_to_embed_the_javascript_engine/index.html deleted file mode 100644 index 7b623d6cbd..0000000000 --- a/files/ja/mozilla/projects/spidermonkey/how_to_embed_the_javascript_engine/index.html +++ /dev/null @@ -1,474 +0,0 @@ ---- -title: JavaScript エンジンを埋め込む方法 -slug: Mozilla/Projects/SpiderMonkey/How_to_embed_the_JavaScript_engine -tags: - - Embedding Mozilla - - JavaScript - - SpiderMonkey - - チュートリアル -translation_of: Mozilla/Projects/SpiderMonkey/How_to_embed_the_JavaScript_engine ---- -
{{SpiderMonkeySidebar("General")}}
- -

特により良いコードの例として JSAPI User Guide も参照して下さい。

- -

チュートリアル要点

- -

Hello World サンプル組み込みアプリケーション

- -

次のコードは、SpiderMonkey を埋め込んで単純な JavaScript スクリプトを実行する方法を示す非常に単純なアプリケーションです。下のコードのサンプルをビルドして実行するための手順を参照してください。

- -

コードは SpiderMonkey のバージョンごとに異なりますので、SpiderMonkey の正しいバージョンを選択してください。

- -

SpiderMonkey 24

- -
// following code might be needed in some case
-// #define __STDC_LIMIT_MACROS
-// #include <stdint.h>
-#include "jsapi.h"
-
-/* The class of the global object. */
-static JSClass global_class = {
-    "global",
-    JSCLASS_GLOBAL_FLAGS,
-    JS_PropertyStub,
-    JS_DeletePropertyStub,
-    JS_PropertyStub,
-    JS_StrictPropertyStub,
-    JS_EnumerateStub,
-    JS_ResolveStub,
-    JS_ConvertStub,
-};
-
-int main(int argc, const char *argv[])
-{
-    JSRuntime *rt = JS_NewRuntime(8L * 1024 * 1024, JS_USE_HELPER_THREADS);
-    if (!rt)
-        return 1;
-
-    JSContext *cx = JS_NewContext(rt, 8192);
-    if (!cx)
-        return 1;
-
-    { // Scope for our various stack objects (JSAutoRequest, RootedObject), so they all go
-      // out of scope before we JS_DestroyContext.
-
-      JSAutoRequest ar(cx); // In practice, you would want to exit this any
-                            // time you're spinning the event loop
-
-      JS::RootedObject global(cx, JS_NewGlobalObject(cx, &global_class, nullptr));
-      if (!global)
-          return 1;
-
-      JS::RootedValue rval(cx);
-
-      { // Scope for JSAutoCompartment
-        JSAutoCompartment ac(cx, global);
-        JS_InitStandardClasses(cx, global);
-
-        const char *script = "'hello'+'world, it is '+new Date()";
-        const char *filename = "noname";
-        int lineno = 1;
-        bool ok = JS_EvaluateScript(cx, global, script, strlen(script), filename, lineno, rval.address());
-        if (!ok)
-          return 1;
-      }
-
-      JSString *str = rval.toString();
-      printf("%s\n", JS_EncodeString(cx, str));
-    }
-
-    JS_DestroyContext(cx);
-    JS_DestroyRuntime(rt);
-    JS_ShutDown();
-    return 0;
-}
- -

SpiderMonkey 31

- -
// following code might be needed in some case
-// #define __STDC_LIMIT_MACROS
-// #include <stdint.h>
-#include "jsapi.h"
-
-/* The class of the global object. */
-static JSClass global_class = {
-    "global",
-    JSCLASS_GLOBAL_FLAGS,
-    JS_PropertyStub,
-    JS_DeletePropertyStub,
-    JS_PropertyStub,
-    JS_StrictPropertyStub,
-    JS_EnumerateStub,
-    JS_ResolveStub,
-    JS_ConvertStub,
-    nullptr,
-    nullptr,
-    nullptr,
-    nullptr,
-    JS_GlobalObjectTraceHook
-};
-
-int main(int argc, const char *argv[])
-{
-    JS_Init();
-
-    JSRuntime *rt = JS_NewRuntime(8L * 1024 * 1024, JS_USE_HELPER_THREADS);
-    if (!rt)
-        return 1;
-
-    JSContext *cx = JS_NewContext(rt, 8192);
-    if (!cx)
-        return 1;
-
-    { // Scope for our various stack objects (JSAutoRequest, RootedObject), so they all go
-      // out of scope before we JS_DestroyContext.
-
-      JSAutoRequest ar(cx); // In practice, you would want to exit this any
-                            // time you're spinning the event loop
-
-      JS::RootedObject global(cx, JS_NewGlobalObject(cx, &global_class, nullptr, JS::FireOnNewGlobalHook));
-      if (!global)
-          return 1;
-
-      JS::RootedValue rval(cx);
-
-      { // Scope for JSAutoCompartment
-        JSAutoCompartment ac(cx, global);
-        JS_InitStandardClasses(cx, global);
-
-        const char *script = "'hello'+'world, it is '+new Date()";
-        const char *filename = "noname";
-        int lineno = 1;
-        bool ok = JS_EvaluateScript(cx, global, script, strlen(script), filename, lineno, &rval);
-        if (!ok)
-          return 1;
-      }
-
-      JSString *str = rval.toString();
-      printf("%s\n", JS_EncodeString(cx, str));
-    }
-
-    JS_DestroyContext(cx);
-    JS_DestroyRuntime(rt);
-    JS_ShutDown();
-    return 0;
-}
- -

SpiderMonkey 38

- -
// following code might be needed in some case
-// #define __STDC_LIMIT_MACROS
-// #include <stdint.h>
-#include "jsapi.h"
-
-/* The class of the global object. */
-static JSClass global_class = {
-    "global",
-    JSCLASS_GLOBAL_FLAGS,
-    nullptr,
-    nullptr,
-    nullptr,
-    nullptr,
-    nullptr,
-    nullptr,
-    nullptr,
-    nullptr,
-    nullptr,
-    nullptr,
-    nullptr,
-    JS_GlobalObjectTraceHook
-};
-
-int main(int argc, const char *argv[])
-{
-    JS_Init();
-
-    JSRuntime *rt = JS_NewRuntime(8L * 1024 * 1024);
-    if (!rt)
-        return 1;
-
-    JSContext *cx = JS_NewContext(rt, 8192);
-    if (!cx)
-        return 1;
-
-    { // Scope for our various stack objects (JSAutoRequest, RootedObject), so they all go
-      // out of scope before we JS_DestroyContext.
-
-      JSAutoRequest ar(cx); // In practice, you would want to exit this any
-                            // time you're spinning the event loop
-
-      JS::RootedObject global(cx, JS_NewGlobalObject(cx, &global_class, nullptr, JS::FireOnNewGlobalHook));
-      if (!global)
-          return 1;
-
-      JS::RootedValue rval(cx);
-
-      { // Scope for JSAutoCompartment
-        JSAutoCompartment ac(cx, global);
-        JS_InitStandardClasses(cx, global);
-
-        const char *script = "'hello'+'world, it is '+new Date()";
-        const char *filename = "noname";
-        int lineno = 1;
-        JS::CompileOptions opts(cx);
-        opts.setFileAndLine(filename, lineno);
-        bool ok = JS::Evaluate(cx, global, opts, script, strlen(script), &rval);
-        if (!ok)
-          return 1;
-      }
-
-      JSString *str = rval.toString();
-      printf("%s\n", JS_EncodeString(cx, str));
-    }
-
-    JS_DestroyContext(cx);
-    JS_DestroyRuntime(rt);
-    JS_ShutDown();
-    return 0;
-}
- -

SpiderMonkey 45

- -
// following code might be needed in some case
-// #define __STDC_LIMIT_MACROS
-// #include <stdint.h>
-#include "jsapi.h"
-#include "js/Initialization.h"
-
-/* The class of the global object. */
-static JSClass global_class = {
-    "global",
-    JSCLASS_GLOBAL_FLAGS,
-    nullptr,
-    nullptr,
-    nullptr,
-    nullptr,
-    nullptr,
-    nullptr,
-    nullptr,
-    nullptr,
-    nullptr,
-    nullptr,
-    nullptr,
-    JS_GlobalObjectTraceHook
-};
-
-int main(int argc, const char *argv[])
-{
-    JS_Init();
-
-    JSRuntime *rt = JS_NewRuntime(8L * 1024 * 1024);
-    if (!rt)
-        return 1;
-
-    JSContext *cx = JS_NewContext(rt, 8192);
-    if (!cx)
-        return 1;
-
-    { // Scope for our various stack objects (JSAutoRequest, RootedObject), so they all go
-      // out of scope before we JS_DestroyContext.
-
-      JSAutoRequest ar(cx); // In practice, you would want to exit this any
-                            // time you're spinning the event loop
-
-      JS::RootedObject global(cx, JS_NewGlobalObject(cx, &global_class, nullptr, JS::FireOnNewGlobalHook));
-      if (!global)
-          return 1;
-
-      JS::RootedValue rval(cx);
-
-      { // Scope for JSAutoCompartment
-        JSAutoCompartment ac(cx, global);
-        JS_InitStandardClasses(cx, global);
-
-        const char *script = "'hello'+'world, it is '+new Date()";
-        const char *filename = "noname";
-        int lineno = 1;
-        JS::CompileOptions opts(cx);
-        opts.setFileAndLine(filename, lineno);
-        bool ok = JS::Evaluate(cx, opts, script, strlen(script), &rval);
-        if (!ok)
-          return 1;
-      }
-
-      JSString *str = rval.toString();
-      printf("%s\n", JS_EncodeString(cx, str));
-    }
-
-    JS_DestroyContext(cx);
-    JS_DestroyRuntime(rt);
-    JS_ShutDown();
-    return 0;
-}
- -

SpiderMonkey 52

- -
#include "jsapi.h"
-#include "js/Initialization.h"
-
-static JSClassOps global_ops = {
-    nullptr,
-    nullptr,
-    nullptr,
-    nullptr,
-    nullptr,
-    nullptr,
-    nullptr,
-    nullptr,
-    nullptr,
-    nullptr,
-    nullptr,
-    JS_GlobalObjectTraceHook
-};
-
-/* The class of the global object. */
-static JSClass global_class = {
-    "global",
-    JSCLASS_GLOBAL_FLAGS,
-    &global_ops
-};
-
-int main(int argc, const char *argv[])
-{
-    JS_Init();
-
-    JSContext *cx = JS_NewContext(8L * 1024 * 1024);
-    if (!cx)
-        return 1;
-    if (!JS::InitSelfHostedCode(cx))
-        return 1;
-
-    { // Scope for our various stack objects (JSAutoRequest, RootedObject), so they all go
-      // out of scope before we JS_DestroyContext.
-
-      JSAutoRequest ar(cx); // In practice, you would want to exit this any
-                            // time you're spinning the event loop
-
-      JS::CompartmentOptions options;
-      JS::RootedObject global(cx, JS_NewGlobalObject(cx, &global_class, nullptr, JS::FireOnNewGlobalHook, options));
-      if (!global)
-          return 1;
-
-      JS::RootedValue rval(cx);
-
-      { // Scope for JSAutoCompartment
-        JSAutoCompartment ac(cx, global);
-        JS_InitStandardClasses(cx, global);
-
-        const char *script = "'hello'+'world, it is '+new Date()";
-        const char *filename = "noname";
-        int lineno = 1;
-        JS::CompileOptions opts(cx);
-        opts.setFileAndLine(filename, lineno);
-        bool ok = JS::Evaluate(cx, opts, script, strlen(script), &rval);
-        if (!ok)
-          return 1;
-      }
-
-      JSString *str = rval.toString();
-      printf("%s\n", JS_EncodeString(cx, str));
-    }
-
-    JS_DestroyContext(cx);
-    JS_ShutDown();
-    return 0;
-}
- -

Hello Worldの例のビルドと実行

- -
-

ビルドコマンドラインは OS とツールに依存します。Mac と Linux のコマンドラインのサンプルを次に示します (<objdir> は SpiderMonkey がビルドされたディレクトリです)。

- -
# SpiderMonkey のデバッグビルドを使用している場合は、以下のコマンドに加えて -DDEBUG が必要です。
-# SpiderMonkey 31 以外のバージョンを使用している場合は、-lmozjs-XX を自分のバージョンに変更してください。
-
-[Mac]
-clang++ -std=c++11 -I<objdir>/dist/include -L<objdir>/dist/lib helloworld.cpp -o helloworld  -lmozjs-31 -lz
-[Linux]
-g++ -std=c++11 -I<objdir>/dist/include -L<objdir>/dist/lib helloworld.cpp -o helloworld  -lmozjs-31 -lz -lpthread -ldl
- -

"helloworld, it is TIME" と表示されます (ここでは TIME が現在の時刻です)。

- -
    -
  1. Make sure the build computer has the prerequisites for building SpiderMonkey: Linux, Windows, Mac OS X, others. For Windows, the following steps will assume that you have installed the MozillaBuild package.
  2. -
  3. Get the SpiderMonkey source code. You can download a source archive or use Mercurial (hg) to pull the SpiderMonkey repository. On Windows, do not install the SpiderMonkey source code under the MSYS root directory (which is usually c:\mozilla-build\msys). Instead use something like c:\mozjs-31.2.0
  4. -
  5. Compile SpiderMonkey using the build instructions at SpiderMonkey Build Documentation. By default this will build a SpiderMonkey shared library that you will link into your application in a later step.
  6. -
  7. Copy the code example above into a text editor and save the file as helloworld.cpp in the SpiderMonkey js\src directory. To get a copy of the code sample without line numbers, hover over the sample near the top until buttons appear. Then click the view source button, and copy the code from the window that appears.
  8. -
  9. Compile the helloworld application and link to the SpiderMonkey library.
  10. -
  11. Run the helloworld executable at the command line: -
    ./helloworld
    -
  12. -
-
- -

JavaScript から C 関数の呼び出し方

- -

doit という名前のC関数について言及します。これは呼び出されるときに少なくとも二つの実際のパラメータを使います。(もし呼びだし元がより少ないパラメータを使う場合、JSエンジンは無くなった一つの変数に対して未定義の変数が渡される事を確認すべきです):

- -
#define DOIT_MINARGS 2
-
-static JSBool
-doit(JSContext *cx, unsigned argc, jsval *vp)
-{
-    jsval *argv = JS_ARGV(cx, vp);
-    /*
-     * Look in argv for argc actual parameters, set *rval to return a
-     * value to the caller.
-     */
-    ...
-}
-
- -

そして、以下のようにコーディングし、JSに渡します:

- -
ok = JS_DefineFunction(cx, global, "doit", doit, DOIT_MINARGS, 0);
-
- -

または、ネイティブな関数群として定義するならば、おそらくそれらをテーブルの中に置き、関数テーブルとして定義するでしょう:

- -
static JSFunctionSpec my_functions[] = {
-    {"doit", doit, DOIT_MINARGS, 0, 0},
-    etc...
-    {0,0,0,0,0},
-};
-
- -

(最終的に、すべてのNULL 関数はテーブルを終端します)そして、以下のようにします:

- -
ok = JS_DefineFunctions(cx, global, my_functions);
-
- -

C から JavaScript の関数の呼び出し方

- -

クリックイベントを最上位の UI から座標 (x,y) の UI 要素に焦点をあてます:

- -
JSObject *target, *event;
-jsval argv[1], rval;
-
-/*
- * Find event target and make event object to represent this click.
- * Pass cx to NewEventObject so JS_NewObject can be called.
- */
-target = FindEventTargetAt(cx, global, x, y);
-event = NewEventObject(cx, "click", x, y);
-argv[0] = OBJECT_TO_JSVAL(event);
-
-/* To emulate the DOM, you might want to try "onclick" too. */
-ok = JS_CallFunctionName(cx, target, "onClick", 1, argv, &rval);
-
-/* Now test rval to see whether we should cancel the event. */
-if (JSVAL_IS_BOOLEAN(rval) && !JSVAL_TO_BOOLEAN(rval))
-    CancelEvent(event);
-
- -

繰り返しますが、ここではエラーチェックは無視しています。(関数呼び出し後の 戻り値 !ok のテストような)、いくつかのCのイベント管理処理やハンドラーが偽値を返したときのイベントをキャンセルする場合のDOMの伝統的なやり方を適切にエミュレートするために疑似コードを用いています。

- -
-

Original Document Information

- - -
diff --git a/files/ja/mozilla/projects/spidermonkey/index.html b/files/ja/mozilla/projects/spidermonkey/index.html deleted file mode 100644 index e285c49690..0000000000 --- a/files/ja/mozilla/projects/spidermonkey/index.html +++ /dev/null @@ -1,102 +0,0 @@ ---- -title: SpiderMonkey -slug: Mozilla/Projects/SpiderMonkey -tags: - - SpiderMonkey -translation_of: Mozilla/Projects/SpiderMonkey ---- -
{{SpiderMonkeySidebar}}
- -

SpiderMonkey は 、C / C++ で書かれた JavaScript エンジンです。Firefoxを含む、Mozillaの複数の製品で使用されており、MPL2  ライセンスの下で利用できます。

- -

独立したソースコードリリースは、リリースページにあります。

- -
-
-

ガイド

- -

ビルド

- -
-
SpiderMonkey のビルド手順
-
SpiderMonkey をビルドしてテストスイートを実行する方法について。
-
- -

SpiderMonkey の利用

- -
-
JavaScript シェルの手引き
-
JavaScript シェルの取得、構築、利用方法について。
-
JSAPI ユーザガイド
-
このガイドでは、SpiderMonkey の概要と、あなたのアプリケーションを JavaScript 対応にするため、アプリケーションから組み込んだエンジンを呼び出す方法について説明します。
-
JSAPI クックブック
-
よく使われる JavaScript の式や文の JSAPI 表現を解説します。
-
GC ルーティングガイド
-
SpiderMonkey の世代別 GC に対応したコードの書き方を解説します。
-
JavaScript エンジンの埋め込み方
-
SpiderMonkey の埋め込み方の古い解説です。
-
- -

SpiderMonkey のハック

- -
-
SpiderMonkey 入門
-
SpiderMonkey をハックするためのガイド。
-
SpiderMonkey 開発のための CDT 設定
-
SpiderMonkey を開発するための Eclipse 設定手順を解説します。
-
SpiderMonkey に貢献するには
-
4 分弱のスライドキャストです。
-
- -
-
JavaScript テストの自動実行
-
JavaScript テストスイートの自動実行方法について解説します。
-
JavaScript のテストを作成する
-
JavaScript テストスイートに対するテストの追加方法を解説します。
-
-
- -
-

リファレンス

- -
-
JSAPI レファレンス
-
SpiderMonkey の API レファレンスです。
-
JS Debugger API レファレンス
-
Gecko 8.0 {{GeckoRelease("8.0")}} と同時にリリースされた SpiderMonkey 1.8.6 で導入された、Debugger オブジェクトの API について解説します。
-
バイトコードの解説
-
SpiderMonkey が利用するバイトコードのリストです。
-
Parser API
-
SpiderMonkey の持つ構文解析器と、JavaScript API からの利用方法を解説しています。
-
- -

TIPS、トリック、哲学

- -
-
今後の方針
-
機能、設計、コーディングにおける今後の方針を述べています。
-
SpiderMonkey の内部構造
-
設計の概要と、ファイル単位での実装の解説です。
-
バイトコードのレファレンス
-
SpiderMonkey の使用するバイトコードのレファレンスです。
-
SpiderMonkey の内部構造: GC
-
GC の内部構造を解説します。
-
SpiderMonkey の内部構造: ハックのための TIPS
-
SpiderMonkey をハックするために有用なツールと TIPS  がまとめられています。
-
- -

関連項目

- - - -

リリースノート

- -
-
SpiderMonkey リリースノート
-
現在のリリースと、次にあげる過去のリリースに対するリリースノートがまとめられています:52, 45, 38, 31, 24, 17
-
-
-
diff --git a/files/ja/mozilla/projects/spidermonkey/index/index.html b/files/ja/mozilla/projects/spidermonkey/index/index.html deleted file mode 100644 index f59feeeb07..0000000000 --- a/files/ja/mozilla/projects/spidermonkey/index/index.html +++ /dev/null @@ -1,10 +0,0 @@ ---- -title: Index -slug: Mozilla/Projects/SpiderMonkey/Index -tags: - - Index - - MDN Meta - - SpiderMonkey -translation_of: Mozilla/Projects/SpiderMonkey/Index ---- -

{{Index("/ja/docs/Mozilla/Projects/SpiderMonkey")}}

diff --git a/files/ja/mozilla/projects/spidermonkey/internals/bytecode/index.html b/files/ja/mozilla/projects/spidermonkey/internals/bytecode/index.html deleted file mode 100644 index f4e65a7748..0000000000 --- a/files/ja/mozilla/projects/spidermonkey/internals/bytecode/index.html +++ /dev/null @@ -1,6855 +0,0 @@ ---- -title: バイトコードの説明 -slug: Mozilla/Projects/SpiderMonkey/Internals/Bytecode -tags: - - SpiderMonkey -translation_of: Mozilla/Projects/SpiderMonkey/Internals/Bytecode ---- -
{{SpiderMonkeySidebar("Internals")}}
- -

バイトコード一覧

- -

この文書は make_opcode_doc.py によって Opcodes.h から自動的に生成されます。

- -

ステートメント

- -

Jumps

- -
-
JSOP_AND [-1, +1] (JUMP, DETECTING, IC)
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value69 (0x45)
Operandsint32_t offset
Length5
Stack Usescond
Stack Defscond
- -

スタックの先頭の値をブール値に変換し、結果が false の場合、現在のバイトコードから 32-bit のオフセットにジャンプします。

-
-
JSOP_GOTO [-0, +0] (JUMP)
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value6 (0x06)
Operandsint32_t offset
Length5
Stack Uses 
Stack Defs 
- -

現在のバイトコードから 32-bit のオフセットにジャンプします。

-
-
JSOP_IFEQ [-1, +0] (JUMP, DETECTING, IC)
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value7 (0x07)
Operandsint32_t offset
Length5
Stack Usescond
Stack Defs 
- -

Pops the top of stack value, converts it into a boolean, if the result is false, jumps to a 32-bit offset from the current bytecode.

- -

The idea is that a sequence like JSOP_ZERO; JSOP_ZERO; JSOP_EQ; JSOP_IFEQ; JSOP_RETURN; reads like a nice linear sequence that will execute the return.

-
-
JSOP_IFNE [-1, +0] (JUMP, IC)
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value8 (0x08)
Operandsint32_t offset
Length5
Stack Usescond
Stack Defs 
- -

Pops the top of stack value, converts it into a boolean, if the result is true, jumps to a 32-bit offset from the current bytecode.

-
-
JSOP_LABEL [-0, +0] (CODE_OFFSET)
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value106 (0x6a)
Operandsint32_t offset
Length5
Stack Uses 
Stack Defs 
- -

This opcode precedes every labeled statement. It's a no-op.

- -

offset is the offset to the next instruction after this statement, the one break LABEL; would jump to. IonMonkey uses this.

-
-
JSOP_LOOPENTRY [-0, +0] (LOOPENTRY, IC)
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value227 (0xe3)
Operandsuint32_t icIndex, uint8_t BITFIELD
Length6
Stack Uses 
Stack Defs 
- -

This opcode is the target of the entry jump for some loop. The uint8 argument is a bitfield. The lower 7 bits of the argument indicate the loop depth. This value starts at 1 and is just a hint: deeply nested loops all have the same value. The upper bit is set if Ion should be able to OSR at this point, which is true unless there is non-loop state on the stack. See JSOP_JUMPTARGET for the icIndex argument.

-
-
JSOP_LOOPHEAD [-0, +0] (ICINDEX)
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value109 (0x6d)
Operandsuint32_t icIndex
Length5
Stack Uses 
Stack Defs 
- -

Another no-op.

- -

This opcode is the target of the backwards jump for some loop. See JSOP_JUMPTARGET for the icIndex operand.

-
-
JSOP_OR [-1, +1] (JUMP, DETECTING, IC)
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value68 (0x44)
Operandsint32_t offset
Length5
Stack Usescond
Stack Defscond
- -

Converts the top of stack value into a boolean, if the result is true, jumps to a 32-bit offset from the current bytecode.

-
-
- -

Switch Statement

- -
-
JSOP_CASE [-2, +1] (JUMP)
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value121 (0x79)
Operandsint32_t offset
Length5
Stack Usesval, cond
Stack Defsval(if !cond)
- -

Pops the top two values on the stack as val and cond. If cond is true, jumps to a 32-bit offset from the current bytecode, re-pushes val onto the stack if false.

-
-
JSOP_CONDSWITCH [-0, +0]
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value120 (0x78)
Operands 
Length1
Stack Uses 
Stack Defs 
- -

This no-op appears after the bytecode for EXPR in switch (EXPR) {...} if the switch cannot be optimized using JSOP_TABLESWITCH.

- -

For a non-optimized switch statement like this:

- -
   switch (EXPR) {
-     case V0:
-       C0;
-     ...
-     default:
-       D;
-   }
-
- -

the bytecode looks like this:

- -
   (EXPR)
-   condswitch
-   (V0)
-   case ->C0
-   ...
-   default ->D
-   (C0)
-   ...
-   (D)
-
- -

Note that code for all case-labels is emitted first, then code for the body of each case clause.

-
-
JSOP_DEFAULT [-1, +0] (JUMP)
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value122 (0x7a)
Operandsint32_t offset
Length5
Stack Useslval
Stack Defs 
- -

This appears after all cases in a JSOP_CONDSWITCH, whether there is a default: label in the switch statement or not. Pop the switch operand from the stack and jump to a 32-bit offset from the current bytecode. offset from the current bytecode.

-
-
JSOP_TABLESWITCH [-1, +0] (TABLESWITCH, DETECTING)
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value70 (0x46)
Operandsint32_t len, int32_t low, int32_t high,uint24_t firstResumeIndex
Lengthlen
Stack Usesi
Stack Defs 
- -

Pops the top of stack value as i, if low <= i <= high, jumps to a 32-bit offset: offset is stored in the script's resumeOffsets

- -
                         list at index 'firstResumeIndex + (i - low)'
-
- -

jumps to a 32-bit offset: len from the current bytecode otherwise

-
-
- -

For-In Statement

- -
-
JSOP_ENDITER [-1, +0]
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value78 (0x4e)
Operands 
Length1
Stack Usesiter
Stack Defs 
- -

Exits a for-in loop by popping the iterator object from the stack and closing it.

-
-
JSOP_ISGENCLOSING [-1, +2]
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value187 (0xbb)
Operands 
Length1
Stack Usesval
Stack Defsval, res
- -

Pushes a boolean indicating whether the top of the stack is MagicValue(JS_GENERATOR_CLOSING).

-
-
JSOP_ISNOITER [-1, +2]
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value77 (0x4d)
Operands 
Length1
Stack Usesval
Stack Defsval, res
- -

Pushes a boolean indicating whether the value on top of the stack is MagicValue(JS_NO_ITER_VALUE).

-
-
JSOP_ITER [-1, +1] (IC)
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value75 (0x4b)
Operands 
Length1
Stack Usesval
Stack Defsiter
- -

Sets up a for-in loop. It pops the top of stack value as val and pushes iter which is an iterator for val.

-
-
JSOP_MOREITER [-1, +2]
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value76 (0x4c)
Operands 
Length1
Stack Usesiter
Stack Defsiter, val
- -

Pushes the next iterated value onto the stack. If no value is available, MagicValue(JS_NO_ITER_VALUE) is pushed.

-
-
- -

With Statement

- -
-
JSOP_ENTERWITH [-1, +0] (SCOPE)
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value3 (0x03)
Operandsuint32_t staticWithIndex
Length5
Stack Usesval
Stack Defs 
- -

Pops the top of stack value, converts it to an object, and adds a WithEnvironmentObject wrapping that object to the environment chain.

- -

There is a matching JSOP_LEAVEWITH instruction later. All name lookups between the two that may need to consult the With object are deoptimized.

-
-
JSOP_LEAVEWITH [-0, +0]
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value4 (0x04)
Operands 
Length1
Stack Uses 
Stack Defs 
- -

Pops the environment chain object pushed by JSOP_ENTERWITH.

-
-
- -

Exception Handling

- -
-
JSOP_EXCEPTION [-0, +1]
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value118 (0x76)
Operands 
Length1
Stack Uses 
Stack Defsexception
- -

Pushes the current pending exception onto the stack and clears the pending exception. This is only emitted at the beginning of code for a catch-block, so it is known that an exception is pending. It is used to implement catch-blocks and yield*.

-
-
JSOP_FINALLY [-0, +2]
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value135 (0x87)
Operands 
Length1
Stack Uses 
Stack Defsfalse, resumeIndex
- -

This opcode has a def count of 2, but these values are already on the stack (they're pushed by JSOP_GOSUB).

-
-
JSOP_GOSUB [-2, +0] (JUMP)
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value116 (0x74)
Operandsint32_t offset
Length5
Stack Usesfalse, resumeIndex
Stack Defs 
- -

This opcode is used for entering a finally block. Jumps to a 32-bit offset from the current pc.

- -

Note: this op doesn't actually push/pop any values, but it has a use count of 2 (for the false + resumeIndex values pushed by preceding bytecode ops) because the finally entry point does not expect these values on the stack. See also JSOP_FINALLY (it has a def count of 2).

- -

When the execution resumes from finally block, those stack values are popped.

-
-
JSOP_RETSUB [-2, +0]
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value117 (0x75)
Operands 
Length1
Stack Useslval, rval
Stack Defs 
- -

This opcode is used for returning from a finally block.

- -

Pops the top two values on the stack as rval and lval. Then: - If lval is true, throws rval. - If lval is false, jumps to the resumeIndex stored in lval.

-
-
JSOP_THROW [-1, +0]
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value112 (0x70)
Operands 
Length1
Stack Usesv
Stack Defs 
- -

Pops the top of stack value as v, sets pending exception as v, then raises error.

-
-
JSOP_THROWMSG [-0, +0] (UINT16)
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value74 (0x4a)
Operandsuint16_t msgNumber
Length3
Stack Uses 
Stack Defs 
- -

Sometimes we know when emitting that an operation will always throw.

- -

Throws the indicated JSMSG.

-
-
JSOP_TRY [-0, +0]
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value134 (0x86)
Operands 
Length1
Stack Uses 
Stack Defs 
- -

This no-op appears at the top of the bytecode for a TryStatement.

- -

Location information for catch/finally blocks is stored in a side table, script->trynotes().

-
-
- -

Function

- -
-
JSOP_CALL [-(argc+2), +1] (ARGC, INVOKE, TYPESET, IC)
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value58 (0x3a)
Operandsuint16_t argc
Length3
Stack Usescallee, this, args[0], ..., args[argc-1]
Stack Defsrval
- -

Invokes callee with this and args, pushes return value onto the stack.

-
-
JSOP_CALLITER [-2, +1] (ARGC, INVOKE, TYPESET, IC)
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value145 (0x91)
Operandsuint16_t argc (must be 0)
Length3
Stack Usescallee, this
Stack Defsrval
- -

Like JSOP_CALL, but used as part of for-of and destructuring bytecode to provide better error messages.

-
-
JSOP_CALL_IGNORES_RV [-(argc+2), +1] (ARGC, INVOKE, TYPESET, IC)
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value231 (0xe7)
Operandsuint16_t argc
Length3
Stack Usescallee, this, args[0], ..., args[argc-1]
Stack Defsrval
- -

Like JSOP_CALL, but tells the function that the return value is ignored. stack.

-
-
JSOP_CHECKISCALLABLE [-1, +1] (UINT8)
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value219 (0xdb)
Operandsuint8_t kind
Length2
Stack Usesobj
Stack Defsobj
- -

Checks that the top value on the stack is callable, and throws a TypeError if not. The operand kind is used only to generate an appropriate error message.

-
-
JSOP_EVAL [-(argc+2), +1] (ARGC, INVOKE, TYPESET, CHECKSLOPPY, IC)
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value123 (0x7b)
Operandsuint16_t argc
Length3
Stack Usescallee, this, args[0], ..., args[argc-1]
Stack Defsrval
- -

Invokes eval with args and pushes return value onto the stack.

- -

If eval in global scope is not original one, invokes the function with this and args, and pushes return value onto the stack.

-
-
JSOP_FUNAPPLY [-(argc+2), +1] (ARGC, INVOKE, TYPESET, IC)
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value79 (0x4f)
Operandsuint16_t argc
Length3
Stack Usescallee, this, args[0], ..., args[argc-1]
Stack Defsrval
- -

Invokes callee with this and args, pushes return value onto the stack.

- -

This is for f.apply.

-
-
JSOP_FUNCALL [-(argc+2), +1] (ARGC, INVOKE, TYPESET, IC)
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value108 (0x6c)
Operandsuint16_t argc
Length3
Stack Usescallee, this, args[0], ..., args[argc-1]
Stack Defsrval
- -

Invokes callee with this and args, pushes return value onto the stack.

- -

If callee is determined to be the canonical Function.prototype.call function, then this operation is optimized to directly call callee with args[0] as this, and the remaining arguments as formal args to callee.

- -

Like JSOP_FUNAPPLY but for f.call instead of f.apply.

-
-
JSOP_FUNWITHPROTO [-1, +1] (OBJECT)
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value52 (0x34)
Operandsuint32_t funcIndex
Length5
Stack Usesproto
Stack Defsobj
- -

Pushes a clone of a function with a given [[Prototype]] onto the stack.

-
-
JSOP_GETRVAL [-0, +1]
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value2 (0x02)
Operands 
Length1
Stack Uses 
Stack Defsrval
- -

Pushes stack frame's rval onto the stack.

-
-
JSOP_LAMBDA [-0, +1] (OBJECT)
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value130 (0x82)
Operandsuint32_t funcIndex
Length5
Stack Uses 
Stack Defsobj
- -

Pushes a closure for a named or anonymous function expression onto the stack.

-
-
JSOP_LAMBDA_ARROW [-1, +1] (OBJECT)
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value131 (0x83)
Operandsuint32_t funcIndex
Length5
Stack Usesnew.target
Stack Defsobj
- -

Pops the top of stack value as new.target, pushes an arrow function with lexical new.target onto the stack.

-
-
JSOP_NEW [-(argc+3), +1] (ARGC, INVOKE, TYPESET, IC, IC)
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value82 (0x52)
Operandsuint16_t argc
Length3
Stack Usescallee, this, args[0], ..., args[argc-1], newTarget
Stack Defsrval
- -

Invokes callee as a constructor with this and args, pushes return value onto the stack.

-
-
JSOP_OPTIMIZE_SPREADCALL [-1, +2]
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value178 (0xb2)
Operands 
Length1
Stack Usesarr
Stack Defsarr, optimized
- -

Pops the top stack value, pushes the value and a boolean value that indicates whether the spread operation for the value can be optimized in spread call.

-
-
JSOP_RETRVAL [-0, +0]
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value153 (0x99)
Operands 
Length1
Stack Uses 
Stack Defs 
- -

Stops interpretation and returns value set by JSOP_SETRVAL. When not set, returns undefined.

- -

Also emitted at end of script so interpreter don't need to check if opcode is still in script range.

-
-
JSOP_RETURN [-1, +0]
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value5 (0x05)
Operands 
Length1
Stack Usesrval
Stack Defs 
- -

Pops the top of stack value as rval, stops interpretation of current script and returns rval.

-
-
JSOP_SETFUNNAME [-2, +1] (UINT8)
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value182 (0xb6)
Operandsuint8_t prefixKind
Length2
Stack Usesfun, name
Stack Defsfun
- -

Pops the top two values on the stack as name and fun, defines the name of fun to name with prefix if any, and pushes fun back onto the stack.

-
-
JSOP_SETRVAL [-1, +0]
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value152 (0x98)
Operands 
Length1
Stack Usesrval
Stack Defs 
- -

Pops the top of stack value as rval, sets the return value in stack frame as rval.

-
-
JSOP_SPREADCALL [-3, +1] (INVOKE, TYPESET, IC)
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value41 (0x29)
Operands 
Length1
Stack Usescallee, this, args
Stack Defsrval
- -

spreadcall variant of JSOP_CALL.

- -

Invokes callee with this and args, pushes the return value onto the stack.

- -

args is an Array object which contains actual arguments.

-
-
JSOP_SPREADEVAL [-3, +1] (INVOKE, TYPESET, CHECKSLOPPY, IC)
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value43 (0x2b)
Operands 
Length1
Stack Usescallee, this, args
Stack Defsrval
- -

spreadcall variant of JSOP_EVAL

- -

Invokes eval with args and pushes the return value onto the stack.

- -

If eval in global scope is not original one, invokes the function with this and args, and pushes return value onto the stack.

-
-
JSOP_SPREADNEW [-4, +1] (INVOKE, TYPESET, IC)
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value42 (0x2a)
Operands 
Length1
Stack Usescallee, this, args, newTarget
Stack Defsrval
- -

spreadcall variant of JSOP_NEW

- -

Invokes callee as a constructor with this and args, pushes the return value onto the stack.

-
-
JSOP_SPREADSUPERCALL [-4, +1] (INVOKE, TYPESET, IC)
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value166 (0xa6)
Operands 
Length1
Stack Usescallee, this, args, newTarget
Stack Defsrval
- -

spreadcall variant of JSOP_SUPERCALL.

- -

Behaves exactly like JSOP_SPREADNEW.

-
-
JSOP_STRICTEVAL [-(argc+2), +1] (ARGC, INVOKE, TYPESET, CHECKSTRICT, IC)
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value124 (0x7c)
Operandsuint16_t argc
Length3
Stack Usescallee, this, args[0], ..., args[argc-1]
Stack Defsrval
- -

Invokes eval with args and pushes return value onto the stack.

- -

If eval in global scope is not original one, invokes the function with this and args, and pushes return value onto the stack.

-
-
JSOP_STRICTSPREADEVAL [-3, +1] (INVOKE, TYPESET, CHECKSTRICT, IC)
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value50 (0x32)
Operands 
Length1
Stack Usescallee, this, args
Stack Defsrval
- -

spreadcall variant of JSOP_EVAL

- -

Invokes eval with args and pushes the return value onto the stack.

- -

If eval in global scope is not original one, invokes the function with this and args, and pushes return value onto the stack.

-
-
JSOP_SUPERCALL [-(argc+3), +1] (ARGC, INVOKE, TYPESET, IC)
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value165 (0xa5)
Operandsuint16_t argc
Length3
Stack Usescallee, this, args[0], ..., args[argc-1], newTarget
Stack Defsrval
- -

Behaves exactly like JSOP_NEW, but allows JITs to distinguish the two cases.

-
-
JSOP_TRYSKIPAWAIT [-1, +2]
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value223 (0xdf)
Operands 
Length1
Stack Usesvalue
Stack Defsvalue_or_resolved, canskip
- -

Pops the top of stack value as value, checks if the await for value can be skipped. If the await operation can be skipped and the resolution value for value can be acquired, pushes the resolution value and true onto the stack. Otherwise, pushes value and false on the stack.

-
-
- -

Generator

- -
-
JSOP_ASYNCAWAIT [-2, +1]
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value151 (0x97)
Operands 
Length1
Stack Usesvalue, gen
Stack Defspromise
- -

Pops the top two values value and gen from the stack, then starts "awaiting" for value to be resolved, which will then resume the execution of gen. Pushes the async function promise on the stack, so that it'll be returned to the caller on the very first "await".

-
-
JSOP_ASYNCRESOLVE [-2, +1] (UINT8)
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value192 (0xc0)
Operandsuint8_t fulfillOrReject
Length2
Stack UsesvalueOrReason, gen
Stack Defspromise
- -

Pops the top two values valueOrReason and gen from the stack, then pushes the promise resolved with valueOrReason. `gen` must be the internal generator object created in async functions. The pushed promise is the async function's result promise, which is stored in `gen`.

-
-
JSOP_AWAIT [-2, +1] (RESUMEINDEX)
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value209 (0xd1)
Operandsuint24_t resumeIndex
Length4
Stack Usespromise, gen
Stack Defsresolved
- -

Pops the generator and the return value promise, stops interpretation and returns promise. Pushes resolved value onto the stack.

-
-
JSOP_CHECKISOBJ [-1, +1] (UINT8)
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value14 (0x0e)
Operandsuint8_t kind
Length2
Stack Usesresult
Stack Defsresult
- -

Checks that the top value on the stack is an object, and throws a TypeError if not. The operand kind is used only to generate an appropriate error message.

-
-
JSOP_FINALYIELDRVAL [-1, +0]
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value204 (0xcc)
Operands 
Length1
Stack Usesgen
Stack Defs 
- -

Pops the generator and suspends and closes it. Yields the value in the frame's return value slot.

-
-
JSOP_GENERATOR [-0, +1]
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value212 (0xd4)
Operands 
Length1
Stack Uses 
Stack Defsgenerator
- -

Initializes generator frame, creates a generator and pushes it on the stack.

-
-
JSOP_INITIALYIELD [-1, +1] (RESUMEINDEX)
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value202 (0xca)
Operandsuint24_t resumeIndex
Length4
Stack Usesgenerator
Stack Defsgenerator
- -

Pops the generator from the top of the stack, suspends it and stops interpretation.

-
-
JSOP_RESUME [-2, +1] (UINT8, INVOKE)
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value205 (0xcd)
Operandsresume kind (AbstractGeneratorObject::ResumeKind)
Length2
Stack Usesgen, val
Stack Defsrval
- -

Pops the generator and argument from the stack, pushes a new generator frame and resumes execution of it. Pushes the return value after the generator yields.

-
-
JSOP_TOASYNCITER [-2, +1]
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value210 (0xd2)
Operands 
Length1
Stack Usesiter, next
Stack Defsasynciter
- -

Pops the iterator and its next method from the top of the stack, and create async iterator from it and push the async iterator back onto the stack.

-
-
JSOP_YIELD [-2, +1] (RESUMEINDEX)
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value203 (0xcb)
Operandsuint24_t resumeIndex
Length4
Stack Usesrval1, gen
Stack Defsrval2
- -

Pops the generator and the return value rval1, stops interpretation and returns rval1. Pushes sent value from send() onto the stack.

-
-
- -

Debugger

- -
-
JSOP_DEBUGGER [-0, +0]
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value115 (0x73)
Operands 
Length1
Stack Uses 
Stack Defs 
- -

Invokes debugger.

-
-
JSOP_DEBUGLEAVELEXICALENV [-0, +0]
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value201 (0xc9)
Operands 
Length1
Stack Uses 
Stack Defs 
- -

The opcode to assist the debugger.

-
-
- -

Variables and Scopes

- -

Variables

- -
-
JSOP_BINDNAME [-0, +1] (ATOM, NAME, IC)
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value110 (0x6e)
Operandsuint32_t nameIndex
Length5
Stack Uses 
Stack Defsenv
- -

Looks up name on the environment chain and pushes the environment which contains the name onto the stack. If not found, pushes global lexical environment onto the stack.

-
-
JSOP_DEFCONST [-0, +0] (ATOM)
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value128 (0x80)
Operandsuint32_t nameIndex
Length5
Stack Uses 
Stack Defs 
- -

Defines the new constant binding on global lexical environment.

- -

Throws if a binding with the same name already exists on the environment, or if a var binding with the same name exists on the global.

-
-
JSOP_DEFFUN [-1, +0]
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value127 (0x7f)
Operands 
Length1
Stack Usesfun
Stack Defs 
- -

Defines the given function on the current scope.

- -

This is used for global scripts and also in some cases for function scripts where use of dynamic scoping inhibits optimization.

-
-
JSOP_DEFLET [-0, +0] (ATOM)
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value162 (0xa2)
Operandsuint32_t nameIndex
Length5
Stack Uses 
Stack Defs 
- -

Defines the new mutable binding on global lexical environment.

- -

Throws if a binding with the same name already exists on the environment, or if a var binding with the same name exists on the global.

-
-
JSOP_DEFVAR [-0, +0] (ATOM)
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value129 (0x81)
Operandsuint32_t nameIndex
Length5
Stack Uses 
Stack Defs 
- -

Defines the new binding on the frame's current variables-object (the environment on the environment chain designated to receive new variables).

- -

Throws if the current variables-object is the global object and a binding with the same name exists on the global lexical environment.

- -

This is used for global scripts and also in some cases for function scripts where use of dynamic scoping inhibits optimization.

-
-
JSOP_DELNAME [-0, +1] (ATOM, NAME, CHECKSLOPPY)
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value36 (0x24)
Operandsuint32_t nameIndex
Length5
Stack Uses 
Stack Defssucceeded
- -

Looks up name on the environment chain and deletes it, pushes true onto the stack if succeeded (if the property was present and deleted or if the property wasn't present in the first place), false if not.

- -

Strict mode code should never contain this opcode.

-
-
JSOP_GETIMPORT [-0, +1] (ATOM, NAME, TYPESET, IC)
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value176 (0xb0)
Operandsuint32_t nameIndex
Length5
Stack Uses 
Stack Defsval
- -

Gets the value of a module import by name and pushes it onto the stack.

-
-
JSOP_GETNAME [-0, +1] (ATOM, NAME, TYPESET, IC)
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value59 (0x3b)
Operandsuint32_t nameIndex
Length5
Stack Uses 
Stack Defsval
- -

Looks up name on the environment chain and pushes its value onto the stack.

-
-
JSOP_SETNAME [-2, +1] (ATOM, NAME, PROPSET, DETECTING, CHECKSLOPPY, IC)
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value111 (0x6f)
Operandsuint32_t nameIndex
Length5
Stack Usesenv, val
Stack Defsval
- -

Pops an environment and value from the stack, assigns value to the given name, and pushes the value back on the stack

-
-
JSOP_STRICTSETNAME [-2, +1] (ATOM, NAME, PROPSET, DETECTING, CHECKSTRICT, IC)
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value49 (0x31)
Operandsuint32_t nameIndex
Length5
Stack Usesenv, val
Stack Defsval
- -

Pops a environment and value from the stack, assigns value to the given name, and pushes the value back on the stack. If the set failed, then throw a TypeError, per usual strict mode semantics.

-
-
- -

Free Variables

- -
-
JSOP_BINDGNAME [-0, +1] (ATOM, NAME, GNAME, IC)
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value214 (0xd6)
Operandsuint32_t nameIndex
Length5
Stack Uses 
Stack Defsglobal
- -

Pushes the global environment onto the stack if the script doesn't have a non-syntactic global scope. Otherwise will act like JSOP_BINDNAME.

- -

nameIndex is only used when acting like JSOP_BINDNAME.

-
-
JSOP_BINDVAR [-0, +1]
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value213 (0xd5)
Operands 
Length1
Stack Uses 
Stack Defsenv
- -

Pushes the nearest var environment.

-
-
JSOP_GETGNAME [-0, +1] (ATOM, NAME, TYPESET, GNAME, IC)
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value154 (0x9a)
Operandsuint32_t nameIndex
Length5
Stack Uses 
Stack Defsval
- -

Looks up name on global environment and pushes its value onto the stack, unless the script has a non-syntactic global scope, in which case it acts just like JSOP_NAME.

- -

Free variable references that must either be found on the global or a ReferenceError.

-
-
JSOP_INITGLEXICAL [-1, +1] (ATOM, NAME, PROPINIT, GNAME, IC)
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value161 (0xa1)
Operandsuint32_t nameIndex
Length5
Stack Usesval
Stack Defsval
- -

Initializes an uninitialized global lexical binding with the top of stack value.

-
-
JSOP_SETGNAME [-2, +1] (ATOM, NAME, PROPSET, DETECTING, GNAME, CHECKSLOPPY, IC)
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value155 (0x9b)
Operandsuint32_t nameIndex
Length5
Stack Usesenv, val
Stack Defsval
- -

Pops the top two values on the stack as val and env, sets property of env as val and pushes val back on the stack.

- -

env should be the global lexical environment unless the script has a non-syntactic global scope, in which case acts like JSOP_SETNAME.

-
-
JSOP_STRICTSETGNAME [-2, +1] (ATOM, NAME, PROPSET, DETECTING, GNAME, CHECKSTRICT, IC)
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value156 (0x9c)
Operandsuint32_t nameIndex
Length5
Stack Usesenv, val
Stack Defsval
- -

Pops the top two values on the stack as val and env, sets property of env as val and pushes val back on the stack. Throws a TypeError if the set fails, per strict mode semantics.

- -

env should be the global lexical environment unless the script has a non-syntactic global scope, in which case acts like JSOP_STRICTSETNAME.

-
-
- -

Local Variables

- -
-
JSOP_CHECKLEXICAL [-0, +0] (LOCAL, NAME)
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value138 (0x8a)
Operandsuint24_t localno
Length4
Stack Uses 
Stack Defs 
- -

Checks if the value of the local variable is the JS_UNINITIALIZED_LEXICAL magic, throwing an error if so.

-
-
JSOP_GETLOCAL [-0, +1] (LOCAL, NAME)
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value86 (0x56)
Operandsuint24_t localno
Length4
Stack Uses 
Stack Defsval
- -

Pushes the value of local variable onto the stack.

-
-
JSOP_INITLEXICAL [-1, +1] (LOCAL, NAME, DETECTING)
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value139 (0x8b)
Operandsuint24_t localno
Length4
Stack Usesv
Stack Defsv
- -

Initializes an uninitialized local lexical binding with the top of stack value.

-
-
JSOP_SETLOCAL [-1, +1] (LOCAL, NAME, DETECTING)
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value87 (0x57)
Operandsuint24_t localno
Length4
Stack Usesv
Stack Defsv
- -

Stores the top stack value to the given local.

-
-
JSOP_THROWSETCALLEE [-1, +1]
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value179 (0xb3)
Operands 
Length1
Stack Usesv
Stack Defsv
- -

Throws a runtime TypeError for invalid assignment to the callee in a named lambda, which is always a const binding. This is a different bytecode than JSOP_SETCONST because the named lambda callee, if not closed over, does not have a frame slot to look up the name with for the error message.

-
-
JSOP_THROWSETCONST [-1, +1] (LOCAL, NAME, DETECTING)
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value169 (0xa9)
Operandsuint24_t localno
Length4
Stack Usesv
Stack Defsv
- -

Throws a runtime TypeError for invalid assignment to const. The localno is used for better error messages.

-
-
- -

Aliased Variables

- -
-
JSOP_CHECKALIASEDLEXICAL [-0, +0] (ENVCOORD, NAME)
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value140 (0x8c)
Operandsuint8_t hops, uint24_t slot
Length5
Stack Uses 
Stack Defs 
- -

Checks if the value of the aliased variable is the JS_UNINITIALIZED_LEXICAL magic, throwing an error if so.

-
-
JSOP_GETALIASEDVAR [-0, +1] (ENVCOORD, NAME, TYPESET, IC)
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value136 (0x88)
Operandsuint8_t hops, uint24_t slot
Length5
Stack Uses 
Stack DefsaliasedVar
- -

Pushes aliased variable onto the stack.

- -

An "aliased variable" is a var, let, or formal arg that is aliased. Sources of aliasing include: nested functions accessing the vars of an enclosing function, function statements that are conditionally executed, eval, with, and arguments. All of these cases require creating a CallObject to own the aliased variable.

- -

An ALIASEDVAR opcode contains the following immediates:

- -
uint8 hops: the number of environment objects to skip to find the
-             EnvironmentObject containing the variable being accessed
-uint24 slot: the slot containing the variable in the EnvironmentObject
-             (this 'slot' does not include RESERVED_SLOTS).
-
-
-
JSOP_INITALIASEDLEXICAL [-1, +1] (ENVCOORD, NAME, PROPINIT, DETECTING)
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value141 (0x8d)
Operandsuint8_t hops, uint24_t slot
Length5
Stack Usesv
Stack Defsv
- -

Initializes an uninitialized aliased lexical binding with the top of stack value.

-
-
JSOP_SETALIASEDVAR [-1, +1] (ENVCOORD, NAME, PROPSET, DETECTING)
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value137 (0x89)
Operandsuint8_t hops, uint24_t slot
Length5
Stack Usesv
Stack Defsv
- -

Sets aliased variable as the top of stack value.

-
-
JSOP_THROWSETALIASEDCONST [-1, +1] (ENVCOORD, NAME, DETECTING)
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value170 (0xaa)
Operandsuint8_t hops, uint24_t slot
Length5
Stack Usesv
Stack Defsv
- -

Throws a runtime TypeError for invalid assignment to const. The environment coordinate is used for better error messages.

-
-
- -

Intrinsics

- -
-
JSOP_GETINTRINSIC [-0, +1] (ATOM, NAME, TYPESET, IC)
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value143 (0x8f)
Operandsuint32_t nameIndex
Length5
Stack Uses 
Stack Defsintrinsic[name]
- -

Pushes the value of the intrinsic onto the stack.

- -

Intrinsic names are emitted instead of JSOP_*NAME ops when the CompileOptions flag selfHostingMode is set.

- -

They are used in self-hosted code to access other self-hosted values and intrinsic functions the runtime doesn't give client JS code access to.

-
-
JSOP_SETINTRINSIC [-1, +1] (ATOM, NAME, DETECTING)
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value144 (0x90)
Operandsuint32_t nameIndex
Length5
Stack Usesval
Stack Defsval
- -

Stores the top stack value in the specified intrinsic.

-
-
- -

Block-local Scope

- -
-
JSOP_FRESHENLEXICALENV [-0, +0]
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value197 (0xc5)
Operands 
Length1
Stack Uses 
Stack Defs 
- -

Replaces the current block on the env chain with a fresh block that copies all the bindings in the block. This operation implements the behavior of inducing a fresh lexical environment for every iteration of a for(let ...; ...; ...) loop, if any declarations induced by such a loop are captured within the loop.

-
-
JSOP_POPLEXICALENV [-0, +0]
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value200 (0xc8)
Operands 
Length1
Stack Uses 
Stack Defs 
- -

Pops lexical environment from the env chain.

-
-
JSOP_PUSHLEXICALENV [-0, +0] (SCOPE)
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value199 (0xc7)
Operandsuint32_t scopeIndex
Length5
Stack Uses 
Stack Defs 
- -

Pushes lexical environment onto the env chain.

-
-
JSOP_RECREATELEXICALENV [-0, +0]
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value198 (0xc6)
Operands 
Length1
Stack Uses 
Stack Defs 
- -

Recreates the current block on the env chain with a fresh block with uninitialized bindings. This operation implements the behavior of inducing a fresh lexical environment for every iteration of a for-in/of loop whose loop-head has a (captured) lexical declaration.

-
-
- -

This

- -
-
JSOP_CHECKRETURN [-1, +0]
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value190 (0xbe)
Operands 
Length1
Stack Usesthis
Stack Defs 
- -

Check if a derived class constructor has a valid return value and this value before it returns. If the return value is not an object, stores the this value to the return value slot.

-
-
JSOP_CHECKTHIS [-1, +1]
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value189 (0xbd)
Operands 
Length1
Stack Usesthis
Stack Defsthis
- -

Throw if the value on top of the stack is the TDZ MagicValue. Used in derived class constructors.

-
-
JSOP_CHECKTHISREINIT [-1, +1]
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value191 (0xbf)
Operands 
Length1
Stack Usesthis
Stack Defsthis
- -

Throw an exception if the value on top of the stack is not the TDZ MagicValue. Used in derived class constructors.

-
-
JSOP_FUNCTIONTHIS [-0, +1]
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value185 (0xb9)
Operands 
Length1
Stack Uses 
Stack Defsthis
- -

Determines the this value for current function frame and pushes it onto the stack. Emitted in the prologue of functions with a this-binding.

-
-
JSOP_GIMPLICITTHIS [-0, +1] (ATOM)
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value157 (0x9d)
Operandsuint32_t nameIndex
Length5
Stack Uses 
Stack Defsthis
- -

Pushes the implicit this value for calls to the associated name onto the stack; only used when the implicit this might be derived from a non-syntactic scope (instead of the global itself).

- -

Note that code evaluated via the Debugger API uses DebugEnvironmentProxy objects on its scope chain, which are non-syntactic environments that refer to syntactic environments. As a result, the binding we want may be held by a syntactic environments such as CallObject or VarEnvrionmentObject.

-
-
JSOP_GLOBALTHIS [-0, +1]
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value186 (0xba)
Operands 
Length1
Stack Uses 
Stack Defsthis
- -

Pushes this value for current stack frame onto the stack. Emitted when this refers to the global this.

-
-
JSOP_IMPLICITTHIS [-0, +1] (ATOM)
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value226 (0xe2)
Operandsuint32_t nameIndex
Length5
Stack Uses 
Stack Defsthis
- -

Pushes the implicit this value for calls to the associated name onto the stack.

-
-
- -

Super

- -
-
JSOP_SUPERBASE [-1, +1]
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value103 (0x67)
Operands 
Length1
Stack Usescallee
Stack DefshomeObjectProto
- -

Pushes the prototype of the home object for |callee| onto the stack.

-
-
JSOP_SUPERFUN [-1, +1]
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value164 (0xa4)
Operands 
Length1
Stack Usescallee
Stack DefssuperFun
- -

Push the function to invoke with |super()|. This is the prototype of the function passed in as |callee|.

-
-
- -

Arguments

- -
-
JSOP_ARGUMENTS [-0, +1]
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value9 (0x09)
Operands 
Length1
Stack Uses 
Stack Defsarguments
- -

Pushes the arguments object for the current function activation.

- -

If JSScript is not marked needsArgsObj, then a JS_OPTIMIZED_ARGUMENTS magic value is pushed. Otherwise, a proper arguments object is constructed and pushed.

- -

This opcode requires that the function does not have rest parameter.

-
-
JSOP_CALLEE [-0, +1]
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value132 (0x84)
Operands 
Length1
Stack Uses 
Stack Defscallee
- -

Pushes current callee onto the stack.

- -

Used for named function expression self-naming, if lightweight.

-
-
JSOP_ENVCALLEE [-0, +1] (UINT8)
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value206 (0xce)
Operandsuint8_t numHops
Length2
Stack Uses 
Stack Defscallee
- -

Load the callee stored in a CallObject on the environment chain. The numHops operand is the number of environment objects to skip on the environment chain.

-
-
JSOP_GETARG [-0, +1] (QARG, NAME)
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value84 (0x54)
Operandsuint16_t argno
Length3
Stack Uses 
Stack Defsarguments[argno]
- -

Fast get op for function arguments and local variables.

- -

Pushes arguments[argno] onto the stack.

-
-
JSOP_NEWTARGET [-0, +1]
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value148 (0x94)
Operands 
Length1
Stack Uses 
Stack Defsnew.target
- -

Push "new.target"

-
-
JSOP_REST [-0, +1] (TYPESET, IC)
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value224 (0xe0)
Operands 
Length1
Stack Uses 
Stack Defsrest
- -

Creates rest parameter array for current function call, and pushes it onto the stack.

-
-
JSOP_SETARG [-1, +1] (QARG, NAME)
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value85 (0x55)
Operandsuint16_t argno
Length3
Stack Usesv
Stack Defsv
- -

Fast set op for function arguments and local variables.

- -

Sets arguments[argno] as the top of stack value.

-
-
- -

Var Scope

- -
-
JSOP_POPVARENV [-0, +0]
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value181 (0xb5)
Operands 
Length1
Stack Uses 
Stack Defs 
- -

Pops a var environment from the env chain.

-
-
JSOP_PUSHVARENV [-0, +0] (SCOPE)
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value180 (0xb4)
Operandsuint32_t scopeIndex
Length5
Stack Uses 
Stack Defs 
- -

Pushes a var environment onto the env chain.

-
-
- -

Modules

- -
-
JSOP_DYNAMIC_IMPORT [-1, +1]
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value233 (0xe9)
Operands 
Length1
Stack Usesarg
Stack Defsrval
- -

Dynamic import of the module specified by the string value on the top of the stack.

-
-
JSOP_IMPORTMETA [-0, +1]
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value232 (0xe8)
Operands 
Length1
Stack Uses 
Stack Defsimport.meta
- -

Push "import.meta"

-
-
- -

Operators

- -

Comparison Operators

- -
-
JSOP_EQ [-2, +1] (DETECTING, IC)
- JSOP_GE [-2, +1] (IC)
- JSOP_GT [-2, +1] (IC)
- JSOP_LE [-2, +1] (IC)
- JSOP_LT [-2, +1] (IC)
- JSOP_NE [-2, +1] (DETECTING, IC)
-
- - - - - - - - - - - - - - - - - - - - - - - -
ValueJSOP_EQ: 18 (0x12)
- JSOP_GE: 23 (0x17)
- JSOP_GT: 22 (0x16)
- JSOP_LE: 21 (0x15)
- JSOP_LT: 20 (0x14)
- JSOP_NE: 19 (0x13)
Operands 
Length1
Stack Useslval, rval
Stack Defs(lval OP rval)
- -

Pops the top two values from the stack and pushes the result of comparing them.

-
-
JSOP_STRICTEQ [-2, +1] (DETECTING, IC)
- JSOP_STRICTNE [-2, +1] (DETECTING, IC)
-
- - - - - - - - - - - - - - - - - - - - - - - -
ValueJSOP_STRICTEQ: 72 (0x48)
- JSOP_STRICTNE: 73 (0x49)
Operands 
Length1
Stack Useslval, rval
Stack Defs(lval OP rval)
- -

Pops the top two values from the stack, then pushes the result of applying the operator to the two values.

-
-
- -

Arithmetic Operators

- -
-
JSOP_ADD [-2, +1] (IC)
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value27 (0x1b)
Operands 
Length1
Stack Useslval, rval
Stack Defs(lval + rval)
- -

Pops the top two values lval and rval from the stack, then pushes the result of lval + rval.

-
-
JSOP_DEC [-1, +1] (IC)
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value235 (0xeb)
Operands 
Length1
Stack Usesval
Stack Defs(val - 1)
- -

Pops the numeric value val from the stack, then pushes val - 1.

-
-
JSOP_INC [-1, +1] (IC)
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value234 (0xea)
Operands 
Length1
Stack Usesval
Stack Defs(val + 1)
- -

Pops the numeric value val from the stack, then pushes val + 1.

-
-
JSOP_DIV [-2, +1] (IC)
- JSOP_MOD [-2, +1] (IC)
- JSOP_MUL [-2, +1] (IC)
- JSOP_SUB [-2, +1] (IC)
-
- - - - - - - - - - - - - - - - - - - - - - - -
ValueJSOP_DIV: 30 (0x1e)
- JSOP_MOD: 31 (0x1f)
- JSOP_MUL: 29 (0x1d)
- JSOP_SUB: 28 (0x1c)
Operands 
Length1
Stack Useslval, rval
Stack Defs(lval OP rval)
- -

Pops the top two values lval and rval from the stack, then pushes the result of applying the arithmetic operation to them.

-
-
JSOP_NEG [-1, +1] (IC)
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value34 (0x22)
Operands 
Length1
Stack Usesval
Stack Defs(-val)
- -

Pops the value val from the stack, then pushes -val.

-
-
JSOP_POS [-1, +1]
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value35 (0x23)
Operands 
Length1
Stack Usesval
Stack Defs(+val)
- -

Pops the value val from the stack, then pushes +val. (+val is the value converted to a number.)

-
-
JSOP_POW [-2, +1] (IC)
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value150 (0x96)
Operands 
Length1
Stack Useslval, rval
Stack Defs(lval ** rval)
- -

Pops the top two values lval and rval from the stack, then pushes the result of Math.pow(lval, rval).

-
-
JSOP_TONUMERIC [-1, +1]
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value236 (0xec)
Operands 
Length1
Stack Usesval
Stack DefsToNumeric(val)
- -

Pop val from the stack, then push the result of ToNumeric(val).

-
-
- -

Bitwise Logical Operators

- -
-
JSOP_BITAND [-2, +1] (IC)
- JSOP_BITOR [-2, +1] (IC)
- JSOP_BITXOR [-2, +1] (IC)
-
- - - - - - - - - - - - - - - - - - - - - - - -
ValueJSOP_BITAND: 17 (0x11)
- JSOP_BITOR: 15 (0x0f)
- JSOP_BITXOR: 16 (0x10)
Operands 
Length1
Stack Useslval, rval
Stack Defs(lval OP rval)
- -

Pops the top two values lval and rval from the stack, then pushes the result of the operation applied to the two operands, converting both to 32-bit signed integers if necessary.

-
-
JSOP_BITNOT [-1, +1] (IC)
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value33 (0x21)
Operands 
Length1
Stack Usesval
Stack Defs(~val)
- -

Pops the value val from the stack, then pushes ~val.

-
-
- -

Bitwise Shift Operators

- -
-
JSOP_LSH [-2, +1] (IC)
- JSOP_RSH [-2, +1] (IC)
-
- - - - - - - - - - - - - - - - - - - - - - - -
ValueJSOP_LSH: 24 (0x18)
- JSOP_RSH: 25 (0x19)
Operands 
Length1
Stack Useslval, rval
Stack Defs(lval OP rval)
- -

Pops the top two values lval and rval from the stack, then pushes the result of the operation applied to the operands.

-
-
JSOP_URSH [-2, +1] (IC)
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value26 (0x1a)
Operands 
Length1
Stack Useslval, rval
Stack Defs(lval >>> rval)
- -

Pops the top two values lval and rval from the stack, then pushes lval >>> rval.

-
-
- -

Logical Operators

- -
-
JSOP_NOT [-1, +1] (DETECTING, IC)
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value32 (0x20)
Operands 
Length1
Stack Usesval
Stack Defs(!val)
- -

Pops the value val from the stack, then pushes !val.

-
-
- -

Special Operators

- -
-
JSOP_DELELEM [-2, +1] (ELEM, CHECKSLOPPY)
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value38 (0x26)
Operands 
Length1
Stack Usesobj, propval
Stack Defssucceeded
- -

Pops the top two values on the stack as propval and obj, deletes propval property from obj, pushes true onto the stack if succeeded, false if not.

-
-
JSOP_DELPROP [-1, +1] (ATOM, PROP, CHECKSLOPPY)
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value37 (0x25)
Operandsuint32_t nameIndex
Length5
Stack Usesobj
Stack Defssucceeded
- -

Pops the top of stack value, deletes property from it, pushes true onto the stack if succeeded, false if not.

-
-
JSOP_IN [-2, +1] (IC)
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value113 (0x71)
Operands 
Length1
Stack Usesid, obj
Stack Defs(id in obj)
- -

Pops the top two values id and obj from the stack, then pushes id in obj. This will throw a TypeError if obj is not an object.

- -

Note that obj is the top value.

-
-
JSOP_INSTANCEOF [-2, +1] (IC)
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value114 (0x72)
Operands 
Length1
Stack Usesobj, ctor
Stack Defs(obj instanceof ctor)
- -

Pops the top two values obj and ctor from the stack, then pushes obj instanceof ctor. This will throw a TypeError if obj is not an object.

-
-
JSOP_STRICTDELPROP [-1, +1] (ATOM, PROP, CHECKSTRICT)
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value46 (0x2e)
Operandsuint32_t nameIndex
Length5
Stack Usesobj
Stack Defssucceeded
- -

Pops the top of stack value and attempts to delete the given property from it. Pushes true onto success, else throws a TypeError per strict mode property-deletion requirements.

-
-
JSOP_TYPEOF [-1, +1] (DETECTING, IC)
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value39 (0x27)
Operands 
Length1
Stack Usesval
Stack Defs(typeof val)
- -

Pops the value val from the stack, then pushes typeof val.

-
-
JSOP_TYPEOFEXPR [-1, +1] (DETECTING, IC)
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value196 (0xc4)
Operands 
Length1
Stack Usesval
Stack Defs(typeof val)
- -

Pops the top stack value as val and pushes typeof val. Note that this opcode isn't used when, in the original source code, val is a name -- see JSOP_TYPEOF for that. (This is because typeof undefinedName === "undefined".)

-
-
JSOP_VOID [-1, +1]
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value40 (0x28)
Operands 
Length1
Stack Usesval
Stack Defsundefined
- -

Pops the top value on the stack and pushes undefined.

-
-
- -

Stack Operations

- -
-
JSOP_DUP [-1, +2]
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value12 (0x0c)
Operands 
Length1
Stack Usesv
Stack Defsv, v
- -

Pushes a copy of the top value on the stack.

-
-
JSOP_DUP2 [-2, +4]
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value13 (0x0d)
Operands 
Length1
Stack Usesv1, v2
Stack Defsv1, v2, v1, v2
- -

Duplicates the top two values on the stack.

-
-
JSOP_DUPAT [-0, +1] (UINT24)
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value44 (0x2c)
Operandsuint24_t n
Length4
Stack Usesv[n], v[n-1], ..., v[1], v[0]
Stack Defsv[n], v[n-1], ..., v[1], v[0], v[n]
- -

Duplicates the Nth value from the top onto the stack.

-
-
JSOP_PICK [-0, +0] (UINT8)
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value133 (0x85)
Operandsuint8_t n
Length2
Stack Usesv[n], v[n-1], ..., v[1], v[0]
Stack Defsv[n-1], ..., v[1], v[0], v[n]
- -

Picks the nth element from the stack and moves it to the top of the stack.

-
-
JSOP_POP [-1, +0]
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value81 (0x51)
Operands 
Length1
Stack Usesv
Stack Defs 
- -

Pops the top value off the stack.

-
-
JSOP_POPN [-n, +0] (UINT16)
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value11 (0x0b)
Operandsuint16_t n
Length3
Stack Usesv[n-1], ..., v[1], v[0]
Stack Defs 
- -

Pops the top n values from the stack.

-
-
JSOP_SWAP [-2, +2]
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value10 (0x0a)
Operands 
Length1
Stack Usesv1, v2
Stack Defsv2, v1
- -

Swaps the top two values on the stack. This is useful for things like post-increment/decrement.

-
-
JSOP_UNPICK [-0, +0] (UINT8)
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value183 (0xb7)
Operandsuint8_t n
Length2
Stack Usesv[n], v[n-1], ..., v[1], v[0]
Stack Defsv[0], v[n], v[n-1], ..., v[1]
- -

Moves the top of the stack value under the nth element of the stack. Note: n must NOT be 0.

-
-
- -

Debugger

- -
-
JSOP_DEBUGAFTERYIELD [-0, +0]
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value208 (0xd0)
Operands 
Length1
Stack Uses 
Stack Defs 
- -

Bytecode emitted after yield expressions to help the Debugger fix up the frame in the JITs. No-op in the interpreter.

-
-
- -

Literals

- -

Constants

- -
-
JSOP_BIGINT [-0, +1] (BIGINT)
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value237 (0xed)
Operandsuint32_t constIndex
Length5
Stack Uses 
Stack Defsval
- -

Pushes a BigInt constant onto the stack.

-
-
JSOP_BUILTINPROTO [-0, +1] (UINT8)
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value221 (0xdd)
Operandsuint8_t kind
Length2
Stack Uses 
Stack Defs%BuiltinPrototype%
- -

Pushes the current global's builtin prototype for a given proto key.

-
-
JSOP_DOUBLE [-0, +1] (DOUBLE)
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value60 (0x3c)
OperandsDoubleValue literal
Length9
Stack Uses 
Stack Defsval
- -

Pushes numeric constant onto the stack.

-
-
JSOP_FALSE [-0, +1]
- JSOP_TRUE [-0, +1]
-
- - - - - - - - - - - - - - - - - - - - - - - -
ValueJSOP_FALSE: 66 (0x42)
- JSOP_TRUE: 67 (0x43)
Operands 
Length1
Stack Uses 
Stack Defstrue/false
- -

Pushes boolean value onto the stack.

-
-
JSOP_INT32 [-0, +1] (INT32)
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value216 (0xd8)
Operandsint32_t val
Length5
Stack Uses 
Stack Defsval
- -

Pushes 32-bit int immediate integer operand onto the stack.

-
-
JSOP_INT8 [-0, +1] (INT8)
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value215 (0xd7)
Operandsint8_t val
Length2
Stack Uses 
Stack Defsval
- -

Pushes 8-bit int immediate integer operand onto the stack.

-
-
JSOP_IS_CONSTRUCTING [-0, +1]
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value65 (0x41)
Operands 
Length1
Stack Uses 
Stack DefsJS_IS_CONSTRUCTING
- -

Pushes JS_IS_CONSTRUCTING

-
-
JSOP_NULL [-0, +1]
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value64 (0x40)
Operands 
Length1
Stack Uses 
Stack Defsnull
- -

Pushes null onto the stack.

-
-
JSOP_ONE [-0, +1]
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value63 (0x3f)
Operands 
Length1
Stack Uses 
Stack Defs1
- -

Pushes 1 onto the stack.

-
-
JSOP_STRING [-0, +1] (ATOM)
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value61 (0x3d)
Operandsuint32_t atomIndex
Length5
Stack Uses 
Stack Defsatom
- -

Pushes string constant onto the stack.

-
-
JSOP_SYMBOL [-0, +1] (UINT8)
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value45 (0x2d)
Operandsuint8_t symbol (the JS::SymbolCode of the symbol to use)
Length2
Stack Uses 
Stack Defssymbol
- -

Push a well-known symbol onto the operand stack.

-
-
JSOP_UINT16 [-0, +1] (UINT16)
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value88 (0x58)
Operandsuint16_t val
Length3
Stack Uses 
Stack Defsval
- -

Pushes unsigned 16-bit int immediate integer operand onto the stack.

-
-
JSOP_UINT24 [-0, +1] (UINT24)
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value188 (0xbc)
Operandsuint24_t val
Length4
Stack Uses 
Stack Defsval
- -

Pushes unsigned 24-bit int immediate integer operand onto the stack.

-
-
JSOP_UNDEFINED [-0, +1]
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value1 (0x01)
Operands 
Length1
Stack Uses 
Stack Defsundefined
- -

Pushes undefined onto the stack.

-
-
JSOP_UNINITIALIZED [-0, +1]
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value142 (0x8e)
Operands 
Length1
Stack Uses 
Stack Defsuninitialized
- -

Pushes a JS_UNINITIALIZED_LEXICAL value onto the stack, representing an uninitialized lexical binding.

- -

This opcode is used with the JSOP_INITLEXICAL opcode.

-
-
JSOP_ZERO [-0, +1]
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value62 (0x3e)
Operands 
Length1
Stack Uses 
Stack Defs0
- -

Pushes 0 onto the stack.

-
-
- -

Object

- -
-
JSOP_CALLELEM [-2, +1] (ELEM, TYPESET, IC)
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value193 (0xc1)
Operands 
Length1
Stack Usesobj, propval
Stack Defsobj[propval]
- -

Pops the top two values on the stack as propval and obj, pushes propval property of obj onto the stack. Requires the value under obj to be the receiver of the following call.

- -

Like JSOP_GETELEM but for call context.

-
-
JSOP_CALLPROP [-1, +1] (ATOM, PROP, TYPESET, IC)
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value184 (0xb8)
Operandsuint32_t nameIndex
Length5
Stack Usesobj
Stack Defsobj[name]
- -

Pops the top of stack value, pushes property of it onto the stack. Requires the value under obj to be the receiver of the following call.

- -

Like JSOP_GETPROP but for call context.

-
-
JSOP_CALLSITEOBJ [-0, +1] (OBJECT)
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value101 (0x65)
Operandsuint32_t objectIndex
Length5
Stack Uses 
Stack Defsobj
- -

Pushes the call site object specified by objectIndex onto the stack. Defines the raw property specified by objectIndex + 1 on the call site object and freezes both the call site object as well as its raw property.

-
-
JSOP_CHECKCLASSHERITAGE [-1, +1]
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value51 (0x33)
Operands 
Length1
Stack Usesheritage
Stack Defsheritage
- -

Ensures the result of a class's heritage expression is either null or a constructor.

-
-
JSOP_CHECKOBJCOERCIBLE [-1, +1]
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value163 (0xa3)
Operands 
Length1
Stack Usesval
Stack Defsval
- -

Throw if the value on the stack is not coerscible to an object (is |null| or |undefined|).

-
-
JSOP_GETBOUNDNAME [-1, +1] (ATOM, NAME, TYPESET, IC)
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value195 (0xc3)
Operandsuint32_t nameIndex
Length5
Stack Usesenv
Stack Defsv
- -

Pops an environment, gets the value of a bound name on it. If the name is not bound to the environment, throw a ReferenceError. Used in conjunction with BINDNAME.

-
-
JSOP_GETELEM [-2, +1] (ELEM, TYPESET, IC)
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value55 (0x37)
Operands 
Length1
Stack Usesobj, propval
Stack Defsobj[propval]
- -

Pops the top two values on the stack as propval and obj, pushes propval property of obj onto the stack.

-
-
JSOP_GETELEM_SUPER [-3, +1] (ELEM, TYPESET, IC)
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value125 (0x7d)
Operands 
Length1
Stack Usesreceiver, propval, obj
Stack Defsobj[propval]
- -

LIKE JSOP_GETELEM but takes receiver on stack, and the propval is evaluated before the obj.

-
-
JSOP_GETPROP [-1, +1] (ATOM, PROP, TYPESET, IC)
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value53 (0x35)
Operandsuint32_t nameIndex
Length5
Stack Usesobj
Stack Defsobj[name]
- -

Pops the top of stack value, pushes property of it onto the stack.

-
-
JSOP_GETPROP_SUPER [-2, +1] (ATOM, PROP, TYPESET, IC)
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value104 (0x68)
Operandsuint32_t nameIndex
Length5
Stack Usesreceiver, obj
Stack Defsobj[name]
- -

Pops the top two values, and pushes the property of one, using the other as the receiver.

-
-
JSOP_INITELEM [-3, +1] (ELEM, PROPINIT, DETECTING, IC)
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value94 (0x5e)
Operands 
Length1
Stack Usesobj, id, val
Stack Defsobj
- -

Initialize a numeric property in an object literal, like {1: x}.

- -

Pops the top three values on the stack as val, id and obj, defines id property of obj as val, pushes obj onto the stack.

-
-
JSOP_INITELEM_GETTER [-3, +1] (ELEM, PROPINIT, DETECTING)
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value99 (0x63)
Operands 
Length1
Stack Usesobj, id, val
Stack Defsobj
- -

Initialize a numeric getter in an object literal like {get 2() {}}.

- -

Pops the top three values on the stack as val, id and obj, defines id getter of obj as val, pushes obj onto the stack.

-
-
JSOP_INITELEM_SETTER [-3, +1] (ELEM, PROPINIT, DETECTING)
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value100 (0x64)
Operands 
Length1
Stack Usesobj, id, val
Stack Defsobj
- -

Initialize a numeric setter in an object literal like {set 2(v) {}}.

- -

Pops the top three values on the stack as val, id and obj, defines id setter of obj as val, pushes obj onto the stack.

-
-
JSOP_INITHIDDENELEM [-3, +1] (ELEM, PROPINIT, DETECTING, IC)
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value175 (0xaf)
Operands 
Length1
Stack Usesobj, id, val
Stack Defsobj
- -

Initialize a non-enumerable numeric property in an object literal, like {1: x}.

- -

Pops the top three values on the stack as val, id and obj, defines id property of obj as val, pushes obj onto the stack.

-
-
JSOP_INITHIDDENELEM_GETTER [-3, +1] (ELEM, PROPINIT, DETECTING)
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value173 (0xad)
Operands 
Length1
Stack Usesobj, id, val
Stack Defsobj
- -

Initialize a non-enumerable numeric getter in an object literal like {get 2() {}}.

- -

Pops the top three values on the stack as val, id and obj, defines id getter of obj as val, pushes obj onto the stack.

-
-
JSOP_INITHIDDENELEM_SETTER [-3, +1] (ELEM, PROPINIT, DETECTING)
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value174 (0xae)
Operands 
Length1
Stack Usesobj, id, val
Stack Defsobj
- -

Initialize a non-enumerable numeric setter in an object literal like {set 2(v) {}}.

- -

Pops the top three values on the stack as val, id and obj, defines id setter of obj as val, pushes obj onto the stack.

-
-
JSOP_INITHIDDENPROP [-2, +1] (ATOM, PROP, PROPINIT, DETECTING, IC)
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value147 (0x93)
Operandsuint32_t nameIndex
Length5
Stack Usesobj, val
Stack Defsobj
- -

Initialize a non-enumerable data-property on an object.

- -

Pops the top two values on the stack as val and obj, defines nameIndex property of obj as val, pushes obj onto the stack.

-
-
JSOP_INITHIDDENPROP_GETTER [-2, +1] (ATOM, PROP, PROPINIT, DETECTING)
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value171 (0xab)
Operandsuint32_t nameIndex
Length5
Stack Usesobj, val
Stack Defsobj
- -

Initialize a non-enumerable getter in an object literal.

- -

Pops the top two values on the stack as val and obj, defines getter of obj as val, pushes obj onto the stack.

-
-
JSOP_INITHIDDENPROP_SETTER [-2, +1] (ATOM, PROP, PROPINIT, DETECTING)
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value172 (0xac)
Operandsuint32_t nameIndex
Length5
Stack Usesobj, val
Stack Defsobj
- -

Initialize a non-enumerable setter in an object literal.

- -

Pops the top two values on the stack as val and obj, defines setter of obj as val, pushes obj onto the stack.

-
-
JSOP_INITHOMEOBJECT [-2, +1]
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value92 (0x5c)
Operands 
Length1
Stack Usesfun, homeObject
Stack Defsfun
- -

Initialize the home object for functions with super bindings.

- -

This opcode takes the function and the object to be the home object, does the set, and leaves the function on the stack.

-
-
JSOP_INITLOCKEDPROP [-2, +1] (ATOM, PROP, PROPINIT, DETECTING, IC)
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value146 (0x92)
Operandsuint32_t nameIndex
Length5
Stack Usesobj, val
Stack Defsobj
- -

Initialize a non-configurable, non-writable, non-enumerable data-property on an object.

- -

Pops the top two values on the stack as val and obj, defines nameIndex property of obj as val, pushes obj onto the stack.

-
-
JSOP_INITPROP [-2, +1] (ATOM, PROP, PROPINIT, DETECTING, IC)
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value93 (0x5d)
Operandsuint32_t nameIndex
Length5
Stack Usesobj, val
Stack Defsobj
- -

Initialize a named property in an object literal, like {a: x}.

- -

Pops the top two values on the stack as val and obj, defines nameIndex property of obj as val, pushes obj onto the stack.

-
-
JSOP_INITPROP_GETTER [-2, +1] (ATOM, PROP, PROPINIT, DETECTING)
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value97 (0x61)
Operandsuint32_t nameIndex
Length5
Stack Usesobj, val
Stack Defsobj
- -

Initialize a getter in an object literal.

- -

Pops the top two values on the stack as val and obj, defines getter of obj as val, pushes obj onto the stack.

-
-
JSOP_INITPROP_SETTER [-2, +1] (ATOM, PROP, PROPINIT, DETECTING)
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value98 (0x62)
Operandsuint32_t nameIndex
Length5
Stack Usesobj, val
Stack Defsobj
- -

Initialize a setter in an object literal.

- -

Pops the top two values on the stack as val and obj, defines setter of obj as val, pushes obj onto the stack.

-
-
JSOP_MUTATEPROTO [-2, +1]
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value194 (0xc2)
Operands 
Length1
Stack Usesobj, newProto
Stack Defssucceeded
- -

__proto__: v inside an object initializer.

- -

Pops the top two values on the stack as newProto and obj, sets prototype of obj as newProto, pushes true onto the stack if succeeded, false if not.

-
-
JSOP_NEWINIT [-0, +1] (UINT32, IC)
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value89 (0x59)
Operands(uint32_t extra)
Length5
Stack Uses 
Stack Defsobj
- -

Pushes newly created object onto the stack.

- -

This opcode has four extra bytes so it can be exchanged with JSOP_NEWOBJECT during emit.

-
-
JSOP_NEWOBJECT [-0, +1] (OBJECT, IC)
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value91 (0x5b)
Operandsuint32_t baseobjIndex
Length5
Stack Uses 
Stack Defsobj
- -

Pushes newly created object onto the stack.

- -

This opcode takes an object with the final shape, which can be set at the start and slots then filled in directly.

-
-
JSOP_OBJECT [-0, +1] (OBJECT)
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value80 (0x50)
Operandsuint32_t objectIndex
Length5
Stack Uses 
Stack Defsobj
- -

Pushes deep-cloned object literal or singleton onto the stack.

-
-
JSOP_OBJWITHPROTO [-1, +1]
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value83 (0x53)
Operands 
Length1
Stack Usesproto
Stack Defsobj
- -

Pushes newly created object onto the stack with provided [[Prototype]].

-
-
JSOP_SETELEM [-3, +1] (ELEM, PROPSET, DETECTING, CHECKSLOPPY, IC)
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value56 (0x38)
Operands 
Length1
Stack Usesobj, propval, val
Stack Defsval
- -

Pops the top three values on the stack as val, propval and obj, sets propval property of obj as val, pushes val onto the stack.

-
-
JSOP_SETELEM_SUPER [-4, +1] (ELEM, PROPSET, DETECTING, CHECKSLOPPY)
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value158 (0x9e)
Operands 
Length1
Stack Usesreceiver, propval, obj, val
Stack Defsval
- -

LIKE JSOP_SETELEM, but takes receiver on the stack, and the propval is evaluated before the base.

-
-
JSOP_SETPROP [-2, +1] (ATOM, PROP, PROPSET, DETECTING, CHECKSLOPPY, IC)
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value54 (0x36)
Operandsuint32_t nameIndex
Length5
Stack Usesobj, val
Stack Defsval
- -

Pops the top two values on the stack as val and obj and performs obj.prop = val, pushing val back onto the stack.

-
-
JSOP_SETPROP_SUPER [-3, +1] (ATOM, PROP, PROPSET, DETECTING, CHECKSLOPPY)
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value107 (0x6b)
Operandsuint32_t nameIndex
Length5
Stack Usesreceiver, obj, val
Stack Defsval
- -

Pops the top three values on the stack as val, obj and receiver, and performs obj.prop = val, pushing val back onto the stack.

-
-
JSOP_STRICTDELELEM [-2, +1] (ELEM, CHECKSTRICT)
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value47 (0x2f)
Operands 
Length1
Stack Usesobj, propval
Stack Defssucceeded
- -

Pops the top two values on the stack as propval and obj, and attempts to delete propval property from obj. Pushes true onto the stack on success, else throws a TypeError per strict mode property deletion requirements.

-
-
JSOP_STRICTSETELEM [-3, +1] (ELEM, PROPSET, DETECTING, CHECKSTRICT, IC)
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value57 (0x39)
Operands 
Length1
Stack Usesobj, propval, val
Stack Defsval
- -

Pops the top three values on the stack as val, propval and obj, sets propval property of obj as val, pushes val onto the stack. Throws a TypeError if the set fails, per strict mode semantics.

-
-
JSOP_STRICTSETELEM_SUPER [-4, +1] (ELEM, PROPSET, DETECTING, CHECKSTRICT)
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value159 (0x9f)
Operands 
Length1
Stack Usesreceiver, propval, obj, val
Stack Defsval
- -

LIKE JSOP_STRICTSETELEM, but takes receiver on the stack, and the propval is evaluated before the base.

-
-
JSOP_STRICTSETPROP [-2, +1] (ATOM, PROP, PROPSET, DETECTING, CHECKSTRICT, IC)
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value48 (0x30)
Operandsuint32_t nameIndex
Length5
Stack Usesobj, val
Stack Defsval
- -

Pops the top two values on the stack as val and obj, and performs obj.prop = val, pushing val back onto the stack. Throws a TypeError if the set-operation failed (per strict mode semantics).

-
-
JSOP_STRICTSETPROP_SUPER [-3, +1] (ATOM, PROP, PROPSET, DETECTING, CHECKSTRICT)
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value105 (0x69)
Operandsuint32_t nameIndex
Length5
Stack Usesreceiver, obj, val
Stack Defsval
- -

Pops the top three values on the stack as val and obj, and receiver, and performs obj.prop = val, pushing val back onto the stack. Throws a TypeError if the set-operation failed (per strict mode semantics).

-
-
JSOP_TOID [-1, +1]
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value225 (0xe1)
Operands 
Length1
Stack UsespropertyNameValue
Stack DefspropertyKey
- -

Replace the top-of-stack value propertyNameValue with ToPropertyKey(propertyNameValue).

-
-
- -

Array

- -
-
JSOP_HOLE [-0, +1]
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value218 (0xda)
Operands 
Length1
Stack Uses 
Stack Defshole
- -

Pushes a JS_ELEMENTS_HOLE value onto the stack, representing an omitted property in an array literal (e.g. property 0 in the array [, 1]).

- -

This opcode is used with the JSOP_NEWARRAY opcode.

-
-
JSOP_INITELEM_ARRAY [-2, +1] (UINT32, ELEM, PROPINIT, DETECTING, IC)
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value96 (0x60)
Operandsuint32_t index
Length5
Stack Usesobj, val
Stack Defsobj
- -

Initialize an array element.

- -

Pops the top two values on the stack as val and obj, sets index property of obj as val, pushes obj onto the stack.

-
-
JSOP_INITELEM_INC [-3, +2] (ELEM, PROPINIT, IC)
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value95 (0x5f)
Operands 
Length1
Stack Usesobj, index, val
Stack Defsobj, (index + 1)
- -

Pops the top three values on the stack as val, index and obj, sets index property of obj as val, pushes obj and index + 1 onto the stack.

- -

This opcode is used in Array literals with spread and spreadcall arguments.

-
-
JSOP_LENGTH [-1, +1] (ATOM, PROP, TYPESET, IC)
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value217 (0xd9)
Operandsuint32_t nameIndex
Length5
Stack Usesobj
Stack Defsobj['length']
- -

Pops the top of stack value, pushes the length property of it onto the stack.

-
-
JSOP_NEWARRAY [-0, +1] (UINT32, IC)
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value90 (0x5a)
Operandsuint32_t length
Length5
Stack Uses 
Stack Defsobj
- -

Pushes newly created array onto the stack.

- -

This opcode takes the final length, which is preallocated.

-
-
JSOP_NEWARRAY_COPYONWRITE [-0, +1] (OBJECT)
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value102 (0x66)
Operandsuint32_t objectIndex
Length5
Stack Uses 
Stack Defsobj
- -

Pushes a newly created array onto the stack, whose elements are the same as that of a template object's copy on write elements.

-
-
- -

RegExp

- -
-
JSOP_REGEXP [-0, +1] (REGEXP)
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value160 (0xa0)
Operandsuint32_t regexpIndex
Length5
Stack Uses 
Stack Defsregexp
- -

Pushes a regular expression literal onto the stack. It requires special "clone on exec" handling.

-
-
- -

Class

- -
-
JSOP_CLASSCONSTRUCTOR [-0, +1] (ATOM)
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value167 (0xa7)
Operandsatom className
Length5
Stack Uses 
Stack Defsconstructor
- -

Push a default constructor for a base class literal.

-
-
JSOP_DERIVEDCONSTRUCTOR [-1, +1] (ATOM)
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value168 (0xa8)
Operandsatom className
Length5
Stack Usesproto
Stack Defsconstructor
- -

Push a default constructor for a derived class literal.

-
-
- -

Other

- -
-
JSOP_DEBUGCHECKSELFHOSTED [-1, +1]
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value177 (0xb1)
Operands 
Length1
Stack UsescheckVal
Stack DefscheckVal
- -

Examines the top stack value, asserting that it's either a self-hosted function or a self-hosted intrinsic. This opcode does nothing in a non-debug build.

-
-
JSOP_FORCEINTERPRETER [-0, +0]
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value207 (0xcf)
Operands 
Length1
Stack Uses 
Stack Defs 
- -

No-op bytecode only emitted in some self-hosted functions. Not handled by the JITs so the script always runs in the interpreter.

-
-
JSOP_HASOWN [-2, +1] (IC)
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value211 (0xd3)
Operands 
Length1
Stack Usesid, obj
Stack Defs(obj.hasOwnProperty(id))
- -

Pops the top two values id and obj from the stack, then pushes obj.hasOwnProperty(id)

- -

Note that obj is the top value.

-
-
JSOP_ITERNEXT [-1, +1]
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value222 (0xde)
Operands 
Length1
Stack Usesval
Stack Defsval
- -

NOP opcode to hint to IonBuilder that the value on top of the stack is the (likely string) key in a for-in loop.

-
-
JSOP_JUMPTARGET [-0, +0] (ICINDEX)
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value230 (0xe6)
Operandsuint32_t icIndex
Length5
Stack Uses 
Stack Defs 
- -

This opcode is a no-op and it indicates the location of a jump instruction target. Some other opcodes act as jump targets as well, see BytecodeIsJumpTarget. The IC index is used by the Baseline interpreter.

-
-
JSOP_LINENO [-0, +0] (UINT32)
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value119 (0x77)
Operandsuint32_t lineno
Length5
Stack Uses 
Stack Defs 
- -

Embedded lineno to speedup pc->line mapping.

-
-
JSOP_NOP [-0, +0]
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value0 (0x00)
Operands 
Length1
Stack Uses 
Stack Defs 
- -

No operation is performed.

-
-
JSOP_NOP_DESTRUCTURING [-0, +0]
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value229 (0xe5)
Operands 
Length1
Stack Uses 
Stack Defs 
- -

No-op used by the decompiler to produce nicer error messages about destructuring code.

-
-
JSOP_RESUMEINDEX [-0, +1] (RESUMEINDEX)
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value126 (0x7e)
Operandsuint24_t resumeIndex
Length4
Stack Uses 
Stack DefsresumeIndex
- -

Pushes a resumeIndex (stored as 24-bit operand) on the stack.

- -

Resume indexes are used for ops like JSOP_YIELD and JSOP_GOSUB. JSScript and BaselineScript have lists of resume entries (one for each resumeIndex); this lets the JIT resume at these ops from JIT code.

-
-
JSOP_TOSTRING [-1, +1]
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value228 (0xe4)
Operands 
Length1
Stack Usesval
Stack DefsToString(val)
- -

Converts the value on the top of the stack to a String.

-
-
JSOP_TRY_DESTRUCTURING [-0, +0]
-
- - - - - - - - - - - - - - - - - - - - - - - -
Value220 (0xdc)
Operands 
Length1
Stack Uses 
Stack Defs 
- -

No-op used by the exception unwinder to determine the correct environment to unwind to when performing IteratorClose due to destructuring.

-
-
diff --git a/files/ja/mozilla/projects/spidermonkey/internals/garbage_collection/index.html b/files/ja/mozilla/projects/spidermonkey/internals/garbage_collection/index.html deleted file mode 100644 index e12b08f89b..0000000000 --- a/files/ja/mozilla/projects/spidermonkey/internals/garbage_collection/index.html +++ /dev/null @@ -1,131 +0,0 @@ ---- -title: Garbage collection -slug: Mozilla/Projects/SpiderMonkey/Internals/Garbage_collection -translation_of: Mozilla/Projects/SpiderMonkey/Internals/Garbage_collection ---- -
- この文書について: これはSpiderMonkeyのGC内部についての雑多な草案です。内容が古いまたは不正確な場合があります。
-
-

警告:SpiderMonkey ガベージコレクションTipsは悲しいことに古い内容であり、完全に無視されるべきものとなってしまいました、

-
-

デザインの概要

-

SpiderMonkeyは、オプションでインクリメンタルマーキングモード(incremental marking mode)を有効にされたマーク & スイープ方式のガベージコレクション(GC)を持っています。マークフェイズでは、インクリメンタルマーキングに必要なマークスタックを用います。ファイナライザを伴わないオブジェクトのスイープは、バックグラウンドスレッドにて実行されます。

-

世代別GCおよびコンパクションGC(compacting GC)の実装に向けた作業が進行中です。

-

 

-

主要なデータ構造

-

Cell

-

Cell は、外部からも使用される、GCによって割当と回収が行われるメモリーの単位です。つまり、GC以外から見れば、GCの仕事はCellの割当と自動的な回収ということになります。

-

例えばJSObjectのように、CellはGCによって割り当てられる全てのクラスの基底クラスとなります。

-

Allocation Kind

-

Cellは、Allocation Kindにより分類されます。Allocation Kindはオブジェクトのサイズおよびファイナライズの振る舞いを定義します。Allocation KindはAllocKind列挙型によって定義されます。

-

Arenas always hold objects of the same allocation kind. Thus, an arena holds objects all of the same size and finalization behavior.

-

Compartment

-

JSヒープはCompartmentに分割されます。Compartmentの要点は以下になります:

- -

Compartmentは、SpiderMonkeyにおける、GCを含む特にメモリに関連した事項の構造的かつ分野横断的なコンセプトになっています。詳細はCompartmentsを参照してください。

-

JSCompartmentはGCに関連した重要なフィールドを保持しています:

-
-
- ArenaLists型 arenas
-
- この構造体は、それぞれのAllocation KindのArenaの2つのリストを記録しています。未使用のArenaのリストと、割当済みのArenaのリストです。
-
- bool型 needsBarrier
-
- このCompartmentにおけるGCが、インクリメンタルバリアの実行を必要とする場合にtrueとなります。すなわり、このCompartmentが現在インクリメンタルGCを実行しているかどうかを表します。
-
- CompartmentGCState型 gcState
-
- このCompartmentが現在GCを実行しているかどうかを表します。もし実行していなければ、GCの実行がスケジュールされているかを表します。
-
- size_t型 gcBytes, gcTriggerBytes, gcMallocBytes, gcMaxMallocBytes
-
- GCのスケジュールに使用される情報を表します
-
- WrapperMap型 crossCompartmentWrappers
-
- このCompartment内のオブジェクトのラッパーの集合です。Mapのキーはオブジェクト、値はラッパーです。同じオブジェクトに対するラッパーが複数回要求される場合、エンジンが同一のラッパーを毎回返せるようにするためにマッピングが必要とされます。ラッパーオブジェクトの集合は同様に、単一および複数のcompartmentの(non-globalな)GCにおいても必要となります
-
-

Zone

-

TODO(原文ママ)

-

Chunk

-

Chunkはメモリの割当における最大の内部単位となります。

-

Chunkは1MBのサイズを持ち、内部にArena、パディング、Mark Bitmap(ChunkBitmap)、解放されたArenaのビットマップ、およびChunkヘッダ(ChunkInfo)を保持しています。

-

ChunkInfoは、ChunkInfo::freeArenasHeadから開始しており、ArenaHeader::nextを介してリンクしている未割当のArenaのリストを保持します。また、ChunkInfoは未割当のArenaの数の基本的な情報を保持しています。

-

TODO ChunkInfo next/prev(原文ママ)

-

Arena

-

Arenaはメモリ割当の内部単位です。

-

Arenaは1ページ(ほぼ全てのプラットフォームで4096バイト)の大きさであり、ArenaHeaderと、僅かなパディングとなるバイト領域と、整列された要素の配列を含みます。Arena内のすべての要素は、同じAllocation Kindとサイズを持ちます。

-

すべてのArenaは、ArenaHeader::firstFreeSpanOffetsから始まる自由なメモリ区間のリストを保持します。自由なメモリ区間の最後のCell(最後であるのが望ましい)は、次の自由なメモリ区間を表すFreeSpanを保持します。

-

Free Span

-

構造体FreeSpanは、Arena内の自由なCell [first, last]の連続を表します。FreeSpanは、自由なメモリ区間から割当を行うための関数を保持しています。

-

Mark Bitmap

-

マークビットマップはChunkBitmapによって表されます。

-

マークビットマップはGC Cellごとのビットを持ちます。故に、複数のCellによって構成されているオブジェクトは、ビットマップ中の複数のビットを使います。

-

Exact Stack Rooting API

-
-

:GC rootの実装とおよびSpiderMonkey内での使用についての情報となります。SpiderMonkeyを埋め込んで使う場合の、Rooting APIの使用方法については、 GC Rooting Guideを参照してください。

-
-

GC rootの実装とおよびSpiderMonkey内での使用についての情報となります。 Exact Stack Rooting.

-

マーキング

-

TODO(原文ママ)

-

インクリメンタルマーキング

-

インクリメンタルマーキングは、マーキングの最中に(JavaScriptプログラムによる)状態の変更が発生しても、他のマーキング作業の実行が可能であることを意味します。つまり、マーキングによる長時間のプログラムの実行の停止の代わりに、小さな停止の集まりがGCの実行となるのです。停止時間は10msもしくはそれ以下に抑えられます。

-

長時間の停止が必要となる可能性も常に存在します。インクリメンタルGCの間のメモリ割当の頻度が高い場合、エンジンはインクリメンタルGCの完了の前にout of memoryを実行するかもしれません。そのような場合、エンジンは幾つかのメモリーの返還とプログラムの実行の継続のために、非インクリメンタルな完全なGCを直ちに再実行しなくてはなりません。

-

Incremental write barrier(インクリメンタル書き込みバリア)

-

write barrierを必要とする問題

-

インクリメンタルGCは正確性の担保のためにwrite barrierを必要とします。

-

TODO(原文ママ)、基本的な問題を表す図を用意するVery poor diagram showing IGC hazard that requires a write barrier

-

基本的な問題は以下の通りです(色の説明については、辞書を参照)。オブジェクトAはblackかつポインタ領域を所持しています。オブジェクトBはwhiteとします。ここで、インクリメンタルなスライスが止まり、プログラムの実行による状態の変更が再開しました。プログラムがBをAに保存したことにより、AはBへのポインタを持つことになります。そして、Bへのすべての既存のポインタが削除されました。そのとき、

- -

write barrierは、ポインタの保存の発生前に実行され、生存しているオブジェクトが回収されないようにするために情報を記録する機構の一つです。

-

SpiderMonkeyのincremental write barrier

-

SpiderMonkeyは、(相対的に)シンプルな、ssnapshot-at-the-beginning allocate-black barrierと呼ばれる一般的なincremental write barrierを用いています。

-

このバリアの動作を理解するために、事象を単純にするために、新規にオブジェクトが割り当てられることの無いインクリメンタルGCを仮定します。生存しているオブジェクトを回収しないようにするためにはどうすればよいでしょうか? 一つの方法としては、インクリメンタルGCの最初の時点で生存していたすべてのオブジェクトをマークするという手法があります(これは、オブジェクトへの全ての参照が現在のインクリメンタルGC中に消えた場合は、次のインクリメンタルGC時にそのオブジェクトが回収されるということです)。この手法は、インクリメンタルGCの開始時に生存しているオブジェクトのスナップショットを保存し、それら全てをマークするのとコンセプト上は同義であるために、snapshot-at-the-beginningと呼ばれています。実際にはスナップショットを撮る訳ではありません。そのような場合は完全な非インクリメンタルなマーク作業が必要となります。

-

snapshot-at-the-beginningバリアの実装は単純です。GCポインタを保持する場所がプログラムによって上書きされたタイミングで、バリアは開始します。バリアは単純にポインタによって指し示されているオブジェクトをblackにします。鍵となるのは、オブジェクトへの全てのポインタが上書きされた場合にのみ、オブジェクトはマークされず”死んだもの”となりうるという点です。そのため、オブジェクトへのポインタが上書きされたタイミングでオブジェクトをblackにすれば、オブジェクトが”死ぬ”ということは発生し得ないのです。

-

FIXME(原文ママ):指し示されたオブジェクトをblackにするだけは十分ではないと思います。マークされていない別のオブジェクトがあったら何がおこりますか? マークスタックについても言及すべきです。「指し示されているオブジェクトをblackにする」というのは、「再帰的に指し示されたオブジェクトをblackにする」という意味で書かれていますか?

-

これで、メモリの割当の正確性についても話します。新規に割り当てられたオブジェクトはGCの開始時には存在していませんでした。snapshot-at-the-beginningバリアはこれについては巧くカバーしません。ですが、もし新規に割り当てられたオブジェクトが生存している場合は、それが回収されないようにする必要があります。これは簡単で、インクリメンタルGC中に新規にオブジェクトが割り当てられたら、それをマークすれば良いのです。これを名付けてallocate-blackと言います。

-

SpiderMonkeyの incremental read barrier(インクリメンタル読み取りバリア)

-

インクリメンタルGCの教科書的な実装では、write barrierしかありません。SpiderMonkeyでは、weak pointer(用語集参照)のためにread barrierも用意しています。

-

TODO(原文ママ):解説の完成

-

実装の詳細

-

write barrierは実行時のコストを伴うので、SpiderMonkeyはインクリメンタルGCの実行中以外ではスキップするようにしています。各compartmentのneedsBarrier()フラグによって、バリアが必要かどうかを示しています。

-

T*型のフィールドのように、全てのT型はwrite barrierを必要としており、T::writeBarrierPre(old)という関数が存在しています。たとえば、JSObject*がwrite barrierを必要とする場合、関数ObjectImpl::writeBarrierPre(ObjectImpl *old)が存在します(JSObjectObjectImplを継承しています。)。 zone->needsBarrier()がtrueである場合、writeBarrierPre()oldをマークする、ということです。

-

HeapPtr<t>クラスはwrite barrierの起動を簡単にするために提供されています。HeapPtr<t>はT*をカプセル化し、割当時にwrite barrierを起動します。これにより、GCポインタ型のオブジェクトの領域は、通常、HeapPtr<T><t>として定義されています。HeapValueクラスはValueに対して同じことを行います。HeapSlot(および関連するHeapSlotArray)も同様に、オブジェクトスロットに対するものです。HeapIdは、同じくjsidに対する物です。TODO(原文ママ):なぜHeapValueとHeapSlotの2つが存在するのか</t></t></t>

-

オブジェクトのプライベート領域は、特別に取り扱う必要があります。プライベート領域自体は、エンジンに対しては隠されていますが、マークされる必要があるものを指し示すかもしれません(例:JSObjectのポインタの配列)。この例では、プライベート領域が上書きされた場合、JSObjectのポインタは”死ぬ”ことになります。そのため、write barrierはそれらをマークしなければなりません。ObjectImpl::privateWriteBarrierPreはプライベート領域が上書きされる前にJSObjectクラスのトレースフックによって起動され、これに対処します。

-

他の詳細事項として、write barrierは新規に確保されたオブジェクトのフィールドの初期化時には、上書きされるポインタが存在しないことから、スキップすることができます。

-

Sweeping(スイーピング)

-

TODO(原文ママ)

-

世代別GC

-

TODO(原文ママ)

-

GC統計API

-

実行時にGC統計API.を通じて、GCが保持する明確な統計情報にアクセスする事ができます。

-

ソースファイル

-

jsgc{.h,inlines.h,.cpp} GCを起動するためのエントリーポイントを含む内部API関数群を定義します。

-

jsgcstats.{h,cpp} 保守的なスタックスキャンに基づく情報収集のための構造体ConservativeGCStatsを定義します。TODO(原文ママ):削除されたときに消す

-

gc/Barrier[-inl].h インクリメンタルおよび世代別用のwrite barrierを実装しています。

-

gc/Heap.h GCのヒープ構造の根幹を成す、Chunk, ChunkInfo, ChunkBitmap, Arena, ArenaHeader, Cell, FreeSpanといった一連の構造体を定義します。

-

gc/Marking.{h,cpp} 多様なGC対象用のマーク作業関数の全てを定義します。

-

gc/Memory.{h,cpp} ページの配置と解放(mapping and unmapping)のための僅かな関数に加えて、プラットフォーム固有の実装を保持しています。配置・解放(map/unmap)用の関数はチャンクの確保と解放(allocate and release )用のために、 jsgc.cppによって使用されています。使用されておらずディスクに格納する代わりメモリ破棄が可能なページをOS伝えるなどに用いる、確保または解放(commit or decommit)のための関数もあります。

-

gc/Root.h GCルートとして用いられる変数クラスを定義します。

-

gc/Statistics.{h,cpp} SpiderMonkey GCのパフォーマンスカウンタとして保存される Statics構造体を定義しています。

-

用語の解説

-

TODO(原文ママ): SpiderMonkeyの実装と色の名前が一致しているかを確認

-

black(黒)一般的な計算機科学の文脈において、マークフェイズ中、マーク済かつ子供がgray(マークキューに積まれている)なオブジェクトをblackとします。SpiderMonkeyでは、マークビットが設定されたオブジェクトをblackと見なします。

-

gray(灰色):一般的な計算機科学の文脈において、マークフェイズ中、マークキューに積まれているオブジェクトをgrayとします。SpiderMonkeyでは、マークスタック内のオブジェクトの子孫かつblackで無いものはgrayとなります。つまり、状態が明白でないオブジェクトがgrayであるということです。

-

Handle(ハンドル) 私たちのGCでは、Handleはルートによって登録されたどこかを指し示すポインタです。

-

root TODO(原文ママ): 上からコピーする

-

weak pointer(弱参照ポインタ) 一般的な計算機科学の文脈において、weak pointerはGC目的で指し示された値が生存し続ける必要がなくなるポインタです。具体的には、既にポインタの指し示す対象が既にGCされている場合は、weak pointerのget()メソッドが返す値はnullポインタとなります。Gecko/SpiderMonkeyでは、weak pointerはマークされていないがGC対象となりうるオブジェクトへのポインタとなります。そのため、get()メソッドは存在せず、指し示す値がGCされたかどうかの保証も存在しません。プログラマは、指し示されたオブジェクトの生存時間が、weak pointerの生存時間よりも長いことを保証する必要があります。TODO(原文ママ) これが正しいか確認。

-

white(白) 一般的な計算機科学の文脈において、マークフェイズ中、まだ辿れていないオブジェクトはwhiteとなります。マークされなかった場合、マークフェイズの後にオブジェクトはwhiteとなります。SpiderMonkeyでは、grayでもblackでもない(blackでもマークスタック内のオブジェクトの子でもない)オブジェクトがwhiteとなります。

-

クリーンアップの可能性

-

MarkPagesInUse はすべてのプラットフォームで何の操作も実施しません。

-

統計ファイルのマージ。

-

ArenaLists::refillFreeListsは悪いネーミングです。それは、たとえArenaの解放リストが完全ではなくても、Cellの確保を試みるように見えます。

diff --git a/files/ja/mozilla/projects/spidermonkey/internals/index.html b/files/ja/mozilla/projects/spidermonkey/internals/index.html deleted file mode 100644 index 49e8157aa7..0000000000 --- a/files/ja/mozilla/projects/spidermonkey/internals/index.html +++ /dev/null @@ -1,290 +0,0 @@ ---- -title: Internals -slug: Mozilla/Projects/SpiderMonkey/Internals -tags: - - JavaScript - - SpiderMonkey - - 要更新 - - 要翻訳 -translation_of: Mozilla/Projects/SpiderMonkey/Internals ---- -
{{SpiderMonkeySidebar("Internals")}}
- -

設計

- -

SpiderMonkey は型付けされていないバイトコードと JavaScript で扱いうる値を表す JS::Value 型に対する演算を高速に行えるインタプリタです。Just-In-Time (JIT) コンパイラやガベージコレクションの機構を備え、JavaScript の値が持つ基本的な振る舞いと ECMA 262-5.1 §15 とその他の拡張で定義された標準ライブラリを実装し、いくつかのパブリックな API が提供されています。

- -

インタプリタ

- -

多くの移植可能なインタプリタと同様、SpiderMonkey のインタプリタは主に単一の長大な関数として実装されています。バイトコードを 1 つずつ実行され、現在の命令に対応するコードへの分岐は switch 文を利用して行われます(コンパイラによっては、より高速な手法が利用されます)。JS で記述された関数同士の呼び出し時にはJavaScript のスタックフレームが伸長し、C のスタックは消費されません。一方 JS で記述された関数から、C で定義された関数を呼び出し、また JS で記述された関数を呼ぶような場合は、コールスタックは通常通りに消費されるため、インタプリタは再突入可能となっています。

- -

SpiderMonkey バイトコードの処理には、引数の型による多くの特例が存在します。通常はインタプリタのループ内で処理されますが、邪魔な抽象化を無視する場合もあります。密な配列やプロパティキャッシュのような最適化は、jsinterp.cpp に定義されている jsarray.*jsobj.*  によって隠蔽され、透過的に行われるわけでは「ありません」。

- -

インタプリタに関する状態は、インタプリタのエントリポイントに引数として渡されます。暗黙的な状態は JSContext 型の値にまとめられており、API であろうがなかろうが、SpiderMonkey のすべての関数は第 1 引数に、JSContext 型のポインタをとります。

- -

コンパイラ

- -

コンパイラは JavaScript のソースコードを処理し、script を生成します。script にはバイトコードとそのソースコード、ソースに対するアノテーション、文字列、数値、識別子のリテラルが含まれます。またソースコード中で定義されている関数も含む、オブジェクトも script には含まれます。それぞれの関数は入れ子になった script を保持します。

- -

The compiler consists of: a random-logic rather than table-driven lexical scanner, a recursive-descent parser that produces an AST, and a tree-walking code generator. Semantic and lexical feedback are used to disambiguate hard cases such as missing semicolons, assignable expressions ("lvalues" in C parlance), and whether / is the division symbol or the start of a regular expression. The compiler attempts no error recovery; it bails out on the first error. The emitter does some constant folding and a few codegen optimizations; about the fanciest thing it does is to attach source notes to the script for the decompiler's benefit.

- -

The decompiler implements Function.toSource(), which reconstructs a function's source code. It translates postfix bytecode into infix source by consulting a separate byte-sized code, called source notes, to disambiguate bytecodes that result from more than one grammatical production.

- -

Garbage collector

- -

The GC is a mark-and-sweep, non-conservative (exact) collector. It is used to hold JS objects and string descriptors (JSString), but not string bytes. It runs automatically only when maxbytes (as passed to JS_NewRuntime) bytes of GC things have been allocated and another thing-allocation request is made. JS API users should call JS_GC or JS_MaybeGC between script executions or from the operation callback, as often as necessary.

- -

Because the GC is exact, C/C++ applications must ensure that all live objects, strings, and numbers are GC-reachable.

- -

JavaScript values

- -

The type JS::Value represents a JavaScript value.

- -

The representation is 64 bits and uses NaN-boxing on all platforms, although the exact NaN-boxing format depends on the platform. NaN-boxing is a technique based on the fact that in IEEE-754 there are 2**47 different bit patterns that all represent NaN. Hence, we can encode any floating-point value as a C++ double (noting that JavaScript NaN must be represented as one canonical NaN format). Other values are encoded as a value and a type tag:

- - - -

Only JIT code really depends on the layout--everything else in the engine interacts with values through functions like val.isDouble(). Most parts of the JIT also avoid depending directly on the layout: the files PunboxAssembler.h and NunboxAssembler.h are used to generate native code that depends on the value layout.

- -

Objects consist of a possibly shared structural description, called the map or scope; and unshared property values in a vector, called the slots. Each property has an id, either a nonnegative integer or an atom (unique string), with the same tagged-pointer encoding as a jsval.

- -

The atom manager consists of a hash table associating strings uniquely with scanner/parser information such as keyword type, index in script or function literal pool, etc. Atoms play three roles: as literals referred to by unaligned 16-bit immediate bytecode operands, as unique string descriptors for efficient property name hashing, and as members of the root GC set for exact GC.

- -

Standard library

- -

The methods for arrays, booleans, dates, functions, numbers, and strings are implemented using the JS API. Most are JSFastNatives. Most string methods are customized to accept a primitive string as the this argument. (Otherwise, SpiderMonkey converts primitive values to objects before invoking their methods, per ECMA 262-3 §11.2.1.)

- -

Error handling

- -

SpiderMonkey has two interdependent error-handling systems: JavaScript exceptions (which are not implemented with, or even compatible with, any kind of native C/C++ exception handling) and error reporting. In general, both functions inside SpiderMonkey and JSAPI callback functions signal errors by calling JS_ReportError or one of its variants, or JS_SetPendingException, and returning JS_FALSE or NULL.

- -

Public APIs

- -

The public C/C++ interface, called the JSAPI, is in most places a thin (but source-compatible across versions) layer over the implementation. See the JSAPI User Guide. There is an additional public API for JavaScript debuggers, JSDBGAPI, but {{Source("js/jsd/jsdebug.h")}} might be a better API for debuggers. Another API, JSXDRAPI, provides serialization for JavaScript scripts. (XUL Fastload uses this.)

- -

Just-In-Time compiler

- -

SpiderMonkey contains a baseline compiler as first tier. A second tier JIT, code-named IonMonkey was enabled in Firefox 18. IonMonkey is an optimizing compiler.

- -

Self-hosting of built-in functions in JS

- -

Starting with Firefox 17, SpiderMonkey has the ability to implement built-in functions in self-hosted JS code. This code is compiled in a special compilation mode that gives it access to functionality that's not normally exposed to JS code, but that's required for safe and specification-conformant implementation of built-in functions.

- -

All self-hosted code lives in .js files under builtin/. For details on implementing self-hosted built-ins, see self-hosting.

- -

File walkthrough

- -

jsapi.cpp, jsapi.h

- -

The public API to be used by almost all client code.

- -

jspubtd.h, jsprvtd.h

- -

These files exist to group struct and scalar typedefs so they can be used everywhere without dragging in struct definitions from N different files. The jspubtd.h file contains public typedefs, and is included automatically when needed. The jsprvtd.h file contains private typedefs and is included by various .h files that need type names, but not type sizes or declarations.

- -

jsdbgapi.cpp, jsdbgapi.h

- -

The debugging API. Provided so far:

- -

Traps, with which breakpoints, single-stepping, step over, step out, and so on can be implemented. The debugger will have to consult jsopcode.def on its own to figure out where to plant trap instructions to implement functions like step out, but a future jsdbgapi.h will provide convenience interfaces to do these things. At most one trap per bytecode can be set. When a script (JSScript) is destroyed, all traps set in its bytecode are cleared.

- -

Watchpoints, for intercepting set operations on properties and running a debugger-supplied function that receives the old value and a pointer to the new one, which it can use to modify the new value being set.

- -

Line number to PC and back mapping functions. The line-to-PC direction "rounds" toward the next bytecode generated from a line greater than or equal to the input line, and may return the PC of a for-loop update part, if given the line number of the loop body's closing brace. Any line after the last one in a script or function maps to a PC one byte beyond the last bytecode in the script. An example, from perfect.js:

- -
function perfect(n) {
-  print("The perfect numbers up to " + n + " are:");
-  // We build sumOfDivisors[i] to hold a string expression for
-  // the sum of the divisors of i, excluding i itself.
-  var sumOfDivisors = new ExprArray(n + 1, 1);
-  for (var divisor = 2; divisor <= n; divisor++) {
-    for (var j = divisor + divisor; j <= n; j += divisor) {
-      sumOfDivisors[j] += " + " + divisor;
-    }
-    // At this point everything up to 'divisor' has its sumOfDivisors
-    // expression calculated, so we can determine whether it's perfect
-    // already by evaluating.
-    if (eval(sumOfDivisors[divisor]) == divisor) {
-      print("" + divisor + " = " + sumOfDivisors[divisor]);
-    }
-  }
-  delete sumOfDivisors;
-  print("That's all.");
-}
- -

The line number to PC and back mappings can be tested using the js program with the following script:

- -
load("perfect.js");
-print(perfect);
-dis(perfect);
-print();
-for (var ln = 0; ln <= 40; ln++) {
-    var pc = line2pc(perfect, ln);
-    var ln2 = pc2line(perfect, pc);
-    print("\tline " + ln + " => pc " + pc + " => line " + ln2);
-}
-
- -

The result of the for loop over lines 0 to 40 inclusive is:

- -
line 0 => pc 0 => line 16
-line 1 => pc 0 => line 16
-line 2 => pc 0 => line 16
-line 3 => pc 0 => line 16
-line 4 => pc 0 => line 16
-line 5 => pc 0 => line 16
-line 6 => pc 0 => line 16
-line 7 => pc 0 => line 16
-line 8 => pc 0 => line 16
-line 9 => pc 0 => line 16
-line 10 => pc 0 => line 16
-line 11 => pc 0 => line 16
-line 12 => pc 0 => line 16
-line 13 => pc 0 => line 16
-line 14 => pc 0 => line 16
-line 15 => pc 0 => line 16
-line 16 => pc 0 => line 16
-line 17 => pc 19 => line 20
-line 18 => pc 19 => line 20
-line 19 => pc 19 => line 20
-line 20 => pc 19 => line 20
-line 21 => pc 36 => line 21
-line 22 => pc 53 => line 22
-line 23 => pc 74 => line 23
-line 24 => pc 92 => line 22
-line 25 => pc 106 => line 28
-line 26 => pc 106 => line 28
-line 27 => pc 106 => line 28
-line 28 => pc 106 => line 28
-line 29 => pc 127 => line 29
-line 30 => pc 154 => line 21
-line 31 => pc 154 => line 21
-line 32 => pc 161 => line 32
-line 33 => pc 172 => line 33
-line 34 => pc 172 => line 33
-line 35 => pc 172 => line 33
-line 36 => pc 172 => line 33
-line 37 => pc 172 => line 33
-line 38 => pc 172 => line 33
-line 39 => pc 172 => line 33
-line 40 => pc 172 => line 33
-
- -

jsconfig.h

- -

Various configuration macros defined as 0 or 1 depending on how JS_VERSION is defined (as 10 for JavaScript 1.0, 11 for JavaScript 1.1, etc.). Not all macros are tested around related code yet. In particular, JS 1.0 support is missing from SpiderMonkey.

- -

js.cpp, jsshell.msg

- -

The "JS shell", a simple interpreter program that uses the JS API and more than a few internal interfaces (some of these internal interfaces could be replaced by jsapi.h calls). The js program built from this source provides a test vehicle for evaluating scripts and calling functions, trying out new debugger primitives, etc.

- -

A look at the places where jsshell.msg is used in js.cpp shows how error messages can be handled in JSAPI applications. These messages can be localized at compile time by replacing the .msg file; or, with a little modification to the source, at run time.

- -

More information on the JavaScript shell.

- -

js.msg

- -

SpiderMonkey error messages.

- -

jsarray.*, jsbool.*, jsdate.*, jsfun.*, jsmath.*, jsnum.*, jsstr.*

- -

These file pairs implement the standard classes and (where they exist) their underlying primitive types. They have similar structure, generally starting with class definitions and continuing with internal constructors, finalizers, and helper functions.

- -

jsobj.*, jsscope.*

- -

These two pairs declare and implement the JS object system. All of the following happen here:

- - - -

The details of a native object's map (scope) are mostly hidden in jsscope.{{mediawiki.external('ch')}}.

- -

jsatom.cpp, jsatom.h

- -

The atom manager. Contains well-known string constants, their atoms, the global atom hash table and related state, the js_Atomize() function that turns a counted string of bytes into an atom, and literal pool (JSAtomMap) methods.

- -

jsarena.cpp, jsarena.h

- -

Last-In-First-Out allocation macros that amortize malloc costs and allow for en-masse freeing. See the paper mentioned in jsarena.h's major comment.

- -

jsgc.cpp, jsgc.h

- -

The garbage collector and tracing routines.

- -

jsinterp.*, jscntxt.*, jsinvoke.cpp

- -

The bytecode interpreter, and related functions such as Call and AllocStack, live in jsinterp.cpp. The JSContext constructor and destructor are factored out into jscntxt.cpp for minimal linking when the compiler part of JS is split from the interpreter part into a separate program.

- -

jsinvoke.cpp is a build hack used on some platforms to build js_Interpret under different compiler options from the rest of jsinterp.cpp.

- -

jstracer.*, nanojit/*

- -

The tracing JIT. The interface between the JIT and the rest of SpiderMonkey is conceptually small—the interpreter calls into the trace recorder—but as with everything else, there are tendrils everywhere.

- -

jsemit.*, jsopcode.tbl, jsopcode.*, jsparse.*, jsscan.*, jsscript.*

- -

Compiler and decompiler modules. The jsopcode.tbl file is a C preprocessor source that defines almost everything there is to know about JS bytecodes. See its major comment for how to use it. For now, a debugger will use it and its dependents such as jsopcode.h directly, but over time we intend to extend jsdbgapi.h to hide uninteresting details and provide conveniences. The code generator is split across paragraphs of code in jsparse.cpp, and the utility methods called on JSCodeGenerator appear in jsemit.cpp. Source notes generated by jsparse.cpp and jsemit.cpp are used in jsscript.cpp to map line number to program counter and back.

- -

jstypes.h

- -

Fundamental representation types and utility macros. This file alone among all .h files in SpiderMonkey must be included first by .cpp files. It is not nested in .h files, as other prerequisite .h files generally are, since it is also a direct dependency of most .cpp files and would be over-included if nested in addition to being directly included.

- -

jsbit.h, jslog2.cpp

- -

Bit-twiddling routines. Most of the work here is selectively enabling compiler-specific intrinsics such as GCC's __builtin_ctz, which is useful in calculating base-2 logarithms of integers.

- -

jsutil.cpp, jsutil.h

- -

The JS_ASSERT macro is used throughout the source as a proof device to make invariants and preconditions clear to the reader, and to hold the line during maintenance and evolution against regressions or violations of assumptions that it would be too expensive to test unconditionally at run-time. Certain assertions are followed by run-time tests that cope with assertion failure, but only where I'm too smart or paranoid to believe the assertion will never fail...

- -

jsclist.h

- -

Doubly-linked circular list struct and macros.

- -

jscpucfg.cpp

- -

This standalone program generates jscpucfg.h, a header file containing bytes per word and other constants that depend on CPU architecture and C compiler type model. It tries to discover most of these constants by running its own experiments on the build host, so if you are cross-compiling, beware.

- -

jsdtoa.cpp, jsdtoa.h, dtoa.c

- -

dtoa.c contains David Gay's portable double-precision floating point to string conversion code, with Permission To Use notice included. jsdtoa.cpp #includes this file.

- -

jshash.cpp, jshash.h, jsdhash.cpp, jsdhash.h

- -

Portable, extensible hash tables. These use multiplicative hash for strength reduction over division hash, yet with very good key distribution over power of two table sizes. jshash resolves collisions via chaining, so each entry burns a malloc and can fragment the heap. jsdhash uses open addressing.

- -

jslong.cpp, jslong.h

- -

64-bit integer emulation, and compatible macros that use intrinsic C types, like long long, on platforms where they exist (most everywhere, these days).

- -

jsprf.*

- -

Portable, buffer-overrun-resistant sprintf and friends. For no good reason save lack of time, the %e, %f, and %g formats cause your system's native sprintf, rather than JS_dtoa(), to be used. This bug doesn't affect SpiderMonkey, because it uses its own JS_dtoa() call in jsnum.cpp to convert from double to string, but it's a bug that we'll fix later, and one you should be aware of if you intend to use a JS_*printf() function with your own floating type arguments - various vendor sprintf's mishandle NaN, +/-Inf, and some even print normal floating values inaccurately.

- -

prmjtime.c, prmjtime.h

- -

Time functions. These interfaces are named in a way that makes local vs. universal time confusion likely. Caveat emptor, and we're working on it. To make matters worse, Java (and therefore JavaScript) uses "local" time numbers (offsets from the epoch) in its Date class.

- -

jsfile.cpp, jsfile.h, jsfile.msg

- -

Obsolete. Do not use these files.

- -

Makefile.in, build.mk

- -

Mozilla makefiles. If you're building Gecko or Firefox, the larger build system will use these files. They are also used for current standalone builds.

- -

Makefile.ref, rules.mk, config.mk, config/*

- -

Obsolete SpiderMonkey standalone makefiles from 1.8 and earlier. See SpiderMonkey Build Documentation.

- -

See also

- - diff --git a/files/ja/mozilla/projects/spidermonkey/internals/thread_safety/index.html b/files/ja/mozilla/projects/spidermonkey/internals/thread_safety/index.html deleted file mode 100644 index 90bfb3fb10..0000000000 --- a/files/ja/mozilla/projects/spidermonkey/internals/thread_safety/index.html +++ /dev/null @@ -1,56 +0,0 @@ ---- -title: Thread Safety -slug: Mozilla/Projects/SpiderMonkey/Internals/Thread_Safety -tags: - - JavaScript - - SpiderMonkey ---- -

This page describes implementation details of the SpiderMonkey JavaScript engine. It is mainly of interest to people working on SpiderMonkey itself, but this information is also helpful for anyone embedding SpiderMonkey in a multithreaded environment. See also JS_THREADSAFE.

-

{{ 英語版章題("General background") }}

-

General background

-

SpiderMonkeyは、最上位の構造体としてJSRuntimeを利用します。これらの構造体は、メモリの管理とグローバルなデータ構造を扱います。 通常の場合プログラムは、多くのスレッドを利用する場合でも、1つだけJSRuntimeを使います。JSRuntimeは、JSオブジェクトが動作する 世界といってもよいでしょう。オブジェクトは、他のJSRuntimeに移って動作することはできません。 SpiderMonkey has a top-level struct, <code></code>, that handles, among other things, memory management and "global" data structures. A program typically has only one <code>JSRuntime</code>, even if it has many threads. The <code>JSRuntime</code> is the universe in which JS objects live; they can't travel to other <code>JSRuntime</code>s.

-

全てのJSコードとほとんどのJSAPIの呼び出しは、JSContextの中で動作します。JSContextは、 JSRuntimeの子供のようなもので、例えば、例外の処理などは、JSContextごとに実行されます。 各JSContextは、同時に複数スレッドからアクセスしてはなりません。 All JS code and most JSAPI calls run within a <code>JSContext</code>. The <code>JSContext</code> is a child of the <code>JSRuntime</code>; exception handling, for example, is per-<code>JSContext</code>. Each <code>JSContext</code> must be used by only one thread at a time.

-

オブジェクトは、同じJSRuntime内のJSContext間で共有できます。コンテキストとオブジェクトの間には、固定的な関係はありません。 Objects may be shared among <code>JSContext</code>s within a <code>JSRuntime</code>. There's no fixed association between an object and a context.

-

SpiderMonkeyにおけるスレッドセーフ機能は、-DJS_THREADSAFEをつけてコンパイルすることで有効になります。JS_THREADSAFEを有効にしたビルドでは、次のような操作について特別な処理が行われます。 Thread-safety in SpiderMonkey is turned on by compiling with <code>-DJS_THREADSAFE</code>. In a <code>JS_THREADSAFE</code> build, these operations are handled specially:

- -

* access to <code>JSRuntime</code> data structures * garbage collection * access to properties of objects

-

JSRuntimeのデータ構造へのアクセスは、mutexによってシリアライズされます。 GCとプロパティに関する処理については、もう少し詳しく説明します。 Accesses to <code>JSRuntime</code> data structures are serialized with a few mutexes. The treatment of GC and properties requires more explanation.

-

{{ 英語版章題("Making GC thread-safe") }}

-

Making GC thread-safe

-

JS_THREADSAFEを用いるときは、APIを若干変更します。プログラム中でJSAPIを呼び出すときは、次に示す"request"で くくらなくてはなりません。 With <code>JS_THREADSAFE</code>, the API changes slightly. The program must group JSAPI calls into "requests":

-
   JS_SetContextThread(cx);
-   JS_BeginRequest(cx);
-   /* ... do stuff ... */
-   JS_EndRequest(cx);
-   JS_ClearContextThread(cx);
-
-

複数のスレッドがrequest内で同じJSRuntimeを同時にアクセスできるため、この操作がボトルネックになることはありません。詳細はJS_BeginRequestを参照してください。 It isn't a bottleneck; multiple threads are allowed to be in requests on the same <code>JSRuntime</code> at once. See JS_BeginRequest.

-

requestの最も顕著な効果は、いつでも複数のスレッドがrequestのくくりを実行することができるか、1つのスレッドだけがGCを実行していて他のスレッドが停止させられている 用にすることです。JS_GC()を呼び出しても、他のスレッドが停止させられるまでは、処理がブロックされます。つまり、他のスレッドがJSAPIを呼び出していないか (呼び出していないときには、特に注意する必要がないので)、JSAPIを実行中であってもGCが終了するのを待っているブロックしている状態になるまで、 GCの実行は停止させられます。 The most obvious effect of a request is: at any given moment there can either be multiple threads in active requests, or one thread doing GC and all requests suspended. A call to JS_GC() will block until the latter becomes possible. In other words, GC waits until each other thread is either outside JSAPI (in which case we don't care what it's doing) or else in JSAPI, but blocked, waiting for GC to finish.

-

requestのくくりの中にいないときには、スレッドは、GCに影響を与えるような処理を行ってはいけません。 当たり前のことですが、requestのくくりの中では、GCが抑止されてしまうので、ブロックしたり、時間のかかる処理を行ってはいけません。 Threads must not do anything that would affect GC while outside a request. And obviously you shouldn't block or otherwise dilly-dally while in a request; it prohibits GC. 最適化のために、スレッドには、スレッドごとの大きさごとに分けられた、割り当て可能なGC用のメモリの集合に関するフリーリストを持っています。 このリストにより、ほとんどの場合ロックせずにメモリを割り当てることができます。スレッドがロックを必要とするのは、スレッドの対応するフリーリストが 空だった場合だけです。このようなことが怒った場合に、ロックして広域のGC割り当てを行い、<code>JSRuntime</code>から、フリーリストに領域を補充します。 <!--As an optimization, each thread has its own size-classified freelists containing chunks of GC-managed memory ready to be allocated. This allows allocation to avoid locking most of the time (a significant speed win). A thread needs to lock on allocation only when the relevant per-thread freelist is empty. When this happens, the thread also refills that freelist from the <code>JSRuntime</code>-wide GC allocator while it's in the lock.

-

{{ 英語版章題("Making property accesses thread-safe") }}

-

Making property accesses thread-safe

-

JSAPIのユーザにとっては、プロパティへのアクセスは全てシリアライズされているように見えます。これから記述する方法は、SpiderMonkeyの内部に関するもので ユーザにとっては見えない、最適化についてです。 To the JSAPI user, all property accesses appear to be serialized. The scheme described below is an optimization, internal to SpiderMonkey and invisible to the user.

-

SpiderMonkeyの実装では、mutableなオブジェクトは必要に応じて暗黙のうちにロックされます。ロックの手順は、うまく最適化されていて、単なるmutexではありません。 SpiderMonkey implicitly locks mutable objects as needed. The locking protocol is cleverly optimized. It's not a simple mutex.

-

それぞれの、mutableなオブジェクトは、JSContextが"占有"している(つまり、コンテキストがロックをしなくてもプロパティにアクセスできる) か、JSRuntime内のJSContextで、"共有"しているかのいずれかです。(繰り返しになりますが、JSAPIのユーザにとっては、全てのオブジェクトは 共有されており、この"所有関係"は、ユーザには見えないように最適化されています。) Each mutable object is either "owned" by a <code>JSContext</code>, meaning that context may access its properties without locking; or "shared" across all <code>JSContext</code>s in the <code>JSRuntime</code>. (Again, to the end user, all objects are shared--this "ownership" is a transparent optimization.)

-

初期状態では、オブジェクトの所有者は、オブジェクトを作ったJSContext</code.です。他の<code>JSContextがオブジェクトにアクセスしようとするまでは、 ロックは全く必要ではありません。他のコンテキストがアクセスしようとした時点で、JSRuntimeの広域ロックを取得します。ただ、この時点においても プロパティへの通常のアクセスは、1つのオブジェクト(つまり、プロパティを持っているオブジェクトのこと)のmutable部分に触る必要があるだけです。 従って、デッドロックは問題になりません。* また、スレッドがロックする必要がある場合でも、オブジェクトを所有しているコンテキストが requestのくくりを実行していないのであれば、コストのかかる他のスレッドとのランデブ**を避けることができます。 Initially an object is owned by the <code>JSContext</code> in which it was created. Locking is never needed until some other <code>JSContext</code> tries to access the object. At that point, we acquire a <code>JSRuntime</code>-wide lock. But even then, each ordinary property access only needs to touch mutable parts of one object (the one that has the property), so deadlock isn't an issue.* And even though the calling thread must lock, it can still avoid a costly rendezvous** with another thread, if the context that owns the object is not currently in a request.

-

I found it helpful to read the code for OBJ_GET_SLOT, defined in jsobj.h, and track down the various things it calls.

-
   /* Thread-safe functions and wrapper macros for accessing slots in obj. */
-   #define OBJ_GET_SLOT(cx,obj,slot)                                     \
-       (OBJ_CHECK_SLOT(obj, slot),                                       \
-        (OBJ_IS_NATIVE(obj) && OBJ_SCOPE(obj)->ownercx == cx)            \
-        ? LOCKED_OBJ_GET_SLOT(obj, slot)                                 \
-        : js_GetSlotThreadSafe(cx, obj, slot))
-
-

Here OBJ_CHECK_SLOT() is just an assertion. LOCKED_OBJ_GET_SLOT() is the fast path; it amounts to an array access. OBJ_SCOPE(obj)->ownercx is the object's owning context, or NULL if the object is "shared". (An OBJ_SCOPE is just a handy place to stick this field; it is often shared across multiple objects, so all this locking is somewhat higher than object-level.)

-

This may appear unsafe, at least in SMP environments where writing a word isn't guaranteed to make the new value immediately visible to other CPUs. Requests save the day again: entering or leaving a request always briefly acquires a lock, which forces a read-write barrier. This barrier is necessary and sufficient to make several of these optimizations safe.

-

In short, any JSContext may touch any object, yet not only is locking usually optimized away, the threads don't even have to execute atomic instructions or barrier instructions in the most common path.

-
-

* deadlock isn't an issue: That is, SpiderMonkey doesn't need any special code to detect and avoid potential deadlock when getting or setting an ordinary property, because it can't happen--you're only locking one object at a time. Assigning to __proto__ is an example of a special case: SpiderMonkey checks for prototype chain cycles, which means locking the whole chain. So in that case, and maybe others, SpiderMonkey does extra work to avoid deadlock.

-

** can still avoid a costly rendezvous: That is, it can avoid "asking" that thread to surrender the object and then waiting for the thread to respond. It just takes the object. See ClaimScope in jslock.c.

-

{{ 英語版章題("Patent") }}

-

Patent

-

The SpiderMonkey request model is patented: http://www.wipo.int/pctdb/en/wo.jsp?wo=2003042845

-

The Mozilla Public License in the SpiderMonkey source code grants a worldwide royalty-free license to this invention.

- -

{{ languages( { "en": "en/SpiderMonkey_Internals/Thread_Safety" } ) }} 

diff --git a/files/ja/mozilla/projects/spidermonkey/introduction_to_the_javascript_shell/index.html b/files/ja/mozilla/projects/spidermonkey/introduction_to_the_javascript_shell/index.html deleted file mode 100644 index f07dc77d69..0000000000 --- a/files/ja/mozilla/projects/spidermonkey/introduction_to_the_javascript_shell/index.html +++ /dev/null @@ -1,376 +0,0 @@ ---- -title: JavaScript シェルの紹介 -slug: Mozilla/Projects/SpiderMonkey/Introduction_to_the_JavaScript_shell -tags: - - SpiderMonkey -translation_of: Mozilla/Projects/SpiderMonkey/Introduction_to_the_JavaScript_shell ---- -
{{SpiderMonkeySidebar("General")}}
- -
-

JavaScript シェル (js) は SpiderMonkey ソース配布に含まれているコマンドラインプログラムです。 これは、Python の対話型プロンプト、Lisp の read-eval-print ループ、または Ruby の irb に相当する JavaScript です。この記事では、シェルを使用して JavaScript コードを試したり JavaScript プログラムを実行したりする方法について説明します。

-
- -

SpiderMonkey JavaScript シェルを入手するには、SpiderMonkey ビルドドキュメントを参照するか、Nightly Builds からプラットフォーム用にコンパイルされたバイナリをダウンロードしてください。

- -

他の JavaScript シェルのリストについては、JavaScript シェルを参照してください。

- -
-

メモ: SpiderMonkey 44 {{geckoRelease(44)}} 以降、標準の Web 互換の JavaScript バージョンがデフォルトで使用されます (JS 1.7 以降ではなくなりました)。組み込みの version() シェルは、従来の機能をテストするためにまだ存在しています。

-
- -

JavaScript シェルを実行する

- -

シェルには2つの動作モードがあります。インタラクティブシェルとして使用することができます。ここでは、プロンプトで JavaScript コードを入力してすぐに満足のいく結果を得ることができます。これは、新機能の実験やテストに便利です。実行する JavaScript プログラムファイルをコマンドラインで渡すこともできます。その場合、プログラムは自動的に実行されます。

- -

ビルドの資料に従って、make install を使用してビルド済みシェルをインストールした後は、次のコマンドを使用して対話モードでシェルを実行できます。

- -
js
-
- -

[ If you get " symbol lookup error: ./js: undefined symbol: PR_SetCurrentThreadName" e.g. from a Bash console when using a pre-compiled binary, try <path to your Firefox's run-mozilla.sh>/run-mozilla.sh ./js -- that worked for me]

- -

ファイル foo.js 内の JavaScript コードを実行したい場合は、次のコマンドを使用できます:

- -
js foo.js
-
- -

foo.js を実行してからインタラクティブシェルにドロップするには、次のようにします:

- -
js -f foo.js -i
-
- -

リファレンス

- -
メモ: JavaScript シェルは JavaScript エンジンのテスト環境として使用されるため、使用可能なオプションと組み込み関数は時間の経過とともに変わる可能性があります。
- -

コマンドラインオプション

- -

シェルを制御するために指定できるコマンドラインオプションは多数あります。これらは以下に要約されています。文書化されていないものがあるかどうかを確認するには、必ず自分の jsshell で -h を使用してください。

- -
-
-c, --compileonly
-
プログラムをコンパイルして実行しないようシェルに指示します。これは、プログラムを実行せずにプログラム内の構文エラーを素早くチェックするのに便利な方法です。
-
-e script
-
指定したスクリプトを実行します。これは、実行するコードを含むリテラル文字列です。
-
-f filename
-
filename で指定された JavaScript プログラムを実行します。
-
-i
-
インタラクティブモードを有効にします。(ファイル名が指定されていない場合はデフォルト)
-
--no-ion
-
最適化 JIT コンパイラを無効にします。
-
--no-baseline
-
ベースライン JIT コンパイラを無効にします。
-
-P
-
ファイルの最初の行が "/usr/bin/env js -P" の場合、ファイルの内容は JavaScript エンジンによって解釈されます。
-
これにより、JavaScript ファイルを UNIX および OS X マシン上で実行可能にすることができます。
-
-s
-
厳密な警告モードを有効にします。
-
-w, --warnings
-
警告メッセージを有効にします。
-
-W, --nowarnings
-
警告メッセージを無効にします。
-
- -

環境オプション

- -

js シェルの動作を変更するために設定できる環境変数がいくつかあります。

- -
-
JS_STDOUT=file
-
標準出力を file にリダイレクトします。
-
JS_STDERR=file
-
標準エラー出力を file にリダイレクトします。
-
- -

組み込み関数

- -

JavaScript シェルをより便利にするために、JavaScript プログラムからでもインタラクティブモードでも使える、多くの組み込み関数が提供されています。

- -
-

: このリストは不完全であり、Shell のグローバルオブジェクトと重複しています。詳しくは {{Source("js/src/shell/js.cpp")}} を参照してください (shell_functionsについて)。

-
- -

build()

- -

JavaScript シェルが構築された日時を返します。

- -
メモ: パラメータなしの clear() は本当にすべてをクリアします。これにはこれらすべての組み込み関数が含まれます。
- -

clone(function, [scope])

- -

指定された function オブジェクトを複製します。scope が指定されていない場合、新しいオブジェクトの親は元のオブジェクトのものと同じです。それ以外の場合、新しいオブジェクトは scope で指定されたオブジェクトの範囲内に配置されます。

- -

countHeap([start[, kind]])

- -

{{ jsapi_minversion_inline("1.8") }} ヒープ内のライブ GC のもの、または start から到達可能なもので、指定された値が null ではないものの数を数えます。kind はすべてのものを数える 'all' (デフォルト)、またはその種類のものだけを数えるための 'object', 'double', 'string', 'function', 'qname', 'namespace', 'xml' のいずれかです。

- -

dumpHeap([fileName[, start[, toFind[, maxDepth[, toIgnore]]]]])

- -

{{ jsapi_minversion_inline("1.8") }} 既存のすべてのオブジェクト (または特定の興味深い部分グラフ) のグラフをファイルにダンプします。詳しくは、この関数の C/C++ バージョン、JS_DumpHeap を参照してください。

- -

evalcx(string[, object])

- -

JavaScript コードを文字列で評価します。object が指定されている場合、コードはそのオブジェクト内で実行され、サンドボックスとして扱われます。

- -

string が空で object が指定されていない場合、evalcx() は、意欲的な標準クラスを持つ新しいオブジェクトを返します。

- -

string が "lazy" で object が指定されていない場合、evalcx() は lazy 標準クラスを持つ新しいオブジェクトを返します。

- -
メモ: evalcx() は、シェル内で evalInSandbox のような環境をテストするために、JavaScript エンジンの内部で深く作業している人にのみ役立ちます。
- -

gc()

- -

ガベージコレクタを実行してメモリを解放します。

- -

gcparam(name[, value])

- -

{{ jsapi_minversion_inline("1.8") }} ガベージコレクタのパラメータを読み込むか設定します。

- -

名前は https://searchfox.org/mozilla-central/source/js/src/builtin/TestingFunctions.cpp#464FOR_EACH_GC_PARAM で定義されているパラメータキーのいずれか ('maxBytes''maxMallocBytes'、'gcNumber' など) でなければなりません。

- -

value が指定されていない場合、gcparam() は name という名前の GC パラメータに関連付けられている現在の値を返します。

- -

value が指定されている場合、それは正の uint32 に変換可能でなければなりません。gcparam() は GC パラメータの namevalue に設定します。

- -

詳しくは C/C++ 関数の JS_GetGCParameter および JS_SetGCParameter を参照してください。

- -

gczeal(level)

- -

{{ jsapi_minversion_inline("1.8") }} DEBUG のみ。デバッグ機能である GC の活動量のレベルを設定します。これは、通常の定期的なガベージコレクションの場合は 0、非常に頻繁な GC の場合は 1、非常に頻繁な GC の場合は 2 になります。
- 0 以外は JavaScript の実行を非常に遅くしますが、GC 関連のバグを明らかにしたり再現したりするのに役立ちます。詳しくは、この関数の C/C++ バージョンである JS_SetGCZeal を参照してください。

- -

getpda(object)

- -

指定した object のプロパティ記述子を返します。

- -

getslx(object)

- -

指定されたオブジェクトを構成するコードの行数であるスクリプト行エクステントを返します。

- -

help([command ...])

- -

指定されたコマンド、または指定されていない場合は使用可能なすべての機能に関する簡単なヘルプ情報を表示します。

- -

intern(string)

- -

指定された string をアトムテーブルに内部化します。すべての文字列はアトムと呼ばれる一意の識別子を持ちます。このシステムにより、文字列間の比較が簡単になります。

- -
メモ: この関数は、JavaScript エンジンをテストするときにのみ使用されることを意図しています。
- -

line2pc([function, ] line)

- -

指定されたコード行に対応するプログラムカウンタ値を返します。function が指定されている場合、line は指定された関数へのオフセットです。

- -

load(filename1 [filename])

- -

指定された名前で JavaScript ファイルをロードします。

- -
メモ: JavaScript 以外のファイルをロードするには、read() を使用してください。
- -

options([option ...])

- -

オプションを設定または取得できます。コマンドラインでオプションを指定した場合、options を呼び出した結果は、どのオプションを要求したかを示します。新しいオプションを渡して設定することもできます。

- -

利用可能なオプションは以下のとおりです:

- - - - - - - - - - - - - - - - - - - - -
オプション名説明
strictストリクトモードが有効になります。
werror警告はエラーとして扱われます。
atlineatline が有効になっているとき、//@line num の形式のコメントは次の行の番号を num に設定します。
- -

pc2line(function, [pc])

- -

指定された function の最初の行に対応する JavaScript コードの行番号を返します。関数にプログラムカウンタオフセットを指定した場合は、そのオフセットを含むコード行の行番号が返されます。

- -

print([expression ...])

- -

expression(s) を評価し、その結果を stdout にスペース (" ") で区切って表示し、改行 ("\n") で終了します。

- -

putstr(expression)

- -

expression を評価し、その結果を stdout に表示します。

- -

quit([status])

- -

シェルを終了します。省略した場合、status はデフォルトで 0 になります。

- -

read(filename[, type])

- -

ファイルの内容を読み込んで返します。typeが "binary" の場合は Uint8Array が返され、それ以外の場合は UTF-8 でデコードされた文字列が返されます。

- -

readline()

- -

stdin から単一行の入力を読み込み、呼び出し元に返します。これを使って JavaScript でインタラクティブシェルプログラムを作成することができます。

- -

Reflect.parse()

- -

Parser API を参照してください。

- -
メモ: この関数は、JavaScript エンジンをテストするときにのみ使用することを意図しています。
- -

seal(object[, deep])

- -

指定した object、または deeptrue の場合はオブジェクトグラフをシールします。オブジェクトまたはオブジェクトグラフを封印することで、それらのオブジェクトの変更を無効にします。

- -

sleep(dt)

- -

{{ jsapi_minversion_inline("1.8") }} JS_THREADSAFE でのみビルドされます。dt 秒間スリープします。秒の端数がサポートされています。成功した場合にtrue、スリープが中断された場合にfalseを返します。

- -

stackQuota([number]) {{obsolete_inline}}

- -

スクリプトスタッククォータを取得または設定します。

- -

throwError()

- -

JS_ReportError() 関数からエラーをスローします。

- -
メモ: この関数は、JavaScript エンジンをテストするときにのみ使用することを意図しています。
- -

trap([function, [pc,]] expression)

- -

JavaScript コードの特定の位置にトラップを設定します。関数 functionpc で指定されたオフセットのバイトコードが実行されようとしているとき、式は評価されます。

- -

line2pc() と組み合わせて使用すると、これは強力なデバッグメカニズムです。たとえば、関数 doSomething() の 6 行目が実行されたときにメッセージを表示したい場合は、次のように入力します。

- -
trap(doSomething, line2pc(doSomething, 6), "print('line 6!\n')");
-
- -
メモ: トラップが設定されると、untrap() を使用してトラップを削除するまで、プログラム内の対応するバイトコードが trap バイトコードに置き換えられます。
- -

untrap(function [, pc])

- -

オフセット pc で指定した function からトラップを削除します。pc が指定されていない場合、トラップは関数のエントリポイントから削除されます。

- -

指定された場所にトラップがない場合、この機能は無効です。

- -

version([number])

- -

version() 関数を使用すると、JavaScript のバージョン番号を取得または設定できます。これは、特定のバージョンの JavaScript でのみ使用可能な構文にアクセスするのに役立ちます (たとえば、JavaScript 1.7 の使用を参照)。

- -

デバッグ関数

- -

これらの組み込み関数は DEBUG ビルドでのみ利用可能です。

- -

dis([function])

- -

プログラム全体、または指定された function の JavaScript バイトコードを逆アセンブルします。

- -

たとえば、以下の JavaScript 関数を入力したとします。

- -
function test() {
-  var i = 3;
-  print(i+2);
-}
-
- -

それから dis(test); コマンドを実行すると、この出力が得られます。

- -
main:
-00000:  uint16 3
-00003:  setvar 0
-00006:  pop
-00007:  name "print"
-00010:  pushobj
-00011:  getvar 0
-00014:  uint16 2
-00017:  add
-00018:  call 1
-00021:  pop
-00022:  stop
-
-Source notes:
-  0:     0 [   0] newline
-  1:     3 [   3] decl     offset 0
-  2:     7 [   4] newline
-  3:    18 [  11] xdelta
-  4:    18 [   0] pcbase   offset 11
-
- -

dissrc([function])

- -

プログラム全体または指定された function の JavaScript バイトコードを逆アセンブルして、ソース行を表示します。この関数は、シェルの起動時に -f フラグを使用するか、load() 関数を使用してファイルからロードされたプログラムに対してのみ機能します。

- -

プログラムに関数 doStuff() が含まれている場合は、次のようになります。

- -
function doStuff(input) {
-	print("Enter a number: ");
-	var n1 = readline();
-	print("Enter another one: ");
-	var n2 = readline();
-
-	print("You entered " + n1 + " and " + n2 + "\n");
-}
-
- -

dissrc(doStuff) 関数を呼び出すと、次の出力が得られます。

- -
;-------------------------  10:         print("Enter a number: ");
-00000:  10  name "print"
-00003:  10  pushobj
-00004:  10  string "Enter a number: "
-00007:  10  call 1
-00010:  10  pop
-;-------------------------  11:         var n1 = readline();
-00011:  11  name "readline"
-00014:  11  pushobj
-00015:  11  call 0
-00018:  11  setvar 0
-00021:  11  pop
-;-------------------------  12:         print("Enter another one: ");
-00022:  12  name "print"
-00025:  12  pushobj
-00026:  12  string "Enter another one: "
-00029:  12  call 1
-00032:  12  pop
-;-------------------------  13:         var n2 = readline();
-00033:  13  name "readline"
-00036:  13  pushobj
-00037:  13  call 0
-00040:  13  setvar 1
-00043:  13  pop
-;-------------------------  14:
-;-------------------------  15:         print("You entered " + n1 + " and " + n2 + "\n");
-00044:  15  name "print"
-00047:  15  pushobj
-00048:  15  string "You entered "
-00051:  15  getvar 0
-00054:  15  add
-00055:  15  string " and "
-00058:  15  add
-00059:  15  getvar 1
-00062:  15  add
-00063:  15  string "\\n"
-00066:  15  add
-00067:  15  call 1
-00070:  15  pop
-00071:  15  stop
-
- -

dumpheap(([fileName[, start[, toFind[, maxDepth[, toIgnore]]]]])

- -

GC 情報をダンプします。これは JS_DumpHeap の軽量なラッパーです。

- -

gczeal(zeal)

- -

GC の危険性の発見に役立つように、頻繁な GC を有効にします。zeal は整数です。意味は JS_SetGCZeal のパラメータと同じです。

- -

notes([function])

- -

指定した機能のソースノートを表示します。ソースノートには、バイトコードをソースコードにマップする情報が含まれています。これは、dissrc() 関数を使用する場合など、コードを逆コンパイルするときに使用されます。

diff --git a/files/ja/mozilla/projects/spidermonkey/jsapi_cookbook/index.html b/files/ja/mozilla/projects/spidermonkey/jsapi_cookbook/index.html deleted file mode 100644 index efb0e70aa0..0000000000 --- a/files/ja/mozilla/projects/spidermonkey/jsapi_cookbook/index.html +++ /dev/null @@ -1,514 +0,0 @@ ---- -title: JSAPI Cookbook -slug: Mozilla/Projects/SpiderMonkey/JSAPI_Cookbook -tags: - - SpiderMonkey -translation_of: Mozilla/Projects/SpiderMonkey/JSAPI_Cookbook ---- -

この記事は僅かなJavaScript共通の用語であるJSAPIについて記載しています。

- -
Note:  FOSS wiki ページには、 SpiderMonkey と JSAPI を使用する際に生活を楽にする他のライブラリやプログラムへのリンクがいくつか含まれています。
- -

基礎

- -

Finding the global object

- -

それらのレシピの多くは、最初に現在の大域オブジェクトを見つけることを要求します。

- -
// JavaScript
-var global = this;
-
- -

There is a function, JS_GetGlobalForScopeChain(cx)という関数があります。最良の考え方でありときにそれは大域オブジェクトの取得する場合最良の方法です。しかしJSNative の中では、これを実行する正しい方法は:

- -
/* JSAPI */
-JSBool myNative(JSContext *cx, uintN argc, jsval *vp)
-{
-    CallArgs args = CallArgsFromVp(argc, vp);
-    JSObject *global = JS_GetGlobalForObject(cx, &args.callee());
-    ...
-}
-
- -

関数定義

- -
// JavaScript
-function justForFun() {
-    return null;
-}
-
- -
/* JSAPI */
-JSBool justForFun(JSContext *cx, uintN argc, jsval *vp)
-{
-    JS_SET_RVAL(cx, vp, JSVAL_NULL);
-    return JS_TRUE;
-}
-
-...
-
-/*
- * Add this to your JSContext setup code.
- * This makes your C function visible as a global function in JavaScript.
- */
-if (!JS_DefineFunction(cx, global, "justForFun", &justForFun, 0, 0))
-    return JS_FALSE;
-
- -

JSAPI関数を一度に定義する場合、JS_DefineFunctions. を用います。 JS_DefineFunctions.

- -

配列の生成

- -
// JavaScript
-var x = [];  // or "x = Array()", or "x = new Array"
-
- -
/* JSAPI */
-JSObject *x = JS_NewArrayObject(cx, 0, NULL);
-if (x == NULL)
-    return JS_FALSE;
-
- -

オブジェクトの生成

- -
// JavaScript
-var x = {};  // or "x = Object()", or "x = new Object"
-
- -
/* JSAPI */
-JSObject *x = JS_NewObject(cx, NULL, NULL, NULL);
-if (x == NULL)
-    return JS_FALSE;
-
- -

オブジェクトの生成と初期化

- -
// JavaScript
-var person = new Person("Dave", 24);
-
- -

JavaScriptではとても単純に処理されています。しかし、JSAPIのアプリケーションでは以下に記述するように3つのことを処理する必要があります:

- - - -

(コンストラクタがどのよいうな引数も取らないならば、2番目の段階は省略して 3段階目の処理である JS_New(cx, constructor, 0, NULL) を呼び出せます。)

- -
/* JSAPI */
-
-jsval constructor_val;
-JSObject *constructor; /* BUG - not rooted */
-JSString *name_str;
-jsval argv[2];  /* BUG - not rooted */
-JSObject *obj;
-
-/* Step 1 - Get the value of |Person| and check that it is an object. */
-if (!JS_GetProperty(cx, JS_GetGlobalObject(cx), "Person", &constructor_val))
-    return JS_FALSE;
-if (JSVAL_IS_PRIMITIVE(constructor_val)) {
-    JS_ReportError(cx, "Person is not a constructor");
-    return JS_FALSE;
-}
-constructor = JSVAL_TO_OBJECT(constructor_val);
-
-/* Step 2 - Set up the arguments. */
-name_str = JS_NewStringCopyZ(cx, "Dave");
-if (!name_str)
-    return JS_FALSE;
-argv[0] = STRING_TO_JSVAL(name_str);
-argv[1] = INT_TO_JSVAL(24);
-
-/* Step 3 - Call |new Person(...argv)|, passing the arguments. */
-obj = JS_New(cx, constructor, 2, argv);
-if (!obj)
-    return JS_FALSE;
-
- -

大域的なJS関数の呼び出し

- -
// JavaScript
-var r = foo();  // where f is a global function
-
- -
/* JSAPI
- *
- * Suppose the script defines a global JavaScript
- * function foo() and we want to call it from C.
- */
-jsval r;
-if (!JS_CallFunctionName(cx, JS_GetGlobalObject(cx), "foo", 0, NULL, &r))
-   return JS_FALSE;
-
- -

局所変数を投資てJS関数を呼び出す

- -
// JavaScript
-var r = f();  // where f is a local variable
-
- -
/* JSAPI
- *
- * Suppose f is a local C variable of type jsval.
- */
-jsval r;
-if (!JS_CallFunctionValue(cx, NULL, f, 0, NULL, &r)
-    return JS_FALSE;
-
- -

整数の戻り値

- -
// JavaScript
-return 23;
-
- -
/* JSAPI
- *
- * Warning: This only works for integers that fit in 32 bits.
- * Otherwise, convert the number to floating point (see the next example).
- */
-JS_SET_RVAL(cx, vp, INT_TO_JSVAL(23));
-return JS_TRUE;
-
- -

浮動小数点少数の戻り値

- -
// JavaScript
-return 3.14159;
-
- -
/* JSAPI */
-jsdouble n = 3.14159;
-return JS_NewNumberValue(cx, n, rval);
-
- -

例外処理

- -

throw

- -

新規に最も共通の用語である エラー オブジェクトを生成した場合、それをハンドラに投げる場合 JS_ReportError が処理を行います。 Note JavaScript の例外はC++の例外処理とは異なります。JSAPIコードでは呼び出し側に誤りを通知するために JS_FALSE を返す必要があります。

- -
// JavaScript
-throw new Error("Failed to grow " + varietal + ": too many greenflies.");
-
- -
/* JSAPI */
-JS_ReportError(cx, "Failed to grow %s: too many greenflies.", varietal);
-return JS_FALSE;
-
- -

エラーメッセージを他国間対応にするには、 SyntaxErrorTypeError等のようにエラー種別を投げるように、 JS_ReportErrorNumber を代わりに用います。

- -

JavaScriptでは Error オブジェクトだけでなく、他の値を渡す事もサポートしています。 C/C++ から jsval という値を受け取るためにJS_SetPendingException を使います。

- -
// JavaScript
-throw exc;
-
- -
/* JSAPI */
-JS_SetPendingException(cx, exc);
-return JS_FALSE;
-
- -

JS_ReportError が新規に Error オブジェクトを生成するとき、現在実行中のスタックの先頭にあるJavaScriptコードの行の属性である fileNamelineNumber をセットします。 これは通常、あなたが本当に必要としているものとは一致しないネイティブ関数を呼び出したコードの行になります。JSAPIコードは直接 Error オブジェクトを生成し、コンストラクタに追加の引数を渡す事でことでこれを無視することができます:

- -
// JavaScript
-throw new Error(message, filename, lineno);
-
- -
/* JSAPI */
-JSBool ThrowError(JSContext *cx, JSObject *global,
-                  const char *message, const char *filename, int32 lineno)
-{
-    JSString *messageStr;
-    JSString *filenameStr;
-    jsval args[3];
-    jsval exc;
-
-    messageStr = JS_NewStringCopyZ(cx, message);
-    if (!messageStr)
-        return JS_FALSE;
-    filenameStr = JS_NewStringCopyZ(cx, filename);
-    if (!filenameStr)
-        return JS_FALSE;
-
-    args[0] = STRING_TO_JSVAL(messageStr);
-    args[1] = STRING_TO_JSVAL(filenameStr);
-    args[2] = INT_TO_JSVAL(lineno);
-    if (JS_CallFunctionName(cx, global, "Error", 3, args, &exc))
-        JS_SetPendingException(cx, exc);
-    return JS_FALSE;
-}
-
-...
-
-return ThrowError(cx, global, message, __FILE__, __LINE__);
-
- -

ここのJSAPIコードは、new がJSAPIを用いて擬似的に作り出すことが難しいため、 new なしに throw Error(message) を擬似的に作り出します。この場合、スクリプトが Errorを再定義しなければ、同じ事になります。

- -

catch

- -
// JavaScript
-try {
-    // try some stuff here; for example:
-    foo();
-    bar();
-} catch (exc) {
-    // do error-handling stuff here
-}
-
- -
/* JSAPI */
-    jsval exc;
-
-    /* try some stuff here; for example: */
-    if (!JS_CallFunctionName(cx, global, "foo", 0, NULL, &r))
-        goto catch_block;  /* instead of returning JS_FALSE */
-    if (!JS_CallFunctionName(cx, global, "bar", 0, NULL, &r))
-        goto catch_block;  /* instead of returning JS_FALSE */
-    return JS_TRUE;
-
-catch_block:
-    if (!JS_GetPendingException(cx, &exc))
-        return JS_FALSE;
-    JS_ClearPendingException(cx);
-    /* do error-handling stuff here */
-    return JS_TRUE;
-
- -

finally

- -
// JavaScript
-try {
-   foo();
-   bar();
-} finally {
-   cleanup();
-}
-
- -

C/C++の浄化コードがJSAPI内にコールバックしなければ、処理は単純になります:

- -
/* JSAPI */
-    JSBool success = JS_FALSE;
-
-    if (!JS_CallFunctionName(cx, global, "foo", 0, NULL, &r))
-        goto finally_block;  /* instead of returning JS_FALSE immediately */
-    if (!JS_CallFunctionName(cx, global, "bar", 0, NULL, &r))
-        goto finally_block;
-    success = JS_TRUE;
-    /* Intentionally fall through to the finally block. */
-
-finally_block:
-    cleanup();
-    return success;
-
- -

しかしながら、 cleanup() が実際にJavaScriptの関数であれば、それらはcatchされます。エラーが発生したとき、 JSContextの例外処理の待機がセットされます。 これは上の例で foo()bar() で発生するならば、待機中の例外処理は より悪い状態になるであろう cleanup() 処理を呼び出しているときにセットされます。これを避ける為に、JSAPIコードの実装では finally ブロックには以下のことが必要ですt:

- - - -
/* JSAPI */
-    JSBool success = JS_FALSE;
-    JSExceptionState *exc_state;
-
-    if (!JS_CallFunctionName(cx, global, "foo", 0, NULL, &r))
-        goto finally_block;  /* instead of returning JS_FALSE immediately */
-    if (!JS_CallFunctionName(cx, global, "bar", 0, NULL, &r))
-        goto finally_block;
-    success = JS_TRUE;
-    /* Intentionally fall through to the finally block. */
-
-finally_block:
-    exc_state = JS_SaveExceptionState(cx);
-    if (exc_state == NULL)
-        return JS_FALSE;
-    JS_ClearPendingException(cx);
-
-    if (!JS_CallFunctionName(cx, global, "cleanup", 0, NULL, &r)) {
-        /* The new error replaces the previous one, so discard the saved exception state. */
-        JS_DropExceptionState(cx, exc_state);
-        return JS_FALSE;
-    }
-    JS_RestoreExceptionState(cx, exc_state);
-    return success;
-
- -

オブジェクトの属性

- -

属性の取得

- -
// JavaScript
-var x = y.myprop;
-
- -

JSAPI関数で、属性を取得する関数が JS_GetPropertyです。JSObject * を引数として必要とします。 JavaScriptの値は、通常 jsval 変数に保存されるため、変数のキャストまたは変換が必要になります。

- -

y (ブール値、数値、文字列、 null, または undefinedなどではなく)がオブジェクトであることが確実な場合、これは非常に単純です。 JSVAL_TO_OBJECT を使い、 yJSObject *の型にキャストします。

- -
/* JSAPI */
-jsval x;
-
-assert(!JSVAL_IS_PRIMITIVE(y));
-if (!JS_GetProperty(cx, JSVAL_TO_OBJECT(y), "myprop", &x))
-    return JS_FALSE;
-
- -

もし y がオブジェクトでなければ、コードは壊れます。これはときに受け入れ難いことです。代替的にJavaScriptに振る舞いを擬似的に実行することになります。非常に良い考えですJavaScriptはクラッシュしません。しかし、その正確な振る舞いの実装では、非常に複雑なものになります。

- -

多くの実装では、特別に処理が扱いやすくなるわけではありません。通常、 !JSVAL_IS_PRIMITIVE(y) を検査し、良いメッセージとともに Error を投げることが最良な処理です。

- -
/* JSAPI */
-jsval x;
-
-if (JSVAL_IS_PRIMITIVE(y))
-    return ThrowError(cx, global, "Parameter y must be an object.", __FILE__, __LINE__);  /* see the #throw example */
-if (!JS_GetProperty(cx, JSVAL_TO_OBJECT(y), "myprop", &x))
-    return JS_FALSE;
-
- -

属性の設定

- -
// JavaScript
-y.myprop = x;
-
- -

y がオブジェクトではない場合を懸念するならば、上述の属性の取得を参照して下さい。

- -
/* JSAPI */
-assert(!JSVAL_IS_PRIMITIVE(y));
-if (!JS_SetProperty(cx, JSVAL_TO_OBJECT(y), "myprop", &x))
-    return JS_FALSE;
-
- -

属性の検査

- -
// JavaScript
-if ("myprop" in y) {
-    // then do something
-}
-
- -

y がオブジェクトではない場合を懸念するならば、上述の属性の取得を参照して下さい。

- -
/* JSAPI */
-JSBool found;
-
-assert(!JSVAL_IS_PRIMITIVE(y));
-if (!JS_HasProperty(cx, JSVAL_TO_OBJECT(y), "myprop", &found))
-    return JS_FALSE;
-if (found) {
-    // then do something
-}
-
- -

固定属性を定義する

- -

これはビルトイン関数 Object.defineProperty()に関わる最初の3つの例です。この関数は、オブジェクトの個別の属性の挙動に関してはっきりした操作をJavaScriptのコードに与えます。

- -

この関数を使って、上書きや削除できない固定属性を生成できます。writable: false によって属性を読み出し専用に作り、 configurable: false に設定して、再定義や削除されることから防ぎます。 フラグ enumerable: true は forループ内にあるときにこの属性が設定されます。

- -
// JavaScript
-Object.defineProperty(obj, "prop", {value: 123,
-                                    writable: false,
-                                    enumerable: true,
-                                    configurable: false});
-
- -

JSAPI関数の類似した関数に、 JS_DefinePropertyがあります。属性 JSPROP_READONLY を持っており、その属性はwriteable: falseに一致します。JSPROP_ENUMERATEenumerable: true,に一致し、 JSPROP_PERMANENTconfigurable: falseにその属性が一致します。これらの設定の相対的な挙動を得るためには、必要ない属性のビットを単純に省いて下さい。

- -
/* JSAPI */
-if (!JS_DefineProperty(cx, obj, "prop", INT_TO_JSVAL(123),
-                       JS_PropertyStub, JS_StrictPropertyStub,
-                       JSPROP_READONLY | JSPROP_ENUMERATE | JSPROP_PERMANENT)) {
-   return JS_FALSE;
-}
-
- -

設定と取得の属性の定義

- -

Object.defineProperty() は二つのアクセス関数の属性を定義する為に用いることができます。

- -
// JavaScript
-Object.defineProperty(obj, "prop", {get: GetPropFunc,
-                                    set: SetPropFunc,
-                                    enumerable: true});
-
- -

JSAPIバージョンでは、 GetPropFuncSetPropFuncJSNative型のC/C++ 関数関数として用意されています。of type .

- -
/* JSAPI */
-if (!JS_DefineProperty(cx, obj, "prop", JSVAL_VOID,
-                       (JSPropertyOp) GetPropFunc, (JSStrictPropertyOp) SetPropFunc,
-                       JSPROP_SHARED | JSPROP_NATIVE_ACCESSORS | JSPROP_ENUMERATE)) {
-    return JS_FALSE;
-}
-
- -

取得のための呼び出し専用属性の定義

- -
// JavaScript
-Object.defineProperty(obj, "prop", {get: GetPropFunc,
-                                    enumerable: true});
-
- -

JSAPIバージョン では、属性を読み出し専用に定義し、設定用にはNULLを通します。

- -
/* JSAPI */
-if (!JS_DefineProperty(cx, obj, "prop", JSVAL_VOID,
-                       GetPropFunc, NULL,
-                       JSPROP_SHARED | JSPROP_NATIVE_ACCESSORS | JSPROP_ENUMERATE)) {
-    return JS_FALSE;
-}
-
- -

プロトタイプチェインの働き

- -

String.prototypeにネイティブでは読み出し専用属性を定義します

- -
// JavaScript
-Object.defineProperty(String.prototype, "md5sum", {get: GetMD5Func,
-                                                   enumerable: true});
-
- -

何かが大域的なStringオブジェクトを別な何かに取り替えるならば、以下のようなトリックは動作しません。

- -
/* JSAPI */
-JSObject   *string, *string_prototype;
-jsval       val;
-
-// Get the String constructor from the global object.
-if (!JS_GetProperty(cx, global, "String", &val))
-    return JS_FALSE;
-if (JSVAL_IS_PRIMITIVE(val))
-    return ThrowError(cx, global, "String is not an object", __FILE__, __LINE__);
-string = JSVAL_TO_OBJECT(val);
-
-// Get String.prototype.
-if (!JS_GetProperty(cx, string, "prototype", &val))
-    return JS_FALSE;
-if (JSVAL_IS_PRIMITIVE(val))
-    return ThrowError(cx, global, "String.prototype is not an object", __FILE__, __LINE__);
-string_prototype = JSVAL_TO_OBJECT(val);
-
-// ...and now we can add some new functionality to all strings.
-if (!JS_DefineProperty(cx, string_prototype, "md5sum", JSVAL_VOID, GetMD5Func, NULL,
-                       JSPROP_SHARED | JSPROP_NATIVE_ACCESSORS | JSPROP_ENUMERATE))
-    return JS_FALSE;
-
- -

Wanted

- - diff --git a/files/ja/mozilla/projects/spidermonkey/jsapi_reference/alphabetical_list/index.html b/files/ja/mozilla/projects/spidermonkey/jsapi_reference/alphabetical_list/index.html deleted file mode 100644 index 4bf1ac4123..0000000000 --- a/files/ja/mozilla/projects/spidermonkey/jsapi_reference/alphabetical_list/index.html +++ /dev/null @@ -1,228 +0,0 @@ ---- -title: Alphabetical List -slug: Mozilla/Projects/SpiderMonkey/JSAPI_reference/Alphabetical_List -tags: - - JSAPI_Reference - - SpiderMonkey ---- -

参照: グループ別一覧, カテゴリ表示 (自動).

- diff --git a/files/ja/mozilla/projects/spidermonkey/jsapi_reference/index.html b/files/ja/mozilla/projects/spidermonkey/jsapi_reference/index.html deleted file mode 100644 index 5bb96c5566..0000000000 --- a/files/ja/mozilla/projects/spidermonkey/jsapi_reference/index.html +++ /dev/null @@ -1,926 +0,0 @@ ---- -title: JSAPI リファレンス -slug: Mozilla/Projects/SpiderMonkey/JSAPI_reference -tags: - - JSAPI_Reference - - JavaScript - - SpiderMonkey -translation_of: Mozilla/Projects/SpiderMonkey/JSAPI_reference ---- - - -

JSAPI は、SpiderMonkey JavaScript エンジンのための C API です。JSAPI の使用方法を学ぶには、JSAPI User Guide および JSAPI Phrasebook をご覧ください。

- -
補足: FOSS のページに、Spidermonkey と JASPI の使用を助ける、他のライブラリやプログラムへのリンクがあります。
- -

アルファベット順一覧

- -

- -

ランタイムとコンテキスト

- - - - - - - - - - - -

ロケールコールバック:

- - - -

ロケールコールバック型:

- - - -

- -

スクリプト

- -

一部の JavaScript コードは直接実行されます:

- - - -

JavaScript コードを可能な JSScript へとコンパイルする代わりに、複数のアイテムを実行することができます。

- - - -

JavaScript コードを関数へとコンパイルすることもできます:

- - - -

- -

エラーハンドリング

- - - -

次の関数は、C/C++ 関数に JavaScript 例外のスローとキャッチを許可します。:

- - - - - -

これらの関数は、エラーを例外に、例外をエラーに翻訳します:

- - - -

- -

値と型

- - - -

jsval 定数:

- - - -

jsval の型をチェックする関数とマクロ:

- - - -

関数の引数を圧縮または展開する高レベル型変換ルーチン。

- - - - - -

次の関数は JS 値を変数型に変換します。これらは任意の型の jsval に安全に適用することができます。これらは新しいオブジェクトを返します。例えば、JS_ValueToObject(cx, s)s は新しい String ラッパーオブジェクトを作成する文字列です。これらの関数は JavaScript メソッドを呼び出します。例えば、JS_ValueToString(cx, obj)obj.toString() を呼び出します。

- - - -

高速な未チェックの型キャストマクロ。これらのマクロは正しい型として知られていない値に適用してはいけません。C のキャストのように、正しくない値に適用するとクラッシュの原因となります。これらは新しいオブジェクトを作成したり JavaScript コード内に呼び出したりすることはありません。

- - - -

typeof のように振る舞う関数:

- - - -

=== のように振る舞う関数:

- - - -

- -

メモリ管理

- -

これらの関数は、標準 C 関数の malloc 系のように動作します。ただし、エラーは errno ではなく、SpiderMonkey のエラー API を使用して報告されます:

- - - -

JavaScript オブジェクト、文字列、浮動小数点数はガーベッジコレクションの対象となります。これらの関数は、ガーベッジコレクタ(GC) へのアクセスを提供します:

- - - -

これら残りの API は、アプリケーションがガーベッジコレクションを行う前に、オブジェクトをガーベッジコレクタによる破壊から保護します。

- -

変数が root の場合、その変数へのポインタはガーベッジコレクタによって開放されません。ルートオブジェクトに対しての失敗は、よくある奇妙なクラッシュの原因です。

- - - -

ローカルのルートのスコープは、オブジェクトを別の方法でガーベッジコレクタから保護します。

- - - -

SpiderMonkey 1.8 (未リリース) の新機能 オブジェクトが、SpiderMonkey のデータ構造 ("slots") に格納されていない、他のガーベッジコレクタの対象への参照を含む場合、このオブジェクトは、ガーベッジコレクタのこれらの参照へのトラバース (traverse)を有効にするため、JSTraceOp フックを実装しなければなりません。しかし、ガーベッジコレクタは手の届く範囲のオブジェクトのみを整理しますが、すべてのオブジェクトを見つけることはできないため、クラッシュを引き起こします。(SpiderMonkey 1.7 以前のバージョンでは JSMarkOp フックが代わりに使用されます。これは SpiderMonkey 1.8 のリリース後は非推奨です。)

- -

トレース API は、ガーベッジコレクタと JSTraceOp フックによって使用されます。JSAPI アプリケーションもまた、これらの API をオブジェクトグラフを検査するために使用します。(例えば、これらの API は JS ガーベッジコレクタと他のガーベッジコレクタの、とても円滑な統合をサポートします。)

- - - -

その他の GC API:

- - - -

- -

数値

- - - -

- -

文字列

- - - - - -

Interning 文字列は SpiderMonkey エンジンに、可能ならば既存の文字列オブジェクトを再使用するように伝えます。

- - - -

external strings のための文字データはアプリケーションによって提供されるメモリに格納されます。アプリケーションはこれを、SpiderMonkey のヒープとアプリケーションのメモリの間で、データを先や後へコピーすることを防止するために使用します。

- - - -

- -

オブジェクト

- - - - - -

- -

プロパティ

- -

これらの関数は、直接スクリプトがオブジェクトのプロパティにアクセスする方法に相当します:

- - - -

次の低レベルの関数は、JSAPI アプリケーションが、プロパティの実装方法の詳細へのアクセスを許可します。"Define" は "set" の低レベル版であり、追加の設定へのアクセスを提供し、setter を呼び出しません。同様に、"lookup" は "get" の低レベル版であり、追加のオプションを与え、getter を呼び出しません。

- - - -

次の関数は、JS_GetProperty および JS_GetPropertyById のように振る舞います。ただし、E4X XML オブジェクト上の操作は除きます。

- - - -

SpiderMonkey 拡張は lvalue(オブジェクトのプロパティへの参照) を返すネイティブ関数を許可します:

- - - -

jsidjsval の一種です。ごく少数の API が、jsval の代わりに jsid をプロパティ名に使用します: JS_CheckAccess および JS_Enumerate, JS_GetMethodById, JS_NextProperty

- - - -

jsid 定数:

- - - -

jsid の型を調べる関数とマクロ:

- - - -

- -

クラス

- -

これらの API 機能は、C/C++ に実装された JavaScript からアクセス可能なカスタムクラス—オブジェクト型の定義に使用されます。

- - - -

ネイティブプロパティとメソッドをクラスに追加:

- - - -

JSFastNative メソッドはこれらのマクロを使用します: SpiderMonkey 1.8 の新機能

- - - -

JSClass の振る舞いとそのインスタンスは、コールバック関数を使用して多くの方法でカスタマイズすることができます。

- -

JSClass メソッド型:

- - - -

JSExtendedClass メソッド型:

- - - -

JSObjectOps メソッド型:

- - - -

JSXMLObjectOps メソッド型:

- - - -

これらの stub 関数はカスタム JSClass の作成時に使用されます:

- - - -

JSClass の振る舞いは、これらのフラグを使用してカスタマイズできます:

- - - -

- -

配列

- - - - - - - -

- -

関数

- -

関数またはオブジェクトのメソッドの呼び出し:

- - - -

関数アクセサリ:

- - - -

関数の生成:

- - - -

- -

正規表現

- - - -

- -

セキュリティ

- -

SpiderMonkey 1.8.1 の新機能 セキュリティのコールバックは、ランタイムごと、またはコンテキストごとに設定できます。

- - - -

- -

スレッド

- -

次の関数は SpiderMonkey のスレッドモデルをサポートしています。

- -

JSAPI 1.7 まで これらは JS_THREADSAFE ビルドでのみ利用可能です。

- -

SpiderMonkey 1.8 の新機能 これらの関数はいつでも利用可能です。ただし、JS_THREADSAFE 無しのビルドでは何もしません

- - - -

次の関数はすべてのビルドに存在します。ただし、JS_THREADSAFE 無しのビルドでは何もしません:

- - - -

- -

時間

- - - -

- -

コールバック型

- -

ネイティブ関数型:

- - - -

その他のコールバック型:

- - - -

上記のクラスも参照してください。

- -

- -

マクロ

- - - -

- -

C++ の機能

- - diff --git a/files/ja/mozilla/projects/spidermonkey/jsapi_reference/js_compilefile/index.html b/files/ja/mozilla/projects/spidermonkey/jsapi_reference/js_compilefile/index.html deleted file mode 100644 index a6d409dc85..0000000000 --- a/files/ja/mozilla/projects/spidermonkey/jsapi_reference/js_compilefile/index.html +++ /dev/null @@ -1,66 +0,0 @@ ---- -title: JS CompileFile -slug: Mozilla/Projects/SpiderMonkey/JSAPI_reference/JS_CompileFile -tags: - - JSAPI Reference - - SpiderMonkey -translation_of: Mozilla/Projects/SpiderMonkey/JSAPI_reference/JS_CompileUTF8File ---- -

- -

- -

- -

外部ファイルに含まれるスクリプトをコンパイルします。 Compile a script stored in an external file.

- -

構文

- -
JSScript * JS_CompileFile(JSContext *cx, JSObject *obj,
-    const char *filename);
-
- - - - - - - - - - - - - - - - - - - - - - - - -
NameTypeDescription
cxJSContext *スクリプトをコンパイルするときのコンテキスト {{ Jsapi-requires-request() }}
objJSObject *スクリプトと関連付けるオブジェクトObject with which the script is associated.
filenameconst char *スクリプトを含むファイルの名前Name of file containing the script to compile.
- -

解説

- -

JS_CompileFileは、JavaScriptエンジンで実行するために外部ファイルのスクリプトをコンパイルする関数です。 <code>JS_CompileFile</code> compiles the text of script in an external file location for execution by the JS engine.

- -

filenameは、コンパイル対象のスクリプトを含んでいるファイルの名前を引数に取ります。 <code>filename</code> is the name of the file containing the script to compile.

- -

コンパイルが成功したとき、JS_CompileFileはコンパイル済みのスクリプトへのポインタを返値とします。失敗時にはNULLを返します。 On success, <code>JS_CompileFile</code> returns a pointer to the compiled script. Otherwise it returns <code>NULL</code>.

- -

ファイル名でスクリプトを指定するのではなく、文字列の引数として関数に渡す場合には、JS_CompileScriptを使ってください。 To pass a script as an argument to a function rather than having to specify a file location, use <code>JS_CompileScript</code> instead.

- -

関連項目

- -

{{ LXRSearch("ident", "i", "JS_CompileFile") }}

- -

JS_CompileScript, JS_DecompileScript, JS_DestroyScript, JS_EvaluateScript, JS_ExecuteScript

- -

{{ languages( { "en": "en/JS_CompileFile" } ) }}

diff --git a/files/ja/mozilla/projects/spidermonkey/jsapi_reference/js_constructobject/index.html b/files/ja/mozilla/projects/spidermonkey/jsapi_reference/js_constructobject/index.html deleted file mode 100644 index ae7b116ff2..0000000000 --- a/files/ja/mozilla/projects/spidermonkey/jsapi_reference/js_constructobject/index.html +++ /dev/null @@ -1,63 +0,0 @@ ---- -title: JS ConstructObject -slug: Mozilla/Projects/SpiderMonkey/JSAPI_reference/JS_ConstructObject -tags: - - JSAPI Reference - - SpiderMonkey -translation_of: Mozilla/Projects/SpiderMonkey/JSAPI_reference/JS_ConstructObject ---- -

-

- -

新たにJavaScriptオブジェクトを生成し、コンストラクタを呼び出します。 Create a new JavaScript object and invoke its constructor.

- -

構文

- -
JSObject * JS_ConstructObject(JSContext *cx, JSClass *clasp,
-    JSObject *proto, JSObject *parent);
-
- - - - - - - - - - - - - - - - - - - - - - - - -
NameTypeDescription
cxJSContext *新たなオブジェクトを配置するコンテキストThe context in which to create the new object. {{ jsapi-requires-request }}</td> </tr> <tr> <td><code>clasp</code></td> <td><code>JSClass *</code></td> <td>オブジェクト生成時に利用するクラスへのポインタ。<code>NULL</code>を指定したときは、一般的なJavaScript <code>Object</code>が生成されます。<!--Pointer to the class to use for the new object. If this is <code>NULL</code>, an ordinary JavaScript <code>Object</code> is created.
protoJSObject *クラスとなるプロトタイプオブジェクトへのポインタPointer to the prototype object to use for the new class.
parentJSObject *新たなオブジェクトの __parent__ プロパティに指定するオブジェクトへのポインタPointer to which to set the new object's __parent__ property.
- -

解説

- -

JS_ConstructObjectは、与えられたクラス、プロトタイプ、親オブジェクト、コンストラクタ関数をもとに新たなオブジェクトのインスタンスを生成する関数です。cxには、新たなオブジェクトを配置するランタイムと結び付けられたコンテキストへのポインタを指定します。claspには、ファイナライズ処理などの内部関数が定義された既存クラスへのポインタを指定します。protoは、新たなオブジェクトのプロトタイプとなるオブジェクトへのポインタを指定する引数です。 <code>JS_ConstructObject</code> instantiates a new object based on a specified class, prototype, and parent object, and then invokes its constructor function. <code>cx</code> is a pointer to a context associated with the runtime in which to establish the new object. <code>clasp</code> is a pointer to an existing class to use for internal methods, such as finalize. <code>proto</code> is an optional pointer to the prototype object with which to associate the new object.

- -

自分自身をプロトタイプオブジェクトにするには、protoNULLを指定してください。このとき、claspがプロトタイプを定義している場合には、JS_ConstructObjectは新たなオブジェクトのプロトタイプにそれを用います。定義していない場合は、空オブジェクトスタブをプロトタイプとします。 Set <code>proto</code> to <code>NULL</code> to force JS to assign a prototype object for you. In this case, <code>JS_ConstructObject</code> attempts to assign the new object the prototype object belonging to <code>clasp</code>, if one is defined there. Otherwise, it creates an empty object stub for the prototype.

- -

parentには、新規オブジェクトの親プロパティとなるオブジェクトへのポインタを指定します。この引数はオプションであり、parentNULLを指定することで親プロパティを持たないオブジェクトになります。 <code>parent</code> is an optional pointer to an existing object to which to set the new object's parent object property. You can set <code>parent</code> to <code>NULL</code> if you do not want to set the parent property.

- -

JS_ConstructObjectが成功したとき、新たに生成されたオブジェクトへのポインタをその返値とします。失敗したときはNULLを返します。 On success, <code>JS_ConstructObject</code> returns a pointer to the newly instantiated object. Otherwise it returns <code>NULL</code>.

- -

関連項目

- -

{{ LXRSearch("ident", "i", "JS_ConstructObject") }}

- -

JS_DefineObject, JS_GetFunctionObject, JS_NewArrayObject, JS_NewObject, JS_ValueToObject

- -

{{ languages( { "en": "en/JS_ConstructObject" } ) }}

diff --git a/files/ja/mozilla/projects/spidermonkey/jsapi_reference/js_defineobject/index.html b/files/ja/mozilla/projects/spidermonkey/jsapi_reference/js_defineobject/index.html deleted file mode 100644 index 782201ccc5..0000000000 --- a/files/ja/mozilla/projects/spidermonkey/jsapi_reference/js_defineobject/index.html +++ /dev/null @@ -1,126 +0,0 @@ ---- -title: JS_DefineObject -slug: Mozilla/Projects/SpiderMonkey/JSAPI_reference/JS_DefineObject -tags: - - JSAPI Reference - - SpiderMonkey -translation_of: Mozilla/Projects/SpiderMonkey/JSAPI_reference/JS_DefineObject ---- -

-

-

- -

あるオブジェクトのプロパティとなるオブジェクトを生成する関数です。 Create an object that is a property of another object. {{ 英語版章題("Syntax") }}

- -

構文

- -
JSObject * JS_DefineObject(JSContext *cx, JSObject *obj,
-    const char *name, JSClass *clasp, JSObject *proto,
-    uintN flags);
-
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameTypeDescription
cxJSContext *エラー報告に用いるランタイム環境から派生したコンテキストへのポインタPointer to a JS context from which to derive runtime information for error reporting. {{ Jsapi-requires-request() }}
objJSObject *生成したオブジェクトをプロパティとして持つオブジェクトへのポインタObject to which this new object belongs as a property.
nameconst char *objでのプロパティ名Name of the property that encapsulates the new object in <code>obj</code>.
claspJSClass *オブジェクト生成に用いるクラスClass to use for the new object.
protoJSObject *オブジェクト生成に用いるプロトタイプPrototype object to use for the new object.
flagsuintN生成したオブジェクトの属性を指定するフラグProperty flags for the new object.
- -

{{ 英語版章題("Description") }}

- -

説明

- -

JS_DefineObjectは、オブジェクトのインスタンスを生成し、それを引数objで指定した既存オブジェクトのプロパティとして設定する関数です。引数nameで、objでのプロパティ名を指定し、flagsでそのプロパティの属性を指定します。以下の表で設定可能なflagsの値を示します。これらの値は単一、あるいは複数の値の論理和として引数に与えることができます。 <code>JS_DefineObject</code> instantiates and names a new object for an existing object, <code>obj</code>. <code>name</code> is the property name to assign to <code>obj</code> to hold the new object, and <code>flags</code> contains the property flags to set for the newly created property. The following table lists possible values you can pass in <code>flags</code>, either singly, or <code>OR</code>'d together:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FlagPurpose
JSPROP_ENUMERATEforinループを使ったアクセス(Core JavaScript 1.5 Guide:Object Manipulation Statements)を可能にします。Property is visible to <code>for</code> and <code>in</code> loops.
JSPROP_READONLYプロパティの値を読み取り専用にします。Property is read only.
JSPROP_PERMANENTプロパティの削除を不可能にします。Property cannot be deleted.
JSPROP_EXPORTEDProperty can be imported by other objects.
JSPROP_INDEXProperty is actually an index into an array of properties, and is cast to a const char *.
- -

引数claspはオブジェクトの生成時に用いる基底クラスへのポインタ、引数protoはプロトタイプへのポインタをそれぞれとります。protoNULLを指定した場合、JavaScriptは自分自身をプロトタイプとします。引数objはオブジェクトの親オブジェクトになります。 <code>clasp</code> is a pointer to the base class to use when creating the new object, and <code>proto</code> is an pointer to the prototype upon which to base the new object. If you set <code>proto</code> to <code>NULL</code>, JS sets the prototype object for you. The parent object for the new object is set to <code>obj</code>.

- -

JS_DefineObjectが成功したとき、返値は新たに生成したプロパティオブジェクトへのポインタになります。もしすでにプロパティが設定されていた場合、オブジェクトは生成されず、返り値はNULLになります。 <code>JS_DefineObject</code> returns a pointer to the newly created property object if successful. If the property already exists, or cannot be created, <code>JS_DefineObject</code> returns <code>NULL</code>. {{ 英語版章題("See Also") }}

- -

参照

- - - - - - - - - - - - - - - - -
GroupsFunctions
Documents{{ LXRSearch("ident", "i", "JS_DefineObject", "LXR ID Search") }}
Entries -

JSClass, JS_DefineConstDoubles, JS_DefineElement, JS_DefineFunction, JS_DefineFunctions, JS_DefineProperties, JS_DefineProperty, JS_DefinePropertyWithTinyId, JS_NewObject, JS_ValueToObject

-
- -
 
- -

{{ languages( { "en": "en/JS_DefineObject" } ) }}

diff --git a/files/ja/mozilla/projects/spidermonkey/jsapi_reference/js_destroycontext/index.html b/files/ja/mozilla/projects/spidermonkey/jsapi_reference/js_destroycontext/index.html deleted file mode 100644 index be77b35a40..0000000000 --- a/files/ja/mozilla/projects/spidermonkey/jsapi_reference/js_destroycontext/index.html +++ /dev/null @@ -1,55 +0,0 @@ ---- -title: JS DestroyContext -slug: Mozilla/Projects/SpiderMonkey/JSAPI_reference/JS_DestroyContext -tags: - - JSAPI Reference - - SpiderMonkey -translation_of: Mozilla/Projects/SpiderMonkey/JSAPI_reference/JS_DestroyContext ---- -

- - -

- - -

- -

JSContextを解放します。

- -

構文

- -
void JS_DestroyContext(JSContext *cx);
-
-void JS_DestroyContextNoGC(JSContext *cx);
-
-void JS_DestroyContextMaybeGC(JSContext *cx);
-
- - - - - - - - - - - - - - -
NameTypeDescription
cxJSContext *解放するコンテキスト
- -

解説

- -

これらの関数はコンテキストcxを解放します。それに加え、JS_DestroyContextは実行し、cxグローバルオブジェクトが利用したメモリを回収するためにガベージコレクションを実行します。JS_DestroyContextNoGCはガベージコレクションを実行しません。JS_DestroyContextMaybeGCでは、JavaScriptエンジンが十分なメモリ領域を解放できる可能性を判断し、ガベージコレクションを実行するか否かを判断します。 These functions destroy a context, <code>cx</code>. <code>JS_DestroyContext</code> additionally performs garbage collection to reclaim any memory that was being used by <code>cx</code>'s global object. <code>JS_DestroyContextNoGC</code> does not perform garbage collection. <code>JS_DestroyContextMaybeGC</code> may or may not perform garbage collection; the engine makes an educated guess as to whether enough memory would be reclaimed to justify the work.

- -

JS_THREADSAFEを有効にしたビルドでは、cxのrequest内でこの関数を呼ばないでください。

- -

JS_SetContextCallbackが以前に実行された場合は、そこで設定したコールバック関数が実行されます。 In a <code>JS_THREADSAFE</code> build, the caller must '''not''' be in a request on <code>cx</code>. If <code>JS_SetContextCallback</code> has been called, this calls the callback.

- -

{{ LXRSearch("ident", "i", "JS_DestroyContext") }}

- -

{{ languages( { "en": "en/JS_DestroyContext" } ) }}

diff --git a/files/ja/mozilla/projects/spidermonkey/jsapi_reference/js_destroyruntime/index.html b/files/ja/mozilla/projects/spidermonkey/jsapi_reference/js_destroyruntime/index.html deleted file mode 100644 index d65b41c6d6..0000000000 --- a/files/ja/mozilla/projects/spidermonkey/jsapi_reference/js_destroyruntime/index.html +++ /dev/null @@ -1,45 +0,0 @@ ---- -title: JS DestroyRuntime -slug: Mozilla/Projects/SpiderMonkey/JSAPI_reference/JS_DestroyRuntime -tags: - - JSAPI Reference - - SpiderMonkey -translation_of: Mozilla/Projects/SpiderMonkey/JSAPI_reference/JS_DestroyRuntime ---- -

- -

- -

- -

JavaScriptランタイム環境を解放します。 Frees a JavaScript runtime.

- -

構文

- -
void JS_DestroyRuntime(JSRuntime *rt);
-
- - - - - - - - - - - - - - -
NameTypeDescription
rtJSRuntime *解放するランタイムThe runtime to destroy.
- -

説明

- -

JS_DestroyRuntimeは、JavaScriptランタイム環境rtを解放する関数です。JSAPIの利用を終えた後は必ずJS_DestroyRuntimeを呼び出してください。JS_DestroyRuntimeを呼ぶことで、ガベージコレクションおよびJS_NewRuntimeによって確保されたメモリ領域の解放が行われます。 <code>JS_DestroyRuntime</code> frees the specified the JavaScript runtime environment, <code>rt</code>. Call <code>JS_DestroyRuntime</code> after completing all other JS API calls. <code>JS_DestroyRuntime</code> garbage collects and frees the memory previously allocated by <code>JS_NewRuntime</code>.

- -

{{ LXRSearch("ident", "i", "JS_DestroyRuntime") }}

- -

{{ languages( { "en": "en/JS_DestroyRuntime" } ) }}

diff --git a/files/ja/mozilla/projects/spidermonkey/jsapi_reference/js_dumpheap/index.html b/files/ja/mozilla/projects/spidermonkey/jsapi_reference/js_dumpheap/index.html deleted file mode 100644 index 4a9b9b3dba..0000000000 --- a/files/ja/mozilla/projects/spidermonkey/jsapi_reference/js_dumpheap/index.html +++ /dev/null @@ -1,110 +0,0 @@ ---- -title: JS_DumpHeap -slug: Mozilla/Projects/SpiderMonkey/JSAPI_reference/JS_DumpHeap -translation_of: Mozilla/Projects/SpiderMonkey/JSAPI_reference/JS_DumpHeap ---- -
{{SpiderMonkeySidebar("JSAPI")}}
- -

{{ obsolete_header("jsapi38") }}

- -

{{ Jsapi_minversion_header("1.8") }}

- -
DEBUG のみ。ヒープに割り当てられたもののオブジェクトグラフをダンプします。
- -

構文

- -
bool
-JS_DumpHeap(JSRuntime *rt, FILE *fp, void* startThing, JSGCTraceKind kind,
-            void *thingToFind, size_t maxDepth, void *thingToIgnore);
-
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameTypeDescription
cx{{jsapixref("JSRuntime", "JSContext *")}}Pointer to a JS context. Every JSContext is permanently associated with a JSRuntime; each JSRuntime contains a GC heap.
fpFILE *File for the dump output.
startThingvoid *NULL or a pointer to a GC thing (use {{jsapixref("JS::Value", "JS::Value::toGCThing()")}} to obtain a pointer to pass here). When null, dump all things reachable from the runtime roots. When non-null, dump only things reachable from the object indicated.
startKindJSGCTraceKindTrace kind of startThing, if startThing is not null. Must be JSTRACE_OBJECT when startThing is null.
thingToFindvoid *NULL or a pointer to a GC thing. If this is non-null, JS_DumpHeap only dumps paths in the object graph leading to the specified thing.
maxDepthsize_tThe upper bound on the number of edges to descend from the graph roots.
thingToIgnorevoid *NULL or a pointer to a GC thing that will be ignored during graph traversal.
- -
enum JSGCTraceKind
-{
-    // These trace kinds have a publicly exposed, although opaque, C++ type.
-    // Note: The order here is determined by our Value packing. Other users
-    //       should sort alphabetically, for consistency.
-    JSTRACE_OBJECT = 0x00,
-    JSTRACE_STRING = 0x01,
-    JSTRACE_SYMBOL = 0x02,
-    JSTRACE_SCRIPT = 0x03,
-
-    // Shape details are exposed through JS_TraceShapeCycleCollectorChildren.
-    JSTRACE_SHAPE = 0x04,
-
-    // The kind associated with a nullptr.
-    JSTRACE_NULL = 0x06,
-
-    // A kind that indicates the real kind should be looked up in the arena.
-    JSTRACE_OUTOFLINE = 0x07,
-
-    // The following kinds do not have an exposed C++ idiom.
-    JSTRACE_BASE_SHAPE = 0x0F,
-    JSTRACE_JITCODE = 0x1F,
-    JSTRACE_LAZY_SCRIPT = 0x2F,
-    JSTRACE_TYPE_OBJECT = 0x3F,
-
-    JSTRACE_LAST = JSTRACE_TYPE_OBJECT
-};
-
- -

Description

- -

See {{ Bug(378261) }} for detail.

- -

When tracing a thing, the GC needs to know about the layout of the object it is looking at. There are a fixed number of different layouts that the GC knows about. The "trace kind" is a static map which tells which layout a GC thing has.

- -

Although this map is public, the details are completely hidden. Not all of the matching C++ types are exposed, and those that are, are opaque.

- -

See {{jsapixref("JS::Value", "JS::Value::gcKind()")}} and {{jsapixref("JSTraceCallback")}} in <codde>Tracer.h</codde> for more details.

- -

See Also

- - diff --git a/files/ja/mozilla/projects/spidermonkey/jsapi_reference/js_evaluatescript/index.html b/files/ja/mozilla/projects/spidermonkey/jsapi_reference/js_evaluatescript/index.html deleted file mode 100644 index a58d781ab4..0000000000 --- a/files/ja/mozilla/projects/spidermonkey/jsapi_reference/js_evaluatescript/index.html +++ /dev/null @@ -1,93 +0,0 @@ ---- -title: JS EvaluateScript -slug: Mozilla/Projects/SpiderMonkey/JSAPI_reference/JS_EvaluateScript -tags: - - JSAPI Reference - - SpiderMonkey -translation_of: Mozilla/Projects/SpiderMonkey/JSAPI_reference/JS_EvaluateScript ---- -

- -

- - -

- -

スクリプトのコンパイルおよび実行を行います。 Compile and execute a script.

- -

構文

- -
JSBool JS_EvaluateScript(JSContext *cx, JSObject *obj,
-    const char *src, uintN length, const char *filename,
-    uintN lineno, jsval *rval);
-
-JSBool JS_EvaluateUCScript(JSContext *cx, JSObject *obj,
-    const jschar *src, uintN length, const char *filename,
-    uintN lineno, jsval *rval);
-
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameTypeDescription
cxJSContext *スクリプトを実行するコンテキストThe context in which to run the script. {{ Jsapi-requires-request() }}
objJSObject *スクリプトと関連付けるオブジェクトObject with which the script is associated.
srcconst char *or const jschar *コンパイル・実行対象となるスクリプト文字列String containing the script to compile and execute.
lengthsize_tsrcの文字列長The length of <code>src</code>, in characters.
filenameconst char *エラーメッセージ出力に利用されるスクリプトのファイル名またはそのURLを示す文字列。Name of file or URL containing the script. Used to report filename or URL in error messages.
linenouintNエラー発生時に出力される行数Line number. Used to report the offending line in the file or URL if an error occurs.
rvaljsval *実行結果の出力先。実行に成功したとき、*rvalにはスクリプトの最終行の実行結果の値が格納されます。Out parameter. On success, <code>*rval</code> receives the value of the last-executed expression statement processed in the script.
- -

説明

- -

JS_EvaluateScriptは、オブジェクトobjに結合する形でスクリプトをコンパイル・実行する関数です。実行が成功したとき、rvalにスクリプトの最終行の実行結果の値へのポインタが格納されています。この関数のUnicode版として、JS_EvaluateUCScriptが用意されています。 <code>JS_EvaluateScript</code> compiles and executes a script associated with a JS object, <code>obj</code>. On successful completion, <code>rval</code> is a pointer to a variable that holds the value from the last executed expression statement processed in the script. <code>JS_EvaluateUCScript</code> is the Unicode version of the function.

- -

srcはスクリプト文字列、lengthはその文字列の長さをそれぞれ引数として取ります。 <code>src</code> is the string containing the text of the script. <code>length</code> indicates the size of the text version of the script in characters.

- -

filenameはスクリプトの位置を示すファイル名またはURLを引数として取ります。ここで指定した情報は、コンパイルエラーが発生したときのエラーメッセージに利用されます。linenoも同様にエラーメッセージとして出力される行番号として利用されます。 <code>filename</code> is the name of the file (or URL) containing the script. This information is used in messages if an error occurs during compilation. Similarly, <code>lineno</code> is used to report the line number of the script or file where an error occurred during compilation.

- -

スクリプトのコンパイルと実行が成功したとき、JS_EvaluateScriptおよびJS_EvaluateUCScriptJS_TRUEを、失敗したときはJS_FALSEをそれぞれ返します。コンパイル・実行に失敗したとき、*rvalの値は未定義とみなす必要があります。 If a script compiles and executes successfully, <code>JS_EvaluateScript</code> or <code>JS_EvaluateUCScript</code> returns <code>JS_TRUE</code>. Otherwise it returns <code>JS_FALSE</code>. On failure, your application should assume that <code>*rval</code> is undefined.

- -

関連項目

- -

{{ LXRSearch("ident", "i", "JS_EvaluateScript") }}
- {{ LXRSearch("ident", "i", "JS_EvaluateUCScript") }}

- -

JS_CompileFile, JS_CompileScript, JS_DecompileScript, JS_DestroyScript, JS_EvaluateScriptForPrincipals, JS_ExecuteScript

- -

{{ languages( { "en": "en/JS_EvaluateScript" } ) }}

diff --git a/files/ja/mozilla/projects/spidermonkey/jsapi_reference/js_getgcparameter/index.html b/files/ja/mozilla/projects/spidermonkey/jsapi_reference/js_getgcparameter/index.html deleted file mode 100644 index 1bfa969e7c..0000000000 --- a/files/ja/mozilla/projects/spidermonkey/jsapi_reference/js_getgcparameter/index.html +++ /dev/null @@ -1,323 +0,0 @@ ---- -title: JS_GetGCParameter -slug: Mozilla/Projects/SpiderMonkey/JSAPI_reference/JS_GetGCParameter -tags: - - JSAPI Reference - - SpiderMonkey -translation_of: Mozilla/Projects/SpiderMonkey/JSAPI_reference/JS_GetGCParameter ---- -
{{SpiderMonkeySidebar("JSAPI")}}
- -
-

ガベージコレクションに関連するパフォーマンスパラメータを調整します。

-
- -

構文

- -
uint32_t
-JS_GetGCParameter(JSRuntime *rt, JSGCParamKey key);
-
-void
-JS_SetGCParameter(JSRuntime *rt, JSGCParamKey key, uint32_t value);
-
-uint32_t
-JS_GetGCParameterForThread(JSContext *cx, JSGCParamKey key); // Added in SpiderMonkeySidebar 17
-
-void
-JS_SetGCParameterForThread(JSContext *cx, JSGCParamKey key, uint32_t value); // Added in SpiderMonkeySidebar 17
-
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameTypeDescription
rt{{jsapixref("JSRuntime", "JSRuntime *")}}The runtime to configure.
cx{{jsapixref("JSRuntime", "JSContext *")}}The context to configure. {{ Jsapi-requires-request() }}
keyJSGCParamKeySpecifies which garbage collection parameter to get or set.
valueuint32_t(JS_SetGCParameter only) The value to assign to the parameter.
- -
typedef enum JSGCParamKey {
-    JSGC_MAX_BYTES,
-    JSGC_MAX_MALLOC_BYTES,
-    JSGC_MAX_NURSERY_BYTES,
-    JSGC_BYTES,
-    JSGC_NUMBER,
-    JSGC_MODE,
-    JSGC_UNUSED_CHUNKS,
-    JSGC_TOTAL_CHUNKS,
-    JSGC_SLICE_TIME_BUDGET,
-    JSGC_MARK_STACK_LIMIT,
-    JSGC_HIGH_FREQUENCY_TIME_LIMIT,
-    JSGC_HIGH_FREQUENCY_LOW_LIMIT,
-    JSGC_HIGH_FREQUENCY_HIGH_LIMIT,
-    JSGC_HIGH_FREQUENCY_HEAP_GROWTH_MAX,
-    JSGC_HIGH_FREQUENCY_HEAP_GROWTH_MIN,
-    JSGC_LOW_FREQUENCY_HEAP_GROWTH,
-    JSGC_DYNAMIC_HEAP_GROWTH,
-    JSGC_DYNAMIC_MARK_SLICE,
-    JSGC_ALLOCATION_THRESHOLD,
-    JSGC_MIN_EMPTY_CHUNK_COUNT,
-    JSGC_MAX_EMPTY_CHUNK_COUNT,
-    JSGC_COMPACTION_ENABLED,
-    JSGC_ALLOCATION_THRESHOLD_FACTOR,
-    JSGC_ALLOCATION_THRESHOLD_FACTOR_AVOID_INTERRUPT,
-    JSGC_NURSERY_FREE_THRESHOLD_FOR_IDLE_COLLECTION,
-    JSGC_PRETENURE_THRESHOLD,
-    JSGC_PRETENURE_GROUP_THRESHOLD,
-    JSGC_NURSERY_FREE_THRESHOLD_FOR_IDLE_COLLECTION_PERCENT,
-    JSGC_MIN_NURSERY_BYTES,
-    JSGC_MIN_LAST_DITCH_GC_PERIOD,
-} JSGCParamKey;
-
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Value (C++/JS Shell)Description
JSGC_MAX_BYTES / "maxBytes"Maximum nominal heap before last ditch GC.
JSGC_MAX_MALLOC_BYTES / "maxMallocBytes"Number of JS_malloc bytes before last ditch GC.
JSGC_MAX_NURSERY_BYTES / "maxNurseryBytes"Maximum size the nursery may grow to, or 0 to disable generational GC.
JSGC_MIN_NURSERY_BYTES / "minNurseryBytes"Minimum size the nursery may shrink to.
JSGC_BYTES / "gcBytes"Amount of bytes allocated by the GC.
JSGC_NUMBER / "gcNumber"Number of times GC has been invoked. Includes both major and minor GC.
JSGC_MODE / "mode" -

Select GC mode:

- -
-
JSGC_MODE_GLOBAL (0)
-
The GC runs all objects are visited in a singleslice.
-
JSGC_MODE_ZONE (1)
-
The GC runs only the objects that belong to somezones are visited in a singleslice.
-
JSGC_MODE_INCREMENTAL (2)
-
The GC runs all objects are visited in multipleslices.
-
JSGC_MODE_ZONE_INCREMENTAL (3)
-
The GC runs only the objects that belong to somezones are visited in multipleslices.
-
- -

This does not affect generational GC, see JSGC_MAX_NURSERY_BYTES

-
JSGC_UNUSED_CHUNKS / "unusedChunks"Number of cached empty GC chunks.
JSGC_TOTAL_CHUNKS / "totalChunks"Total number of allocated GC chunks.
JSGC_SLICE_TIME_BUDGET / "sliceTimeBudget"Max milliseconds to spend in an incremental GC slice. 0 for infinite.
JSGC_MARK_STACK_LIMIT / "markStackLimit"Maximum size the GC mark stack can grow to (units: entries).
JSGC_HIGH_FREQUENCY_TIME_LIMIT / "highFrequencyTimeLimit"GCs less than this far apart in time will be considered 'high-frequency GCs'.
JSGC_HIGH_FREQUENCY_LOW_LIMIT / "highFrequencyLowLimit" -

Controls for dynamic heap growth. When the GC is in "high frequency" mode (see above) then, the heap will be allowed to grow between collections according to these four parameters. See ZoneHeapThreshold::computeZoneHeapGrowthFactorForHeapSize in GC.cpp for the details.

- -

The first two parameters are in MB and the remaining two are in percentage of heap size.

-
JSGC_HIGH_FREQUENCY_HIGH_LIMIT / "highFrequencyHighLimit"
JSGC_HIGH_FREQUENCY_HEAP_GROWTH_MAX / "highFrequencyHeapGrowthMax"
JSGC_HIGH_FREQUENCY_HEAP_GROWTH_MIN / "highFrequencyHeapGrowthMin"
JSGC_LOW_FREQUENCY_HEAP_GROWTH / "lowFrequencyHeapGrowth"Heap growth percentage for low frequency GCs.
JSGC_DYNAMIC_HEAP_GROWTH / "dynamicHeapGrowth"If false, the heap growth percentage is fixed at 300%. If true, it is determined based on whether GCs are high- or low- frequency.
JSGC_DYNAMIC_MARK_SLICE / "dynamicMarkSlice"If true, high-frequency GCs will use a longer mark slice.
JSGC_ALLOCATION_THRESHOLD / "allocationThreshold"Lower limit after which we limit the heap growth. The heap will be collected if it is greater than: MAX(allocThreshold, lastSize) * thresholdFactor, This establishes allocThreshold as a baseline or default heap size.
JSGC_ALLOCATION_THRESHOLD_FACTOR / "allocationThresholdFactor" -

These thresholds (as percentages) are compared with the zone threshold (above) to decide when to begin an incremental collection. JSGC_ALLOCATION_THRESHOLD_FACTOR_AVOID_INTERRUPT is used when a GC is already in progress for other zones and we may wish to avoid interrupting it.

- -

Additionally if a zone expands beyond the threshold without this factor, then it will be collected non-incrementally

-
JSGC_ALLOCATION_THRESHOLD_FACTOR_AVOID_INTERRUPT / "allocationThresholdfactorAvoidInterrupt"
JSGC_MIN_EMPTY_CHUNK_COUNT / "minEmptyChunkCount"We try to keep at least this many unused chunks in the free chunk pool at all times, even after a shrinking GC.
JSGC_MAX_EMPTY_CHUNK_COUNT / "maxEmptyChunkCount"We never keep more than this many unused chunks in the free chunk pool.
JSGC_COMPACTION_ENABLED / "compactingEnabled"non-zero to enable compacting, zero to disable.
JSGC_NURSERY_FREE_THRESHOLD_FOR_IDLE_COLLECTION / "nurseryFreeThresholdForIdleCollection"Collect the nursery in idle time if it has less than this many bytes of free space.
JSGC_NURSERY_FREE_THRESHOLD_FOR_IDLE_COLLECTION_PERCENT / "nurseryFreeThresholdForIdleCollectionPercent"Collect the nursery in idle time if it has less than this percentage of capacity free (value from 0 - 99).
JSGC_PRETENURE_THRESHOLD / "pretenureThreshold"If this percentage of the nursery is tenured and the nursery is at least 4MB, then process object groups to look for pretenuring candidates.
JSGC_PRETENURE_GROUP_THRESHOLD / "pretenureGroupThreshold"If more than this number of objects in a given object group are tenured, then pretenruing will be enabled for new objects in this group.
JSGC_MIN_LAST_DITCH_GC_PERIOD / "minLastDitchGCPeriod"The minimum time to allow between triggering last ditch GCs in seconds.
- -

説明

- -

JS_GetGCParameter returns the current parameter of the garbage collection.

- -

If successful, JS_GetGCParameter returns the current parameter.

- -

JS_SetGCParameter ajusts the parameter of the garbage collection.

- -

あわせて参照

- - diff --git a/files/ja/mozilla/projects/spidermonkey/jsapi_reference/js_getruntime/index.html b/files/ja/mozilla/projects/spidermonkey/jsapi_reference/js_getruntime/index.html deleted file mode 100644 index 36a7593d57..0000000000 --- a/files/ja/mozilla/projects/spidermonkey/jsapi_reference/js_getruntime/index.html +++ /dev/null @@ -1,47 +0,0 @@ ---- -title: JS GetRuntime -slug: Mozilla/Projects/SpiderMonkey/JSAPI_reference/JS_GetRuntime -tags: - - JSAPI Reference - - SpiderMonkey -translation_of: Mozilla/Projects/SpiderMonkey/JSAPI_reference/JS_GetRuntime ---- -

- -

- - - -

- -

JSRuntimeへのポインタを取得します。 Retrieves a pointer to the <code>JSRuntime</code>.

- -

構文

- -
JSRuntime * JS_GetRuntime(JSContext *cx);
-
- - - - - - - - - - - - - - -
NameTypeDescription
cxJSContext *コンテキスト
- -

説明

- -

JS_GetRuntimeは、JSContext cxと関連付けられたJSRuntimeへのポインタを取得する関数です。各コンテキストは、その生成時に指定した (JS_NewContextを参照) JSRuntimeと関連付けられており、JS_GetRuntimeを使うことでその関連付けを取得することができます。 <code>JS_GetRuntime</code> retrieves a pointer to the <code>JSRuntime</code> with which a specified <code>JSContext</code>, <code>cx</code>, is associated. Each context is associated with a particular <code>JSRuntime</code> when it is created (see <code>JS_NewContext</code>); <code>JS_GetRuntime</code> provides a convenient, programmatic way to look up the association.

- -

{{ LXRSearch("ident", "i", "JS_GetRuntime") }}

- -

{{ languages( { "en": "en/JS_GetRuntime" } ) }}

diff --git a/files/ja/mozilla/projects/spidermonkey/jsapi_reference/js_getruntimeprivate/index.html b/files/ja/mozilla/projects/spidermonkey/jsapi_reference/js_getruntimeprivate/index.html deleted file mode 100644 index c4f3f7937b..0000000000 --- a/files/ja/mozilla/projects/spidermonkey/jsapi_reference/js_getruntimeprivate/index.html +++ /dev/null @@ -1,59 +0,0 @@ ---- -title: JS GetRuntimePrivate -slug: Mozilla/Projects/SpiderMonkey/JSAPI_reference/JS_GetRuntimePrivate -tags: - - JSAPI Reference - - SpiderMonkey -translation_of: Mozilla/Projects/SpiderMonkey/JSAPI_reference/JS_GetRuntimePrivate ---- -

- -

- - -

- -

JSRuntimeオブジェクトと関連付けられたアプリケーション固有のフィールドにアクセスします。 Access a <code>JSRuntime</code> field for application-specific data.

- -

構文

- -
void * JS_GetRuntimePrivate(JSRuntime *rt);
-
-void JS_SetRuntimePrivate(JSRuntime *rt, void *data);
-
- - - - - - - - - - - - - - - - - - - -
NameTypeDescription
rtJSRuntime *JavaScriptランタイム環境Any JS runtime.
datavoid *(JS_SetRuntimePrivateのみ)ランタイムrtと関連付けるアプリケーション固有のデータへのポインタ ''(in <code>JS_SetRuntimePrivate</code>)'' Pointer to application-defined data to be associated with the runtime <code>rt</code>.
- -

説明

- -

JSRuntime内には、アプリケーション内で用いる任意のデータを指し示すvoid *型のフィールドが存在します。このフィールドは、コールバック関数が容易にアクセスできる領域であるため、その中でのデータ格納に有用に使えます。JS_GetRuntimePrivateでフィールドの値を取得し、JS_SetRuntimePrivateで値を設定します。フィールドの初期値はNULLに設定されています。 Each <code>JSRuntime</code> has a field of type <code>void *</code> which the application may use for any purpose. It is especially useful for storing data which callbacks may then easily access. <code>JS_GetRuntimePrivate</code> gets the value of this field and <code>JS_SetRuntimePrivate</code> sets it. The field is initially <code>NULL</code>.

- -

このプライベートなデータのメモリ管理はアプリケーション側の責任になります。JavaScriptエンジン自体がこの領域を利用することはありません。 Memory management for this private data is the application's responsibility. The JavaScript engine itself never uses it.

- -

関連項目

- -

{{ LXRSearch("ident", "i", "JS_GetRuntimePrivate") }}

- -

JS_GetContextPrivate, JS_SetContextPrivate, JS_GetPrivate, JS_SetPrivate, JS_GetInstancePrivate

- -

{{ languages( { "en": "en/JS_GetRuntimePrivate" } ) }}

diff --git a/files/ja/mozilla/projects/spidermonkey/jsapi_reference/js_init/index.html b/files/ja/mozilla/projects/spidermonkey/jsapi_reference/js_init/index.html deleted file mode 100644 index 1d52ec7034..0000000000 --- a/files/ja/mozilla/projects/spidermonkey/jsapi_reference/js_init/index.html +++ /dev/null @@ -1,35 +0,0 @@ ---- -title: JS_Init -slug: Mozilla/Projects/SpiderMonkey/JSAPI_reference/JS_Init -translation_of: Mozilla/Projects/SpiderMonkey/JSAPI_reference/JS_Init ---- -
{{obsolete_header}}
- - -

構文

- - -
JSRuntime * JS_Init(uint32 maxbytes);
-
- - - - - - - - - - - - - - - - - -
名称説明
maxbytesuint32ガベージコレクション実行後に割り当てられたバイト数
- - -

説明

-

JS_Init は廃止されました。替わりに JS_NewRuntime を使用して下さい。

diff --git a/files/ja/mozilla/projects/spidermonkey/jsapi_reference/js_lock/index.html b/files/ja/mozilla/projects/spidermonkey/jsapi_reference/js_lock/index.html deleted file mode 100644 index 1ffb9dee10..0000000000 --- a/files/ja/mozilla/projects/spidermonkey/jsapi_reference/js_lock/index.html +++ /dev/null @@ -1,37 +0,0 @@ ---- -title: JS_Lock -slug: Mozilla/Projects/SpiderMonkey/JSAPI_reference/JS_Lock -tags: - - JSAPI_Reference - - SpiderMonkey -translation_of: Mozilla/Projects/SpiderMonkey/JSAPI_reference/JS_Lock ---- -
- {{obsolete_header("jsapi12")}}
-

JS ランタイム環境をロックします。

-

構文

-
void JS_Lock(JSRuntime *rt);
-
- - - - - - - - - - - - - - - -
名称説明
rtJSRuntime *ロックするランタイムへのポインタ
-

説明

-

JS_Lock は非推奨 API です。使用しないで下さい。

-

関連情報

- diff --git a/files/ja/mozilla/projects/spidermonkey/jsapi_reference/js_newcontext/index.html b/files/ja/mozilla/projects/spidermonkey/jsapi_reference/js_newcontext/index.html deleted file mode 100644 index ab77638f70..0000000000 --- a/files/ja/mozilla/projects/spidermonkey/jsapi_reference/js_newcontext/index.html +++ /dev/null @@ -1,93 +0,0 @@ ---- -title: JS NewContext -slug: Mozilla/Projects/SpiderMonkey/JSAPI_reference/JS_NewContext -tags: - - JSAPI Reference - - SpiderMonkey -translation_of: Mozilla/Projects/SpiderMonkey/JSAPI_reference/JS_NewContext ---- -

- -

- -

- -

新たなJavaScriptコンテキストを生成します。 Creates a new JavaScript context.

- -

構文

- -

= Syntax =

- -
JSContext * JS_NewContext(JSRuntime *rt, size_t stackchunksize);
-
- - - - - - - - - - - - - - - - - - - -
NameTypeDescription
rtJSRuntime *コンテキストの親となるランタイムを指定します。JavaScriptのオブジェクト、関数、文字列、数値はJSRuntime内のコンテキスト内で共有されますが、JSRuntimeをまたぐことはありません。 -

Parent runtime for the new context. JavaScript objects, functions, strings, and numbers may be shared among the contexts in a <code>JSRuntime</code>, but they cannot be shared across <code>JSRuntime</code>s.

-
stackchunksizesize_t -

各スタック領域のサイズをバイトで指定します。標準的には8192が適切な値であり、大抵の場合において調節すべきでないパラメータです。 The size, in bytes, of each "stack chunk". This is a memory management tuning parameter which most users should not adjust. <code>8192</code> is a good default value.

-
- -

説明

- -

= Description = スクリプトの実行および値の保持に利用するコンテキストを新規に生成する関数です。各スクリプトは独自のコンテキスト上で実行され、各コンテキストは特定のJSRuntimeオブジェクトrtと関連づけられています。 Creates a new JavaScript context for executing scripts and examining JavaScript values. Each script runs in its own context, and each context must be associated with a specified <code>JSRuntime</code>, <code>rt</code>.

- -

JS_NewContextは、成功したとき新たなコンテキストへのポインタを返します。失敗したときはNULLを返します。 On success, <code>JS_NewContext</code> returns a pointer to the new context. Otherwise it returns <code>NULL</code>.

- -

この関数の呼び元は、コンテキストを使い終わったらJS_DestroyContextを実行しなければなりません。JSRuntimeを解放する前に、そのJSContextをすべて解放する必要があります。 The caller must call <code>JS_DestroyContext</code> when it is done using the context. Before a <code>JSRuntime</code> may be destroyed, all the <code>JSContext</code>s associated with it must be destroyed.

- -

JS_THREADSAFEを有効にしたビルドでは、あるJSContextを同時にアクセスできるスレッドは一つだけです。新規のJSContextは、初期状態で呼び元のスレッドと関連付けられます。コンテキストがあるスレッドと関連付けられている間は、他のスレッドからそれを利用したり解放することはできません。JSContextを別のスレッドに移動する場合は、JS_ClearContextThreadJS_SetContextThreadを利用してください。 In a <code>JS_THREADSAFE</code> build, only one thread may use a <code>JSContext</code> at a time. The new <code>JSContext</code> is initially associated with the calling thread. As long as it stays associated with that thread, no other thread may use it or destroy it. A <code>JSContext</code> may be transferred from one thread to another by calling <code>JS_ClearContextThread</code> and <code>JS_SetContextThread</code>.

- -

新たに生成したJSContextは、初期状態においてグローバルオブジェクトを持ちません。 The new <code>JSContext</code> initially has no global object.

- -

注記

- -

== Notes == 一度生成されたコンテキストは異なるスクリプトやJSAPI呼び出しのために複数回利用される可能性があります。具体的には、Webブラウザが各HTMLに対応する独立したコンテキストを生成したときに、ページ内のすべてのスクリプトは同じコンテキストを用いて実行されるといったシナリオが考えられます。 Once created, a context can be used any number of times for different scripts or JSAPI queries. For example, a browser would create a separate context for each HTML page; every script in the page would use the same context.

- -

新規コンテキストは、ObjectDateArrayといった標準的なグローバルオブジェクトを一切保持していません。それらを利用するには、JS_InitStandardClassesを呼び出す必要があります。JSAPIを利用するアプリケーションで独自の関数やクラスを提供したい場合には、JS_GetGlobalObjectを使ってそのコンテキストのグローバルオブジェクトを取得し、JS_DefineFunctionsおよびJS_InitClassをそれに適用することで独自のグローバル関数やクラスをコンテキストに追加できます。 The new context initially does not contain any globals, even standard globals such as <code>Object</code>, <code>Date</code>, and <code>Array</code>. To create them, call <code>JS_InitStandardClasses</code>. A JSAPI application typically also provides some custom functions and classes. Use <code>JS_GetGlobalObject</code> to get a context's global object. Use <code></code> and <code>JS_InitClass</code> to add custom global functions and classes to the context.

- -

stackchunksizeは、JavaScriptのスタックサイズを調節するものではありません(JSAPIでは、スタック長を調節するインタフェースを提供していません)。stackchunksizeに大きい値を設定するのは誤った方法です。DEBUGビルドにおいて、stackchunksizeを大きくすると性能が著しく劣化します。一般的には8192が推奨されます。 The <code>stackchunksize</code> parameter does not control the JavaScript stack size. (The JSAPI does not provide a way to adjust the stack depth limit.) Passing a large number for <code>stackchunksize</code> is a mistake. In a <code>DEBUG</code> build, large chunk sizes can degrade performance dramatically. The usual value of <code>8192</code> is recommended.

- -

関連項目

- -

= See Also =

- - - - - - - - - - - - - - - - -
GroupsFunctions
Documents{{ LXRSearch("ident", "i", "JS_NewContext", "LXR ID Search") }}
EntriesJS_ContextIterator, -

JS_DestroyContext, JS_SetContextCallback

-
- -

{{ languages( { "en": "en/JS_NewContext" } ) }}

diff --git a/files/ja/mozilla/projects/spidermonkey/jsapi_reference/js_newobject/index.html b/files/ja/mozilla/projects/spidermonkey/jsapi_reference/js_newobject/index.html deleted file mode 100644 index 8efb4676c7..0000000000 --- a/files/ja/mozilla/projects/spidermonkey/jsapi_reference/js_newobject/index.html +++ /dev/null @@ -1,104 +0,0 @@ ---- -title: JS_NewObject -slug: Mozilla/Projects/SpiderMonkey/JSAPI_reference/JS_NewObject -tags: - - JSAPI Reference - - SpiderMonkey -translation_of: Mozilla/Projects/SpiderMonkey/JSAPI_reference/JS_NewObject ---- -

- -

- -

- -

{{ 英語版章題("Summary") }}

- -

概要

- -

オブジェクトのインスタンスを生成する関数です。Instantiates a new object.

- -

{{ 英語版章題("Syntax") }}

- -

構文

- -
JSObject * JS_NewObject(JSContext *cx, JSClass *clasp, JSObject *proto,
-    JSObject *parent);
-
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameTypeDescription
cxJSContext *ランタイム環境へのアクセスに用いる JSContext ポインタPointer to a JS context from which to derive runtime information.
claspJSClass *オブジェクト生成に用いるクラスへのポインタPointer to the class to use for the new object.
protoJSObject *クラスとして用いる prototype オブジェクトへのポインタPointer to the prototype object to use for the new class.
parentJSObject *新規オブジェクトの__parent__プロパティになる親オブジェクトへのポインタ。Pointer to which to set the new object's <code>__parent__</code> property.
- -

{{ 英語版章題("Description") }}

- -

説明

- -

JS_NewObjectは、引数に指定したクラス、プロトタイプ、親オブジェクトを元にしてオブジェクトのインスタンスを生成する関数です。cxは、新規オブジェクトを生成するランタイム環境の子となるコンテキストへのポインタです。claspは、finalizeのような内部で定義されたメソッドを使う既存クラスへのポインタです。protoは、新規に生成するオブジェクトのプロトタイプとなるオブジェクトへのポインタです。 <code>JS_NewObject</code> instantiates a new object based on a specified class, prototype, and parent object. <code>cx</code> is a pointer to a context associated with the runtime in which to establish the new object. <code>clasp</code> is a pointer to an existing class to use for internal methods, such as <code>finalize</code>. <code>proto</code> is an optional pointer to the prototype object with which to associate the new object.

- -

Set proto to NULL to force JS to assign a prototype object for you. In this case, JS_NewObject attempts to assign the new object the prototype object belonging to clasp, if one is defined there. Otherwise, it creates an empty object stub for the prototype.

- -

引数parentは、新たに生成したオブジェクトをプロパティとして持つ親オブジェクトを指定するものです。__parent__プロパティを設定したくない時は、parentNULLを指定してください。 <code>parent</code> is an optional pointer to an existing object to which to set the new object's parent object property. You can set parent to <code>NULL</code> if you do not want to set the <code>__parent__</code> property.

- -

JS_NewObjectが成功したとき、その返値は生成したオブジェクトのインスタンスへのポインタになり、失敗した時はNULLを返します。 On success, <code>JS_NewObject</code> returns a pointer to the newly instantiated object. Otherwise it returns <code>NULL</code>.

- -

{{ 英語版章題("Notes") }}

- -

注記

- -

既存オブジェクトのプロパティとなるオブジェクトを生成するには、JS_DefineObjectを用いてください。 To create a new object that is a property of an existing object, use <code>JS_DefineObject</code>.

- -

{{ 英語版章題("See Also") }}

- -

参照

- - - - - - - - - - - - - - - - -
GroupsFunctions
Documents{{ LXRSearch("ident", "i", "JS_NewObject", "LXR ID Search") }}
Entries -

JSClass, JS_ConstructObject, JS_DefineObject, JS_GetFunctionObject, JS_NewArrayObject, JS_ValueToObject

-
- -
 
- -

{{ languages( { "en": "en/JS_NewObject" } ) }}

diff --git a/files/ja/mozilla/projects/spidermonkey/jsapi_reference/js_newruntime/index.html b/files/ja/mozilla/projects/spidermonkey/jsapi_reference/js_newruntime/index.html deleted file mode 100644 index 5db8397cb9..0000000000 --- a/files/ja/mozilla/projects/spidermonkey/jsapi_reference/js_newruntime/index.html +++ /dev/null @@ -1,52 +0,0 @@ ---- -title: JS NewRuntime -slug: Mozilla/Projects/SpiderMonkey/JSAPI_reference/JS_NewRuntime -tags: - - JSAPI Reference - - SpiderMonkey -translation_of: Mozilla/Projects/SpiderMonkey/JSAPI_reference/JS_NewRuntime ---- -

-

- -

JavaScript ランタイムの初期化を行います。 {{ 英語版章題("Syntax") }}

- -

構文

- -
JSRuntime * JS_NewRuntime(uint32 maxbytes);
-
- - - - - - - - - - - - - - -
NameTypeDescription
maxbytesuint32ガベージコレクション動作後の最大メモリ使用量Maximum number of allocated bytes after which garbage collection is run.
- -

{{ 英語版章題("Description") }}

- -

説明

- -

JS_NewRuntimeは、JavaScriptランタイム環境の初期化を行う関数です。他のJSAPI関数を使うには前もって必ずJS_NewRuntimeを呼ぶことになります。JS_NewRuntimeは、JSRuntimeに用いるメモリ領域を確保し、ランタイム内の初期化を行います。引数maxbytesで、ガベージコレクションが動作した後の最大メモリ使用量を指定します。 <code>JS_NewRuntime</code> initializes the JavaScript runtime environment. Call <code>JS_NewRuntime</code> before making any other API calls. <code>JS_NewRuntime</code> allocates memory for the <code>JSRuntime</code> and initializes certain internal runtime structures. <code>maxbytes</code> specifies the number of allocated bytes after which garbage collection is run.

- -

一般的に、ほとんどのアプリケーションで必要とされるJSRuntimeは一つのみです。JS_THREADSAFEを有効にしたビルドでは、JSRuntimeを共有するJSContextを各スレッドごとに一つ用意することで、複数スレッドからランタイムにアクセスすることが可能です。複数のランタイムが必要になるのは、JavaScriptの値やオブジェクト、関数をスレッド間で完全に分離させたいときだけです。 Generally speaking, most applications need only one <code>JSRuntime</code>. In a <code>JS_THREADSAFE</code> build, each runtime is capable of handling multiple execution threads, using one <code>JSContext</code> per thread, sharing the same <code>JSRuntime</code>. You only need multiple runtimes if your application requires completely separate JS engines that cannot share values, objects, and functions.

- -

JS_NewRuntimeが成功したときは、新たに生成されたランタイムへのポインタがその返り値となり、失敗した時はNULLを返します。JS_NewRuntimeの呼び出し元は、後で必ずそのランタイムをJS_DestroyRuntimeを用いて破棄しなければなりません。 On success, <code>JS_NewRuntime</code> returns a pointer to the newly created runtime, which the caller must later destroy using <code>JS_DestroyRuntime</code>. Otherwise it returns <code>NULL</code>. {{ 英語版章題("Notes") }}

- -

注記

- -

一般的には、JS_NewRuntimeはアプリケーション内でまず最初に実行し、JS_DestroyRuntimeJS_ShutDownを終了時に呼ぶことになります。 Ordinarily, <code>JS_NewRuntime</code> should be the first JSAPI call in an application, and <code>JS_DestroyRuntime</code> and <code>JS_ShutDown</code> should be the last ones.

- -

{{ LXRSearch("ident", "i", "JS_NewRuntime") }}

- -

{{ languages( { "en": "en/JS_NewRuntime" } ) }}

diff --git a/files/ja/mozilla/projects/spidermonkey/jsapi_reference/js_setgczeal/index.html b/files/ja/mozilla/projects/spidermonkey/jsapi_reference/js_setgczeal/index.html deleted file mode 100644 index 0be58ee8dc..0000000000 --- a/files/ja/mozilla/projects/spidermonkey/jsapi_reference/js_setgczeal/index.html +++ /dev/null @@ -1,141 +0,0 @@ ---- -title: JS_SetGCZeal -slug: Mozilla/Projects/SpiderMonkey/JSAPI_reference/JS_SetGCZeal -tags: - - JSAPI Reference - - SpiderMonkey -translation_of: Mozilla/Projects/SpiderMonkey/JSAPI_reference/JS_SetGCZeal ---- -
{{SpiderMonkeySidebar("JSAPI")}}
- -
{{jsapi_minversion_header("1.8")}}
- -
-

GC の活動量、JSAPI アプリケーションの GC 関連のバグを見つけるのに役立つテストおよびデバッグ機能を有効にします。

-
- -

構文

- -
void
-JS_SetGCZeal(JSContext *cx, uint8_t zeal, uint32_t frequency);
-
- - - - - - - - - - - - - - - - - - - - - - - - -
NameTypeDescription
cx{{jsapixref("JSRuntime", "JSContext *")}}A context. The GC zeal level of the associated {{jsapixref("JSRuntime")}} is set.
zealuint8_tThe desired level of garbage collection.
frequencyuint32_tWith some zeal levels, a GC is triggered every frequency allocations.
- -

説明

- -

JS_SetGCZeal sets the level of additional garbage collection to perform for a runtime, for the purpose of finding or reproducing bugs.

- -

There are several different levels which have different functions:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Zeal levelDescription
0Normal amount of collection.  The default: no additional collections are performed.
1Collect when roots are added or removed.
2Collect when every frequency allocations.
3Collect on window paints.
4Verify pre write barriers between instructions.
5Verify pre write barriers between window paints.
6Verify stack rooting.
7Collect the nursery every frequency nursery allocations.
8Incremental GC in two slices: 1) mark roots 2) finish collection.
9Incremental GC in two slices: 1) mark all 2) new marking and finish.
10Incremental GC in multiple slices.
11Verify post write barriers between instructions.
12Verify post write barriers between paints.
13Check internal hashtables on minor GC.
14Perform a shrinking collection every frequency allocations.
- -

With GC zeal enabled, GC-related crashes are much easier to reproduce (they happen more reliably) and debug (they happen sooner, closer to the source of the bug). The drawback is that GC zeal can cause JavaScript code to run extremely slowly.

- -

Regularly running your test suite with GC zeal enabled at level 2 is a good practice.

- -

This function is available only in DEBUG builds. To enable this function in an optimized build, define the macro JS_GC_ZEAL building SpiderMonkey.

- -

(In a debug build of Gecko, you can also set the current GC zeal level using the javascript.options.gczeal preference.)

- -

あわせて参照

- - diff --git a/files/ja/mozilla/projects/spidermonkey/jsapi_reference/js_shutdown/index.html b/files/ja/mozilla/projects/spidermonkey/jsapi_reference/js_shutdown/index.html deleted file mode 100644 index 5d4e2faacd..0000000000 --- a/files/ja/mozilla/projects/spidermonkey/jsapi_reference/js_shutdown/index.html +++ /dev/null @@ -1,34 +0,0 @@ ---- -title: JS ShutDown -slug: Mozilla/Projects/SpiderMonkey/JSAPI_reference/JS_ShutDown -tags: - - JSAPI Reference - - SpiderMonkey -translation_of: Mozilla/Projects/SpiderMonkey/JSAPI_reference/JS_ShutDown ---- -

- -

- -

- -

ランタイム間で共有している資源を解放します。

- -

Free all resources shared among runtimes.

- -

構文

- -
void JS_ShutDown(void);
-
- -

説明

- -

ランタイム間で共有している資源を解放する関数です。この関数を呼ぶのはJSRuntimeオブジェクトが存在しないとき(具体的には、JS_DestroyRuntimeを読んだ後のプログラムの最後など)だけにしてください。 Frees all resources shared among runtimes. Call this only when no <code>JSRuntime</code>s exist (for example, at the end of the program, after calling <code>JS_DestroyRuntime</code>).

- -

利用時の注意点: この関数はjsdtoa.cが確保するメモリ領域と、JS_THREADSAFEオプションを有効にしたビルドにおけるjslock.cが確保するmutex領域を解放します。 Implementation note: This cleans up memory allocated by <code>jsdtoa.c</code> and, in <code>JS_THREADSAFE</code> builds, mutexes allocated by <code>jslock.c</code>.

- -

{{ LXRSearch("ident", "i", "JS_ShutDown") }}

- -

{{ languages( { "en": "en/JS_ShutDown" } ) }}

diff --git a/files/ja/mozilla/projects/spidermonkey/jsapi_reference/js_threadsafe/index.html b/files/ja/mozilla/projects/spidermonkey/jsapi_reference/js_threadsafe/index.html deleted file mode 100644 index b827d4c832..0000000000 --- a/files/ja/mozilla/projects/spidermonkey/jsapi_reference/js_threadsafe/index.html +++ /dev/null @@ -1,114 +0,0 @@ ---- -title: JS_THREADSAFE -slug: Mozilla/Projects/SpiderMonkey/JSAPI_reference/JS_THREADSAFE -translation_of: Mozilla/Projects/SpiderMonkey/JSAPI_reference/JS_THREADSAFE ---- -

{{ note("JS_THREADSAFE は現在恒久的に有効です。") }}

- -

JS_THREADSAFE は、オブジェクトや文字列が共有されていない限り、JavaScript コードの複数のスレッドを同時に実行するためのサポートを可能にするコンパイル時オプションです。

- -

最近この機能に大きな変更を加えました。最近まで、スレッド間でオブジェクトを共有することでうまくいくことが多かったのですが、スクリプトを使うとクラッシュすることがありました。この機能は完全に削除されました。JavaScript エンジンを使用する各スレッドは、本質的にまったく別のメモリ領域で動作する必要があります。

- -

Requests

- -

In a JS_THREADSAFE build, the application must separate code that uses the JSAPI from code that performs blocking I/O or time-consuming calculations.

- -

A request is a region of code that uses the JSAPI. Requests must be bracketed with calls to JS_BeginRequest() and JS_EndRequest().

- -
JS_BeginRequest(cx);
-/* ... do JSAPI stuff ... */
-JS_EndRequest(cx);
-
- -

A request is always associated with a specific JSContext and runs from start to finish on a single thread.

- -

Most JSAPI functions require the caller to be in a request. In this reference, these JSAPI functions are marked with the words "Requires request", like this:

- - - - - - - - - - - - - - -
NameTypeDescription
cxJSContext *The context to use. {{ Jsapi-requires-request() }}
- -

Most JSAPI callback functions are always called from within a request. These callbacks are (unreliably!) documented with the words "Provides request", like this:

- - - - - - - - - - - - - - -
NameTypeDescription
cxJSContext *The context in which the event ocurred. Provides request. In JS_THREADSAFE builds, the JavaScript engine calls this callback only from within an active request on cx. The callback does not need to call JS_BeginRequest()).
- -

In particular, JSNative callbacks provide a request. This means that any potentially long-running operation in a native must be bracketed with calls to JS_SuspendRequest() and JS_ResumeRequest().

- -
JSBool socket_recv(JSContext *cx, unsigned int argc, jsval *vp)
-{
-    ...
-    rc = JS_SuspendRequest(cx);
-    read_size = recv(socket, buf, size, flags);
-    JS_ResumeRequest(cx, rc);
-    ...
-}
-
- -

Garbage collection

- -

Requests help make garbage collection safe when multiple threads are using the JSAPI. For each thread that is in a request:

- - - -

These are actually the same rules that apply to single-threaded JSAPI programs. But in multithreaded programs, if you break the rules, your program is more likely to crash. This is because in single-threaded programs, a random call into the JSAPI is actually pretty unlikely to trigger GC, especially if the calling thread has not been using up a lot of memory. In a multithreaded program, even if the calling thread has been idle, other threads may be active or may call JS_GC().

- -

The above rules mean that at any given moment, there can be either (a) multiple threads in active requests, or (b) one thread doing GC and all requests suspended. When one thread calls JS_GC or otherwise finds that garbage collection is necessary, it must wait for all other threads that are in requests to pause before garbage collection can occur. To keep this wait time to a minimum, applications must avoid long-running requests. The recommended technique in SpiderMonkey 1.8 and later is to periodically call JS_YieldRequest from an operation callback.

- -

Sharing data among threads

- -

"Data can be marshaled across the process boundary through a process known as smuggling." --Mr. Bunny's Guide to ActiveX

- -

Even in JS_THREADSAFE builds, threads cannot safely share objects or strings.

- -

Instead, data must be copied when it is sent from one thread to another. Use JS_WriteStructuredClone to transform data into a flat array of bytes that can be safely written to disk, sent to another process or even another machine, or just passed to another thread. Then use JS_ReadStructuredClone on the other side to turn the serialized data back into JavaScript objects, strings, and so on.

- -

Sharing native functions and private data among threads

- -

In a JS_THREADSAFE build, SpiderMonkey's internal data structures that represent JavaScript values are single-thread-only. In a DEBUG build, this is enforced with assertions.

- -

However, SpiderMonkey does not protect the application's data structures. JSNatives and other callback functions can be called concurrently by multiple threads. Multiple threads can end up accessing private data or C/C++ global variables at the same time. It is up to the application to practice safe threading.

- -

Sharing contexts among threads

- -

Ordinarily, a JSContext is created, used, and destroyed by a single thread. This makes sense, as a context can only be used by one thread at a time. However, there are a few cases where an application might need to share contexts across threads. For example:

- - - - - -

For such cases, use JS_ClearContextThread and JS_SetContextThread to transfer the context safely from one thread to another.

- -

Further info

- -

Note: SpiderMonkey Internals: Thread Safety is mostly obsolete.

diff --git a/files/ja/mozilla/projects/spidermonkey/jsapi_reference/jsint/index.html b/files/ja/mozilla/projects/spidermonkey/jsapi_reference/jsint/index.html deleted file mode 100644 index c5028558cc..0000000000 --- a/files/ja/mozilla/projects/spidermonkey/jsapi_reference/jsint/index.html +++ /dev/null @@ -1,42 +0,0 @@ ---- -title: jsint -slug: Mozilla/Projects/SpiderMonkey/JSAPI_reference/jsint -tags: - - JSAPI_Reference - - SpiderMonkey -translation_of: Mozilla/Projects/SpiderMonkey/JSAPI_reference/jsint ---- -

C 言語 / C++ の整数型のエイリアスです。

- -

構文

- -
typedef ... jsint;
-typedef ... jsuint;
-
-typedef ... jsword;
-typedef ... jsuword;
-
-typedef ... intN;
-typedef ... uintN;
-
-typedef ... int8;
-typedef ... uint8;
-typedef ... int16;
-typedef ... uint16;
-typedef ... int32;
-typedef ... uint32;
-typedef ... int64;
-typedef ... uint64;
-
- - -

説明

- - -

jsint および jsuint は 32 ビットの整数型です。

- - -

jsword および jsuword はポインタサイズの整数型です。

- - -

intN および uintN はプラットフォームのネイティブの int 型と同じサイズの整数型です。

diff --git a/files/ja/mozilla/projects/spidermonkey/jsapi_reference/jsruntime/index.html b/files/ja/mozilla/projects/spidermonkey/jsapi_reference/jsruntime/index.html deleted file mode 100644 index b221ea62ef..0000000000 --- a/files/ja/mozilla/projects/spidermonkey/jsapi_reference/jsruntime/index.html +++ /dev/null @@ -1,23 +0,0 @@ ---- -title: JSRuntime -slug: Mozilla/Projects/SpiderMonkey/JSAPI_reference/JSRuntime -tags: - - JSAPI Reference - - SpiderMonkey -translation_of: Mozilla/Projects/SpiderMonkey/JSAPI_reference/JSRuntime ---- -

- -

- -

- -

JSAPIにおいて、JSRuntimeはメモリ管理やグローバルなデータ構造などを扱う最高位のオブジェクトです。複数のスレッドが動作するプログラムにおいても、プログラム内のJSRuntimeは一般的に一つだけです。JSRuntimeはJavaScriptのオブジェクトを保持する空間であり、オブジェクトは複数のJSRuntimeを跨いで移動することはできません。 JSAPI, <code>JSRuntime</code> is the top-level object that handles, among other things, memory management and "global" data structures. A program typically has only one <code>JSRuntime</code>, even if it has many threads. The <code>JSRuntime</code> is the universe in which JavaScript objects live; they can't travel to other <code>JSRuntime</code>s.

- -

JSContextJSRuntimeの子に位置し、すべてのJavaScriptコードとJSAPIの関数はJSContextを介して実行されます。JSContext内には、global objectや実行時スタックなどが含まれます。 例外処理エラー報告、一部のJavaScriptのオプション などは各JSContextごとに管理されます。JS_THREADSAFEオプションを有効にしたビルドでは、複数のスレッドからJavaScriptのコードを呼び出し並行して実行できますが、呼び出し元のスレッドはそれぞれ独立したJSContextを持つ形になります。詳細はJS_THREADSAFEを参照してください。 All JavaScript code and most JSAPI calls run within a <code>JSContext</code>. The <code>JSContext</code> is a child of the <code>JSRuntime</code>. Among other things, it contains the global object and the execution stack. Exception handling, error reporting, and some language options are per-<code>JSContext</code>. In a <code>JS_THREADSAFE</code> build, multiple threads may run JavaScript code concurrently, but each such thread must have its own <code>JSContext</code>. See <code> JS_THREADSAFE</code> for details.

- -

JavaScriptオブジェクトとそのコンテキストとの関係は固定されたものでなく、オブジェクトはJSRuntimeを介してその子となるJSContext間で共有することができます。 Objects may be shared among <code>JSContext</code>s within a <code>JSRuntime</code>. There's no fixed association between an object and a context.

- -

{{ languages( { "en": "en/JSRuntime" } ) }}

diff --git a/files/ja/mozilla/projects/spidermonkey/jsapi_reference/jstype/index.html b/files/ja/mozilla/projects/spidermonkey/jsapi_reference/jstype/index.html deleted file mode 100644 index 69037c39ee..0000000000 --- a/files/ja/mozilla/projects/spidermonkey/jsapi_reference/jstype/index.html +++ /dev/null @@ -1,52 +0,0 @@ ---- -title: JSType -slug: Mozilla/Projects/SpiderMonkey/JSAPI_reference/JSType -tags: - - JSAPI_Reference - - SpiderMonkey -translation_of: Mozilla/Projects/SpiderMonkey/JSAPI_reference/JSType ---- -

列挙型 JSType の値は、 JavaScript の値の型を表します。

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
説明
JSTYPE_VOIDundefined
JSTYPE_OBJECTJavaScript オブジェクト
JSTYPE_FUNCTION関数
JSTYPE_STRING文字列
JSTYPE_NUMBER数値
JSTYPE_BOOLEAN真偽値 (true / false)
JSTYPE_NULLnull
JSTYPE_XMLXML オブジェクト
-

 

diff --git a/files/ja/mozilla/projects/spidermonkey/jsapi_user_guide/index.html b/files/ja/mozilla/projects/spidermonkey/jsapi_user_guide/index.html deleted file mode 100644 index 815bdfd6cf..0000000000 --- a/files/ja/mozilla/projects/spidermonkey/jsapi_user_guide/index.html +++ /dev/null @@ -1,6 +0,0 @@ ---- -title: JSAPI ユーザガイド -slug: Mozilla/Projects/SpiderMonkey/JSAPI_User_Guide -translation_of: Mozilla/Projects/SpiderMonkey/JSAPI_User_Guide ---- -

{{SpiderMonkeySidebar}}{{Draft}}{{Page("/en-US/docs/Mozilla/Projects/SpiderMonkey/JSAPI_User_Guide")}}

diff --git a/files/ja/mozilla/projects/spidermonkey/jsdbgapi_reference/index.html b/files/ja/mozilla/projects/spidermonkey/jsdbgapi_reference/index.html deleted file mode 100644 index c132f23a19..0000000000 --- a/files/ja/mozilla/projects/spidermonkey/jsdbgapi_reference/index.html +++ /dev/null @@ -1,150 +0,0 @@ ---- -title: JSDBGAPI Reference -slug: Mozilla/Projects/SpiderMonkey/JSDBGAPI_Reference -tags: - - JSDBGAPI_Reference - - JavaScript - - SpiderMonkey ---- -

-

見てのとおり、ほとんどすべての項目がドキュメント化されていません。 -

<tt>trap, untrap, watch, unwatch, line2pc</tt> および <tt>pc2line</tt> 関数の実装は {{ Source("js/src/js.c") }} をご覧ください。{{ Source("js/src/jsdbgapi.h") }} にも (わずかに) コメントがあります。 -

{{ 英語版章題("Breakpoints") }} -

-

ブレークポイント

- -

{{ 英語版章題("Watchpoints") }} -

-

ウォッチポイント

- -

{{ 英語版章題("Inspecting the stack") }} -

-

スタックの調査

- - - - - -

{{ 英語版章題("Evaluating debug code") }} -

-

デバッグコードの評価

- -

{{ 英語版章題("Examining object properties") }} -

-

オブジェクトプロパティの検査

- - - - -

{{ 英語版章題("Hooks") }} -

-

フック

- - -

{{ 英語版章題("Memory usage") }} -

-

メモリ使用量

- -

{{ 英語版章題("System objects") }} -

-

システムオブジェクト

- -

{{ 英語版章題("Profiling") }} -

-

分析

-

これらの関数は、Mac プロファイラである Shark を使用して SpiderMonkey アプリケーションを分析するために使用されます。Profiling JavaScript with Shark をご覧ください。 -

- -

以下の JSNative 関数は、上記 4 つの API をスクリプトに晒すために使用されます。 -

- -{{ languages( { "en": "en/JSDBGAPI_Reference" } ) }} diff --git a/files/ja/mozilla/projects/spidermonkey/parser_api/index.html b/files/ja/mozilla/projects/spidermonkey/parser_api/index.html deleted file mode 100644 index 81b308c6f6..0000000000 --- a/files/ja/mozilla/projects/spidermonkey/parser_api/index.html +++ /dev/null @@ -1,1698 +0,0 @@ ---- -title: Parser API -slug: Mozilla/Projects/SpiderMonkey/Parser_API -tags: - - API - - Guide - - JavaScript - - SpiderMonkey -translation_of: Mozilla/Projects/SpiderMonkey/Parser_API ---- -
{{SpiderMonkeySidebar}}
- -
-

最近のスタンドアロンの SpiderMonkey シェルのビルドには、SpiderMonkey パーサーを反映したものが含まれています。これは JavaScript API として提供されています。これにより、シンタックスハイライト、静的解析、トランスレータ、コンパイラ、難読化ツールなど、JavaScript ソースプログラムを操作するツールを JavaScript で記述することが簡単になります。

-
- -
-

メモ: このページは SpiderMonkey 特有の振る舞いについて説明しており、不完全かもしれません。最新の ECMAScript 機能を含み、SpiderMonkey フォーマットとの下位互換性があるコミュニティ AST 規格については、ESTree の仕様をご覧ください。

-
- -

例:

- -
> var expr = Reflect.parse("obj.foo + 42").body[0].expression
-> expr.left.property
-({loc:null, type:"Identifier", name:"foo"})
-> expr.right
-({loc:{source:null, start:{line:1, column:10}, end:{line:1, column:12}}, type:"Literal", value:42})
-
- -

Firefox 7 以降も利用可能です。次のようにしてグローバルオブジェクトにインポートすることができます。

- -
Components.utils.import("resource://gre/modules/reflect.jsm")
-
- -

または指定されたオブジェクトへ:

- -
Components.utils.import("resource://gre/modules/reflect.jsm", obj)
-
- -

組み込みオブジェクト

- -

SpiderMonkey シェルであっても Firefox (インポート後) であっても、グローバルシングルトンオブジェクト Reflect は現在 parse メソッドだけを含んでいます。

- -

Reflect オブジェクトのプロパティ

- -

Reflect オブジェクトは現在単一のメソッドで構成されています。

- -

Reflect.parse(src[, options])

- -

src を文字列に強制し、結果を JavaScript プログラムとして解析します。デフォルトでは、解析にされた抽象構文ツリー (AST) を表す Program オブジェクト(以下を参照)が返されます。

- -

追加のオプションは、以下のプロパティのいずれかを含めることができる options オブジェクトを介して提供可能です:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
locBooleanDefault: true
When loc is true, the parser includes source location information in the returned AST nodes.
sourceStringDefault: null
A description of the input source; typically a filename, path, or URL. This string is not meaningful to the parsing process, but is produced as part of the source location information in the returned AST nodes.
lineNumberDefault: 1
The initial line number to use for source location information.
builderBuilderDefault: null
-

A builder object, which can be used to produce AST nodes in custom data formats. The expected callback methods are described under Builder Objects.

-
targetStringDefault: script
-

A type of the parsing target, can be either script or module.

-
- -

If parsing fails due to a syntax error, an instance of SyntaxError is thrown. The syntax error object thrown by Reflect.parse() has the same message property as the syntax error that would be thrown by eval(src). The lineNumber and fileName properties of the syntax error object indicate the source location of the syntax error.

- -

Node オブジェクト

- -

By default, Reflect.parse() produces Node objects, which are plain JavaScript objects (i.e., their prototype derives from the standard Object prototype). All node types implement the following interface:

- -
interface Node {
-    type: string;
-    loc: SourceLocation | null;
-}
-
- -

The type field is a string representing the AST variant type. Each subtype of Node is documented below with the specific string of its type field. You can use this field to determine which interface a node implements.

- -

The loc field represents the source location information of the node. If the parser produced no information about the node's source location, the field is null; otherwise it is an object consisting of a start position (the position of the first character of the parsed source region) and an end position (the position of the first character after the parsed source region):

- -
interface SourceLocation {
-    source: string | null;
-    start: Position;
-    end: Position;
-}
-
- -

Each Position object consists of a line number (1-indexed) and a column number (0-indexed):

- -
interface Position {
-    line: uint32 >= 1;
-    column: uint32 >= 0;
-}
- -

Programs

- -
interface Program <: Node {
-    type: "Program";
-    body: [ Statement ];
-}
-
- -

A complete program source tree.

- -

Functions

- -
interface Function <: Node {
-    id: Identifier | null;
-    params: [ Pattern ];
-    defaults: [ Expression ];
-    rest: Identifier | null;
-    body: BlockStatement | Expression;
-    generator: boolean;
-    expression: boolean;
-}
-
- -

A function declaration or expression. The body of the function may be a block statement, or in the case of an expression closure, an expression.

- -
メモ: Expression closures are SpiderMonkey-specific.
- -

If the generator flag is true, the function is a generator function, i.e., contains a yield expression in its body (other than in a nested function).

- -
メモ: Generators are SpiderMonkey-specific.
- -

If the expression flag is true, the function is an expression closure and the body field is an expression.

- -

Statements

- -
interface Statement <: Node { }
-
- -

Any statement.

- -
interface EmptyStatement <: Statement {
-    type: "EmptyStatement";
-}
-
- -

An empty statement, i.e., a solitary semicolon.

- -
interface BlockStatement <: Statement {
-    type: "BlockStatement";
-    body: [ Statement ];
-}
-
- -

A block statement, i.e., a sequence of statements surrounded by braces.

- -
interface ExpressionStatement <: Statement {
-    type: "ExpressionStatement";
-    expression: Expression;
-}
-
- -

An expression statement, i.e., a statement consisting of a single expression.

- -
interface IfStatement <: Statement {
-    type: "IfStatement";
-    test: Expression;
-    consequent: Statement;
-    alternate: Statement | null;
-}
-
- -

An if statement.

- -
interface LabeledStatement <: Statement {
-    type: "LabeledStatement";
-    label: Identifier;
-    body: Statement;
-}
-
- -

A labeled statement, i.e., a statement prefixed by a break/continue label.

- -
interface BreakStatement <: Statement {
-    type: "BreakStatement";
-    label: Identifier | null;
-}
-
- -

A break statement.

- -
interface ContinueStatement <: Statement {
-    type: "ContinueStatement";
-    label: Identifier | null;
-}
-
- -

continue statement.

- -
interface WithStatement <: Statement {
-    type: "WithStatement";
-    object: Expression;
-    body: Statement;
-}
-
- -

with statement.

- -
interface SwitchStatement <: Statement {
-    type: "SwitchStatement";
-    discriminant: Expression;
-    cases: [ SwitchCase ];
-    lexical: boolean;
-}
-
- -

A switch statement. The lexical flag is metadata indicating whether the switch statement contains any unnested let 宣言 (and therefore introduces a new lexical scope).

- -
interface ReturnStatement <: Statement {
-    type: "ReturnStatement";
-    argument: Expression | null;
-}
-
- -

A return statement.

- -
interface ThrowStatement <: Statement {
-    type: "ThrowStatement";
-    argument: Expression;
-}
-
- -

A throw statement.

- -
interface TryStatement <: Statement {
-    type: "TryStatement";
-    block: BlockStatement;
-    handler: CatchClause | null;
-    guardedHandlers: [ CatchClause ];
-    finalizer: BlockStatement | null;
-}
-
- -

A try statement.

- -
メモ: Multiple catch clauses are SpiderMonkey-specific.
- -
interface WhileStatement <: Statement {
-    type: "WhileStatement";
-    test: Expression;
-    body: Statement;
-}
-
- -

A while statement.

- -
interface DoWhileStatement <: Statement {
-    type: "DoWhileStatement";
-    body: Statement;
-    test: Expression;
-}
-
- -

A do/while statement.

- -
interface ForStatement <: Statement {
-    type: "ForStatement";
-    init: VariableDeclaration | Expression | null;
-    test: Expression | null;
-    update: Expression | null;
-    body: Statement;
-}
-
- -

A for statement.

- -
interface ForInStatement <: Statement {
-    type: "ForInStatement";
-    left: VariableDeclaration |  Expression;
-    right: Expression;
-    body: Statement;
-    each: boolean;
-}
-
- -

A for/in statement, or, if each is true, a for each/in statement.

- -
メモ: The for each form is SpiderMonkey-specific.
- -
interface ForOfStatement <: Statement {
-    type: "ForOfStatement";
-    left: VariableDeclaration |  Expression;
-    right: Expression;
-    body: Statement;
-}
- -

A for/of statement.

- -
interface LetStatement <: Statement {
-    type: "LetStatement";
-    head: [ VariableDeclarator ];
-    body: Statement;
-}
-
- -

let statement.

- -
メモ: The let statement form is SpiderMonkey-specific.
- -
interface DebuggerStatement <: Statement {
-    type: "DebuggerStatement";
-}
-
- -

A debugger statement.

- -
メモ: The debugger statement is new in ECMAScript 5th edition, although SpiderMonkey has supported it for years.
- -

宣言

- -
interface Declaration <: Statement { }
-
- -

Any declaration node. Note that 宣言 are considered statements; this is because 宣言 can appear in any statement context in the language recognized by the SpiderMonkey parser.

- -
メモ: 宣言 in arbitrary nested scopes are SpiderMonkey-specific.
- -
interface FunctionDeclaration <: Function, Declaration {
-    type: "FunctionDeclaration";
-    id: Identifier;
-    params: [ Pattern ];
-    defaults: [ Expression ];
-    rest: Identifier | null;
-    body: BlockStatement | Expression;
-    generator: boolean;
-    expression: boolean;
-}
-
- -

A function declaration.

- -
メモ: The id field cannot be null.
- -
interface VariableDeclaration <: Declaration {
-    type: "VariableDeclaration";
-    宣言: [ VariableDeclarator ];
-    kind: "var" | "let" | "const";
-}
-
- -

A variable declaration, via one of var, let, or const.

- -
interface VariableDeclarator <: Node {
-    type: "VariableDeclarator";
-    id: Pattern;
-    init: Expression | null;
-}
-
- -

A variable declarator.

- -
メモ: The id field cannot be null.
- -
メモ: let and const are SpiderMonkey-specific.
- -

Expressions

- -
interface Expression <: Node, Pattern { }
- -

Any expression node. Since the left-hand side of an assignment may be any expression in general, an expression can also be a pattern.

- -
interface ThisExpression <: Expression {
-    type: "ThisExpression";
-}
-
- -

this expression.

- -
interface ArrayExpression <: Expression {
-    type: "ArrayExpression";
-    elements: [ Expression | null ];
-}
- -

An array expression.

- -
interface ObjectExpression <: Expression {
-    type: "ObjectExpression";
-    properties: [ Property ];
-}
- -

An object expression.

- -
interface Property <: Node {
-    type: "Property";
-    key: Literal | Identifier;
-    value: Expression;
-    kind: "init" | "get" | "set";
-}
- -

A literal property in an object expression can have either a string or number as its value. Ordinary property initializers have a kind value "init"; getters and setters have the kind values "get" and "set", respectively.

- -
interface FunctionExpression <: Function, Expression {
-    type: "FunctionExpression";
-    id: Identifier | null;
-    params: [ Pattern ];
-    defaults: [ Expression ];
-    rest: Identifier | null;
-    body: BlockStatement | Expression;
-    generator: boolean;
-    expression: boolean;
-}
-
- -

A function expression.

- -
interface ArrowExpression <: Function, Expression {
-    type: "ArrowExpression";
-    params: [ Pattern ];
-    defaults: [ Expression ];
-    rest: Identifier | null;
-    body: BlockStatement | Expression;
-    generator: boolean;
-    expression: boolean;
-}
-
- -

A fat arrow function expression, i.e., `let foo = (bar) => { /* body */ }`.

- -
interface SequenceExpression <: Expression {
-    type: "SequenceExpression";
-    expressions: [ Expression ];
-}
- -

A sequence expression, i.e., a comma-separated sequence of expressions.

- -
interface UnaryExpression <: Expression {
-    type: "UnaryExpression";
-    operator: UnaryOperator;
-    prefix: boolean;
-    argument: Expression;
-}
- -

A unary operator expression.

- -
interface BinaryExpression <: Expression {
-    type: "BinaryExpression";
-    operator: BinaryOperator;
-    left: Expression;
-    right: Expression;
-}
- -

A binary operator expression.

- -
interface AssignmentExpression <: Expression {
-    type: "AssignmentExpression";
-    operator: AssignmentOperator;
-    left: Pattern;
-    right: Expression;
-}
- -

An assignment operator expression.

- -
interface UpdateExpression <: Expression {
-    type: "UpdateExpression";
-    operator: UpdateOperator;
-    argument: Expression;
-    prefix: boolean;
-}
- -

An update (increment or decrement) operator expression.

- -
interface LogicalExpression <: Expression {
-    type: "LogicalExpression";
-    operator: LogicalOperator;
-    left: Expression;
-    right: Expression;
-}
- -

A logical operator expression.

- -
interface ConditionalExpression <: Expression {
-    type: "ConditionalExpression";
-    test: Expression;
-    alternate: Expression;
-    consequent: Expression;
-}
- -

A conditional expression, i.e., a ternary ?/: expression.

- -
interface NewExpression <: Expression {
-    type: "NewExpression";
-    callee: Expression;
-    arguments: [ Expression ];
-}
- -

A new expression.

- -
interface CallExpression <: Expression {
-    type: "CallExpression";
-    callee: Expression;
-    arguments: [ Expression ];
-}
- -

A function or method call expression.

- -
interface MemberExpression <: Expression {
-    type: "MemberExpression";
-    object: Expression;
-    property: Identifier | Expression;
-    computed: boolean;
-}
- -

A member expression. If computed === true, the node corresponds to a computed e1[e2] expression and property is an Expression. If computed === false, the node corresponds to a static e1.x expression and property is an Identifier.

- -
interface YieldExpression <: Expression {
-    type: "YieldExpression";
-    argument: Expression | null;
-}
-
- -

yield expression.

- -
メモ: yield expressions are SpiderMonkey-specific.
- -
interface ComprehensionExpression <: Expression {
-    type: "ComprehensionExpression";
-    body: Expression;
-    blocks: [ ComprehensionBlock | ComprehensionIf ];
-    filter: Expression | null;
-}
-
- -

An array comprehension. The blocks array corresponds to the sequence of for and for each blocks. The optional filter expression corresponds to the final if clause, if present.

- -
メモ: Array comprehensions are SpiderMonkey-specific.
- -
interface GeneratorExpression <: Expression {
-    type: "GeneratorExpression";
-    body: Expression;
-    blocks: [ ComprehensionBlock | ComprehensionIf ];
-    filter: Expression | null;
-}
-
- -

A generator expression. As with array comprehensions, the blocks array corresponds to the sequence of for and for each blocks, and the optional filter expression corresponds to the final if clause, if present.

- -
メモ: Generator expressions are SpiderMonkey-specific.
- -
interface GraphExpression <: Expression {
-    type: "GraphExpression";
-    index: uint32;
-    expression: Literal;
-}
-
- -

graph expression, aka "sharp literal," such as #1={ self: #1# }.

- -
メモ: Graph expressions are SpiderMonkey-specific.
- -
interface GraphIndexExpression <: Expression {
-    type: "GraphIndexExpression";
-    index: uint32;
-}
-
- -

graph index expression, aka "sharp variable," such as #1#.

- -
メモ: Graph index expressions are SpiderMonkey-specific.
- -
interface LetExpression <: Expression {
-    type: "LetExpression";
-    head: [ VariableDeclarator ];
-    body: Expression;
-}
-
- -

let expression.

- -
メモ: The let expression form is SpiderMonkey-specific.
- -

Patterns

- -
interface Pattern <: Node { }
-
- -

JavaScript 1.7 introduced destructuring assignment and binding forms. All binding forms (such as function parameters, variable 宣言, and catch block headers) accept array and object destructuring patterns in addition to plain identifiers. The left-hand sides of assignment expressions can be arbitrary expressions, but in the case where the expression is an object or array literal, it is interpreted by SpiderMonkey as a destructuring pattern.

- -

Since the left-hand side of an assignment can in general be any expression, in an assignment context, a pattern can be any expression. In binding positions (such as function parameters, variable 宣言, and catch headers), patterns can only be identifiers in the base case, not arbitrary expressions.

- -
interface ObjectPattern <: Pattern {
-    type: "ObjectPattern";
-    properties: [ { key: Literal | Identifier, value: Pattern } ];
-}
-
- -

An object-destructuring pattern. A literal property in an object pattern can have either a string or number as its value.

- -
interface ArrayPattern <: Pattern {
-    type: "ArrayPattern";
-    elements: [ Pattern | null ];
-}
-
- -

An array-destructuring pattern.

- -

Clauses

- -
interface SwitchCase <: Node {
-    type: "SwitchCase";
-    test: Expression | null;
-    consequent: [ Statement ];
-}
-
- -

A case (if test is an Expression) or default (if test === null) clause in the body of a switch statement.

- -
interface CatchClause <: Node {
-    type: "CatchClause";
-    param: Pattern;
-    guard: Expression | null;
-    body: BlockStatement;
-}
-
- -

catch clause following a try block. The optional guard property corresponds to the optional expression guard on the bound variable.

- -
メモ: The guard expression is SpiderMonkey-specific.
- -
interface ComprehensionBlock <: Node {
-    type: "ComprehensionBlock";
-    left: Pattern;
-    right: Expression;
-    each: boolean;
-}
-
- -

for or for each block in an array comprehension or generator expression.

- -
interface ComprehensionIf <: Node {
-    type: "ComprehensionIf";
-    test: Expression;
-}
- -

An if filter in an array comprehension or generator filter.

- -
メモ: Array comprehensions and generator expressions are SpiderMonkey-specific.
- -

Miscellaneous

- -
interface Identifier <: Node, Expression, Pattern {
-    type: "Identifier";
-    name: string;
-}
-
- -

An identifier. Note that an identifier may be an expression or a destructuring pattern.

- -
interface Literal <: Node, Expression {
-    type: "Literal";
-    value: string | boolean | null | number | RegExp;
-}
-
- -

A literal token. Note that a literal can be an expression.

- -
enum UnaryOperator {
-    "-" | "+" | "!" | "~" | "typeof" | "void" | "delete"
-}
-
- -

A unary operator token.

- -
enum BinaryOperator {
-    "==" | "!=" | "===" | "!=="
-         | "<" | "<=" | ">" | ">="
-         | "<<" | ">>" | ">>>"
-         | "+" | "-" | "*" | "/" | "%"
-         | "|" | "^" | "&" | "in"
-         | "instanceof" | ".."
-}
-
- -

A binary operator token.

- -
メモ: The .. operator is E4X-specific.
- -
enum LogicalOperator {
-    "||" | "&&"
-}
-
- -

A logical operator token.

- -
enum AssignmentOperator {
-    "=" | "+=" | "-=" | "*=" | "/=" | "%="
-        | "<<=" | ">>=" | ">>>="
-        | "|=" | "^=" | "&="
-}
-
- -

An assignment operator token.

- -
enum UpdateOperator {
-    "++" | "--"
-}
-
- -

An update (increment or decrement) operator token.

- -

E4X

- -

This section describes node types that are provided for E4X support. E4X has since been removed as of Gecko 21.

- -

{{ Obsolete_header() }}

- -
メモ: E4X is not part of the ECMAScript standard (ECMA-262), but is a separate standard of its own (ECMA-357).
- -

宣言

- -
interface XMLDefaultDeclaration <: Declaration {
-    type: "XMLDefaultDeclaration";
-    namespace: Expression;
-}
-
- -

A default xml namespace declaration.

- -

Expressions

- -
interface XMLAnyName <: Expression {
-    type: "XMLAnyName";
-}
-
- -

The special E4X wildcard pseudo-identifier *.

- -
interface XMLQualifiedIdentifier <: Expression {
-    type: "XMLQualifiedIdentifier";
-    left: Identifier | XMLAnyName;
-    right: Identifier | Expression;
-    computed: boolean;
-}
-
- -

An E4X qualified identifier, i.e., a pseudo-identifier using the namespace separator ::. If the qualified identifier has a computed name (i.e., the id::[expr] form), then computed is true and the right property is an expression.

- -
interface XMLFunctionQualifiedIdentifier <: Expression {
-    type: "XMLFunctionQualifiedIdentifier";
-    right: Identifier | Expression;
-    computed: boolean;
-}
-
- -

An E4X identifier qualified by the function keyword, e.g., function::id.

- -
メモ: function-qualified identifiers are SpiderMonkey-specific.
- -
interface XMLAttributeSelector <: Expression {
-    type: "XMLAttributeSelector";
-    attribute: Expression;
-}
-
- -

An E4X attribute selector expression, i.e., an @ expression.

- -
interface XMLFilterExpression <: Expression {
-    type: "XMLFilterExpression";
-    left: Expression;
-    right: Expression;
-}
-
- -

An E4X list filter expression, i.e., an expression of the form expr.(expr).

- -
interface XMLElement <: XML, Expression {
-    type: "XMLElement";
-    contents: [ XML ];
-}
-
- -

An E4X literal representing a single XML element.

- -
interface XMLList <: XML, Expression {
-    type: "XMLList";
-    contents: [ XML ];
-}
-
- -

An E4X literal representing a list of XML elements.

- -

XML

- -
interface XML <: Node { }
-
- -

XML data.

- -
interface XMLEscape <: XML {
-    type: "XMLEscape";
-    expression: Expression;
-}
-
- -

XML data with an escaped JavaScript expression.

- -
interface XMLText <: XML {
-    type: "XMLText";
-    text: string;
-}
-
- -

Literal XML text.

- -
interface XMLStartTag <: XML {
-    type: "XMLStartTag";
-    contents: [ XML ];
-}
-
- -

An XML start tag.

- -
interface XMLEndTag <: XML {
-    type: "XMLEndTag";
-    contents: [ XML ];
-}
-
- -

An XML end tag.

- -
interface XMLPointTag <: XML {
-    type: "XMLPointTag";
-    contents: [ XML ];
-}
-
- -

An XML point tag.

- -
interface XMLName <: XML {
-    type: "XMLName";
-    contents: string | [ XML ];
-}
-
- -

An XML name.

- -
interface XMLAttribute <: XML {
-    type: "XMLAttribute";
-    value: string;
-}
-
- -

An XML attribute value.

- -
interface XMLCdata <: XML {
-    type: "XMLCdata";
-    contents: string;
-}
-
- -

An XML CDATA node.

- -
interface XMLComment <: XML {
-    type: "XMLComment";
-    contents: string;
-}
-
- -

An XML comment.

- -
interface XMLProcessingInstruction <: XML {
-    type: "XMLProcessingInstruction";
-    target: string;
-    contents: string | null;
-}
-
- -

An XML processing instruction.

- -

ビルダーオブジェクト

- -

The optional builder parameter to Reflect.parse() makes it possible to construct user-specified data from the parser, rather than the default Node objects. Builder objects may contain any of the callback methods described in this section.

- -

Each callback can produce any custom, user-defined datatype; these are referred to below as CustomExpression, CustomStatement, etc.

- -
メモ: Because this library uses null for optional nodes, it is recommended that user-defined datatypes not use null as a representation of an AST node.
- -

If the loc option is enabled (see the Reflect.parse() options above), then each callback is provided with the source location information of the parsed node as an extra parameter.

- -

All builder callbacks are optional. When a callback is missing, the default format is used, but the provided builder methods are still used recursively for sub-nodes.

- -

Programs

- -
program(body[, loc])
- -
body: [ CustomStatement ]
-loc: SourceLocation
-
- -

戻り値: CustomProgram

- -

Callback to produce a custom program node.

- -

Statements

- -
emptyStatement([loc])
- -
loc: SourceLocation
-
- -

戻り値: CustomStatement

- -

Callback to produce a custom empty statement node.

- -
blockStatement(body[, loc])
- -
body: CustomStatement
-loc: SourceLocation
-
- -

戻り値: CustomStatement

- -

Callback to produce a custom block statement node.

- -
expressionStatement(expr[, loc])
- -
expr: CustomExpression
-loc: SourceLocation
-
- -

戻り値: CustomStatement

- -

Callback to produce a custom expression statement node.

- -
labeledStatement(label, body[, loc])
- -
label: CustomIdentifier
-body: CustomStatement
-loc: SourceLocation
-
- -

戻り値: CustomStatement

- -

Callback to produce a custom labeled statement node.

- -
ifStatement(test, cons, alt[, loc])
- -
test: CustomExpression
-cons: CustomStatement
-alt: CustomStatement | null
-loc: SourceLocation
-
- -

戻り値: CustomStatement

- -

Callback to produce a custom if statement node.

- -
switchStatement(disc, cases, isLexical[, loc])
- -
disc: CustomExpression
-cases: [ CustomSwitchCase ]
-isLexical: boolean
-loc: SourceLocation
-
- -

戻り値: CustomStatement

- -

Callback to produce a custom switch statement node. The isLexical flag is metadata indicating whether the switch statement contains any unnested let 宣言 (and therefore introduces a new lexical scope).

- -
whileStatement(test, body[, loc])
- -
test: CustomExpression
-body: CustomStatement
-loc: SourceLocation
-
- -

戻り値: CustomStatement

- -

Callback to produce a custom while statement node.

- -
doWhileStatement(body, test[, loc])
- -
body: CustomStatement
-test: CustomExpression
-loc: SourceLocation
-
- -

戻り値: CustomStatement

- -

Callback to produce a custom do-while statement node.

- -
forStatement(init, test, update, body[, loc])
- -
init: CustomVariableDeclaration | CustomExpression | null
-test: CustomExpression | null
-update: CustomExpression | null
-body: CustomStatement
-loc: SourceLocation
-
- -

戻り値: CustomStatement

- -

Callback to produce a custom for statement node.

- -
forInStatement(left, right, body, isForEach[, loc])
- -
left: CustomVariableDeclaration | CustomExpression
-right: CustomExpression
-body: CustomStatement
-isForEach: boolean
-loc: SourceLocation
-
- -

戻り値: CustomStatement

- -

Callback to produce a custom for-in statement node. The isForEach flag indicates whether the node is a for each statement.

- -
breakStatement(label[, loc])
- -
label: CustomIdentifier | null
-loc: SourceLocation
-
- -

戻り値: CustomStatement

- -

Callback to produce a custom break statement node.

- -
continueStatement(label[, loc])
- -
label: CustomIdentifier | null
-loc: SourceLocation
-
- -

戻り値: CustomStatement

- -

Callback to produce a custom continue statement node.

- -
withStatement(obj, body[, loc])
- -
obj: CustomExpression
-body: CustomStatement
-loc: SourceLocation
-
- -

戻り値: CustomStatement

- -

Callback to produce a custom with statement node.

- -
returnStatement(arg[, loc])
- -
arg: CustomExpression | null
-loc: SourceLocation
-
- -

戻り値: CustomStatement

- -

Callback to produce a custom return statement node.

- -
tryStatement(body, handlers, fin[, loc])
- -
body: CustomStatement
-handlers: [ CustomCatchClause ]
-fin: CustomStatement | null
-loc: SourceLocation
-
- -

戻り値: CustomStatement

- -

Callback to produce a custom try statement node.

- -
throwStatement(arg[, loc])
- -
arg: CustomExpression
-loc: SourceLocation
-
- -

戻り値: CustomStatement

- -

Callback to produce a custom throw statement node.

- -
debuggerStatement([loc])
- -
loc: SourceLocation
-
- -

戻り値: CustomStatement

- -

Callback to produce a custom debugger statement node.

- -
letStatement(head, body[, loc])
- -
head: [ CustomDeclarator ]
-body: CustomStatement
-loc: SourceLocation
-
- -

戻り値: CustomStatement

- -

Callback to produce a custom let statement node.

- -

宣言

- -
functionDeclaration(name, args, body, isGenerator, isExpression[, loc])
- -
name: string
-args: [ CustomPattern ]
-body: CustomStatement | CustomExpression
-isGenerator: boolean
-isExpression: boolean
-loc: SourceLocation
-
- -

戻り値: CustomDeclaration

- -

Callback to produce a custom function declaration node.

- -
variableDeclaration(kind, dtors[, loc])
- -
kind: "const" | "let" | "var"
-dtors: [ CustomDeclarator ]
-loc: SourceLocation
-
- -

戻り値: CustomDeclaration

- -

Callback to produce a custom variable declaration node.

- -
variableDeclarator(patt, init[, loc])
- -
patt: CustomPattern
-init: CustomExpression | null
-loc: SourceLocation
-
- -

戻り値: CustomDeclarator

- -

Callback to produce a custom variable declarator node.

- -

Expressions

- -
sequenceExpression(exprs[, loc])
- -
exprs: [ CustomExpression ]
-loc: SourceLocation
-
- -

戻り値: CustomExpression

- -

Callback to produce a custom sequence expression node.

- -
conditionalExpression(test, cons, alt[, loc])
- -
test: CustomExpression
-cons: CustomExpression
-alt: CustomExpression
-loc: SourceLocation
-
- -

戻り値: CustomExpression

- -

Callback to produce a custom conditional expression node.

- -
unaryExpression(op, arg, isPrefix[, loc])
- -
op: UnaryOperator
-arg: CustomExpression
-isPrefix: boolean
-loc: SourceLocation
-
- -

戻り値: CustomExpression

- -

Callback to produce a custom unary expression node.

- -
binaryExpression(op, left, right[, loc])
- -
op: BinaryOperator
-left: CustomExpression
-right: CustomExpression
-loc: SourceLocation
-
- -

戻り値: CustomExpression

- -

Callback to produce a custom binary expression node.

- -
assignmentExpression(op, left, right[, loc])
- -
op: AssignmentOperator
-left: CustomExpression
-right: CustomExpression
-loc: SourceLocation
-
- -

戻り値: CustomExpression

- -

Callback to produce a custom assignment expression node.

- -
logicalExpression(op, left, right[, loc])
- -
op: LogicalOperator
-left: CustomExpression
-right: CustomExpression
-loc: SourceLocation
-
- -

戻り値: CustomExpression

- -

Callback to produce a custom logical expression node.

- -
updateExpression(op, arg, isPrefix[, loc])
- -
op: UpdateOperator
-arg: CustomExpression
-isPrefix: boolean
-loc: SourceLocation
-
- -

戻り値: CustomExpression

- -

Callback to produce a custom update expression node.

- -
newExpression(callee, args[, loc])
- -
callee: CustomExpression
-args: [ CustomExpression ]
-loc: SourceLocation
-
- -

戻り値: CustomExpression

- -

Callback to produce a custom new-expression node.

- -
callExpression(callee, args[, loc])
- -
callee: CustomExpression
-args: [ CustomExpression ]
-loc: SourceLocation
-
- -

戻り値: CustomExpression

- -

Callback to produce a custom function call node.

- -
memberExpression(obj, prop, isComputed[, loc])
- -
obj: CustomExpression
-prop: CustomIdentifier | CustomExpression
-isComputed: boolean
-loc: SourceLocation
-
- -

戻り値: CustomExpression

- -

Callback to produce a custom member expression node.

- -
functionExpression(name, args, body, isGenerator, isExpression[, loc])
- -
name: CustomIdentifier | null
-args: [ CustomPattern ]
-body: CustomStatement | CustomExpression
-isGenerator: boolean
-isExpression: boolean
-loc: SourceLocation
-
- -

戻り値: CustomExpression

- -

Callback to produce a custom function expression node.

- -
arrayExpression(elts[, loc])
- -
elts: [ CustomExpression | null ]
-loc: SourceLocation
-
- -

戻り値: CustomExpression

- -

Callback to produce a custom array expression node.

- -
objectExpression(props[, loc])
- -
props: [ CustomObjectProperty ]
-loc: SourceLocation
-
- -

戻り値: CustomExpression

- -

Callback to produce a custom object expression node.

- -
thisExpression([loc])
- -
loc: SourceLocation
-
- -

戻り値: CustomExpression

- -

Callback to produce a custom this expression node.

- -
graphExpression(index, expr[, loc])
- -
index: uint32 >= 1
-expr: CustomExpression
-loc: SourceLocation
-
- -

戻り値: CustomExpression

- -

Callback to produce a custom graph expression node.

- -
graphIndexExpression(index[, loc])
- -
index: uint32 >= 1
-loc: SourceLocation
-
- -

戻り値: CustomExpression

- -

Callback to produce a custom graph index expression node.

- -
comprehensionExpression(body, blocks, filter[, loc])
- -
body: CustomExpression
-blocks: [ CustomComprehensionBlock | CustomComprehensionIf ]
-filter: CustomExpression | null
-loc: SourceLocation
-
- -

戻り値: CustomExpression

- -

Callback to produce a custom comprehension expression node.

- -
generatorExpression(body, blocks, filter[, loc])
- -
body: CustomExpression
-blocks: [ CustomComprehensionBlock | CustomComprehensionIf ]
-filter: CustomExpression | null
-loc: SourceLocation
-
- -

戻り値: CustomExpression

- -

Callback to produce a custom generator expression node.

- -
yieldExpression(arg[, loc])
- -
arg: CustomExpression
-loc: SourceLocation
-
- -

戻り値: CustomExpression

- -

Callback to produce a custom yield expression node.

- -
letExpression(head, body[, loc])
- -
head: [ CustomDeclarator ]
-body: CustomExpression
-loc: SourceLocation
-
- -

戻り値: CustomExpression

- -

Callback to produce a custom let expression node.

- -

Patterns

- -
arrayPattern(elts[, loc])
- -
elts: [ CustomPattern | null ]
-loc: SourceLocation
-
- -

戻り値: CustomPattern

- -

Callback to produce a custom array destructuring pattern node.

- -
objectPattern(props[, loc])
- -
props: [ CustomPropertyPattern ]
-loc: SourceLocation
-
- -

戻り値: CustomPattern

- -

Callback to produce a custom object destructuring pattern node.

- -
propertyPattern(key, patt[, loc])
- -
key: CustomLiteral | CustomIdentifier
-patt: CustomPattern
-loc: SourceLocation
-
- -

戻り値: CustomPropertyPattern

- -

Callback to produce a custom object property destructuring pattern node.

- -

Clauses

- -
switchCase(test, cons[, loc])
- -
test: CustomExpression | null
-cons: [ CustomStatement ]
-loc: SourceLocation
-
- -

戻り値: CustomSwitchCase

- -

Callback to produce a custom case or default clause node. The test argument is null if and only if the node is a default clause.

- -
catchClause(arg, guard, body[, loc])
- -
arg: CustomPattern
-guard: CustomExpression
-body: CustomStatement
-loc: SourceLocation
-
- -

戻り値: CustomCatchClause

- -

Callback to produce a custom catch clause node.

- -
comprehensionBlock(left, right, isForEach[, loc])
- -
left: CustomPattern
-right: CustomExpression
-isForEach: boolean
-loc: SourceLocation
-
- -

戻り値: CustomComprehensionBlock

- -

Callback to produce a custom comprehension block node. The isForEach flag indicates whether the node is a for each block.

- -

comprehensionIf(test[, loc])

- -
test: CustomExpression
-loc: SourceLocation
- -

戻り値: CustomComprehensionIf

- -

Callback to produce a custom comprehension if node.

- -

Miscellaneous

- -
identifier(name[, loc])
- -
name: string
-loc: SourceLocation
-
- -

戻り値: CustomIdentifier/CustomPattern/CustomExpression

- -

Callback to produce a custom identifier node.

- -
literal(val[, loc])
- -
val: string | boolean | null | number | RegExp
-loc: SourceLocation
-
- -

戻り値: CustomLiteral / CustomExpression

- -

Callback to produce a custom literal node.

- -
property(kind, key, val[, loc])
- -
kind: "init" | "get" | "set"
-key: CustomLiteral | CustomIdentifier
-val: CustomExpression
-loc: SourceLocation
-
- -

戻り値: CustomObjectProperty

- -

Callback to produce a custom object property initializer node.

- -

E4X

- -

宣言

- -
xmlDefaultDeclaration(ns[, loc])
- -
loc: SourceLocation
-
- -

戻り値: CustomDeclaration

- -

Callback to produce a custom XML default namespace declaration node.

- -

Expressions

- -
xmlAnyName([loc])
- -
loc: SourceLocation
-
- -

戻り値: CustomXMLAnyName/CustomXML/CustomExpression

- -

Callback to produce a custom XML node for the wildcard pseudo-identifier *.

- -
xmlAttributeSelector(expr[, loc])
- -
expr: CustomExpression
-loc: SourceLocation
-
- -

戻り値: CustomXML/CustomExpression

- -

Callback to produce a custom XML attribute selector node.

- -
xmlFilterExpression(left, right[, loc])
- -
left: CustomExpression
-right: CustomExpression
-loc: SourceLocation
-
- -

戻り値: CustomXML/CustomExpression

- -

Callback to produce a custom XML filter expression node.

- -
xmlQualifiedIdentifier(left, right, isComputed[, loc])
- -
left: CustomIdentifier | CustomXMLAnyName
-right: CustomIdentifier | CustomExpression
-isComputed: boolean
-loc: SourceLocation
-
- -

戻り値: CustomXML/CustomExpression

- -

Callback to produce a custom qualified identifier node.

- -
xmlFunctionQualifiedIdentifier(right, isComputed[, loc])
- -
right: CustomIdentifier | CustomExpression
-isComputed: boolean
-loc: SourceLocation
-
- -

戻り値: CustomXML/CustomExpression

- -

Callback to produce a custom XML function-qualified identifier node.

- -
xmlElement(contents[, loc])
- -
contents: [ CustomXML ]
-loc: SourceLocation
-
- -

戻り値: CustomXML/CustomExpression

- -

Callback to produce a custom XML element node.

- -
xmlList(contents[, loc])
- -
contents: [ CustomXML ]
-loc: SourceLocation
-
- -

戻り値: CustomXML/CustomExpression

- -

Callback to produce a custom XML list node.

- -

XML

- -
xmlEscape(expr[, loc])
- -
expr: CustomExpression
-loc: SourceLocation
-
- -

戻り値: CustomXML

- -

Callback to produce a custom XML escape node.

- -
xmlText(text[, loc])
- -
text: string
-loc: SourceLocation
-
- -

戻り値: CustomXML

- -

Callback to produce a custom XML text node.

- -
xmlStartTag(contents[, loc])
- -
contents: [ CustomXML ]
-loc: SourceLocation
-
- -

戻り値: CustomXML

- -

Callback to produce a custom XML start-tag node.

- -
xmlEndTag(contents[, loc])
- -
contents: [ CustomXML ]
-loc: SourceLocation
-
- -

戻り値: CustomXML

- -

Callback to produce a custom XML end-tag node.

- -
xmlPointTag(contents[, loc])
- -
contents: [ CustomXML ]
-loc: SourceLocation
-
- -

戻り値: CustomXML

- -

Callback to produce a custom XML point tag node.

- -
xmlName(contents[, loc])
- -
contents: string | [ CustomXML ]
-loc: SourceLocation
-
- -

戻り値: CustomXML

- -

Callback to produce a custom XML name node.

- -
xmlAttribute(value[, loc])
- -
value: string
-loc: SourceLocation
-
- -

戻り値: CustomXML

- -

Callback to produce a custom XML attribute node.

- -
xmlCdata(contents[, loc])
- -
contents: string
-loc: SourceLocation
-
- -

戻り値: CustomXML

- -

Callback to produce a custom XML CDATA node.

- -
xmlComment(contents[, loc])
- -
contents: string
-loc: SourceLocation
-
- -

戻り値: CustomXML

- -

Callback to produce a custom XML comment node.

- -
xmlProcessingInstruction(target, contents[, loc])
- -
target: string
-contents: string | null
-loc: SourceLocation
-
- -

戻り値: CustomXML

- -

Callback to produce a custom XML processing instruction node.

diff --git a/files/ja/mozilla/projects/spidermonkey/releases/52/index.html b/files/ja/mozilla/projects/spidermonkey/releases/52/index.html deleted file mode 100644 index d3ddc2bdb5..0000000000 --- a/files/ja/mozilla/projects/spidermonkey/releases/52/index.html +++ /dev/null @@ -1,30 +0,0 @@ ---- -title: SpiderMonkey 52 -slug: Mozilla/Projects/SpiderMonkey/Releases/52 -translation_of: Mozilla/Projects/SpiderMonkey/Releases/52 ---- -

{{SpiderMonkeySidebar("Releases")}}

- -
-

これらのリリースノートは不完全です。

- -

Mozilla JavaScript チームは SpiderMonkey 52 のリリースを発表しました。treeherder から完全なソースコードをダウンロードするには、mozilla-esr52 リポジトリにアクセスし、表示される最初の SM(pkg) リンクをクリックします。それは、左下の小さなウィンドウに "artifact uploaded:mozjs-52.x.y.tar.bz2" のような行が表示されます。

- -

SpiderMonkey 52は、Firefox 52 に搭載された JavaScript エンジンです。以前の SpiderMonkey リリースよりもパフォーマンスが向上しています。また、以下で詳しく説明する新しい言語と API の機能も含まれています。

- -

mozilla.dev.tech.js-engineニュースグループ に投稿することで、このリリースに関するご意見をお聞かせください。また、bugzilla.mozilla.org の Product: Core、Component: JavaScript engine のバグを報告してください。 バグを bug 837921 ("sm.embedding"のエイリアス) にすることをお勧めします。

-
- -

 プラットフォームサポート

- -

SpiderMonkey 52 への移行

- -

新しい JavaScript 言語機能

- -

新しい C++ API

- -

削除された API

- -

API の変更

- -

既知の問題

diff --git a/files/ja/mozilla/projects/spidermonkey/releases/index.html b/files/ja/mozilla/projects/spidermonkey/releases/index.html deleted file mode 100644 index f074c9aeb9..0000000000 --- a/files/ja/mozilla/projects/spidermonkey/releases/index.html +++ /dev/null @@ -1,34 +0,0 @@ ---- -title: SpiderMonkey リリースノート -slug: Mozilla/Projects/SpiderMonkey/Releases -translation_of: Mozilla/Projects/SpiderMonkey/Releases ---- -
{{SpiderMonkeySidebar("Releases")}}
- -
-

ここでは SpiderMonkey のリリースノートを一覧で表示しています。

-
- -

現在のリリース

- - - -

次のリリース

- - - -

過去のリリース

- - diff --git a/files/ja/mozilla/projects/spidermonkey/shell_global_objects/index.html b/files/ja/mozilla/projects/spidermonkey/shell_global_objects/index.html deleted file mode 100644 index b560b3e934..0000000000 --- a/files/ja/mozilla/projects/spidermonkey/shell_global_objects/index.html +++ /dev/null @@ -1,662 +0,0 @@ ---- -title: Shell のグローバルオブジェクト -slug: Mozilla/Projects/SpiderMonkey/Shell_global_objects -tags: - - JavaScript - - NeedsContent - - SpiderMonkey -translation_of: Mozilla/Projects/SpiderMonkey/Shell_global_objects ---- -

これらは、プログラムを起動したときに SpiderMonkey js コマンドラインインタプリタによって自動的に設定されるグローバルオブジェクトです。

- -

メモ: このリストは、JavaScript シェルの紹介の「組み込み関数」と重複しているため、おそらく完全ではありません。詳しくは js/src/shell/js.cpp (shell_functions 周辺) をご覧ください。

- -

このページには SpiderMonkey 53 で利用可能な変数と関数がリストされています。各バージョン間には多少の違いがあるかもしれません。js シェルの help() 関数で関数の一覧を見ることができます。

- -

変数

- -
-
scriptArgs
-
js シェルに渡された引数を含む配列。
-
scriptPath
-
スクリプトのパスである文字列。
-
console
-
以下のプロパティを持つオブジェクト: -
-
log
-
式を評価して stdout に出力します。この関数は print() 関数のエイリアスです。
-
-
-
timesAccessed
-
この変数が何回アクセスされたかを示す数を返します
-
PerfMeasurement
-
PerfMeasurement.jsm を参照してください。
-
- -

シェルのみの関数

- -

Functions always available

- -
-
version([number])
-
Get or force a script compilation version number.
-
options([option ...])
-
Get or toggle JavaScript options.
-
load(['foo.js' ...])
-
Load files named by string arguments. Filename is relative to the current working directory.
-
loadRelativeToScript(['foo.js' ...])
-
Load files named by string arguments. Filename is relative to the calling script.
-
evaluate(code[, options])
-
Evaluate code as though it were the contents of a file. options is an optional object that may have these properties: -
-
isRunOnce
-
use the isRunOnce compiler option (default: false)
-
noScriptRval
-
use the no-script-rval compiler option (default: false)
-
fileName
-
filename for error messages and debug info
-
lineNumber
-
starting line number for error messages and debug info
-
columnNumber
-
starting column number for error messages and debug info
-
global
-
global in which to execute the code
-
newContext
-
if true, create and use a new cx (default: false)
-
catchTermination
-
if true, catch termination (failure without an exception value, as for slow scripts or out-of-memory) and return 'terminated'
-
element
-
if present with value v, convert v to an object o and mark the source as being attached to the DOM element o. If the property is omitted or v is null, don't attribute the source to any DOM element.
-
elementAttributeName
-
if present and not undefined, the name of property of element that holds this code. This is what Debugger.Source.prototype.elementAttributeName returns.
-
sourceMapURL
-
if present with value v, convert v to a string, and provide that as the code's source map URL. If omitted, attach no source map URL to the code (although the code may provide one itself, via a //#sourceMappingURL comment).
-
sourceIsLazy
-
if present and true, indicates that, after compilation, script source should not be cached by the JS engine and should be lazily loaded from the embedding as-needed.
-
loadBytecode
-
if true, and if the source is a CacheEntryObject, the bytecode would be loaded and decoded from the cache entry instead of being parsed, then it would be executed as usual.
-
saveBytecode
-
if true, and if the source is a CacheEntryObject, the bytecode would be encoded and saved into the cache entry after the script execution.
-
assertEqBytecode
-
if true, and if both loadBytecode and saveBytecode are true, then the loaded bytecode and the encoded bytecode are compared. and an assertion is raised if they differ.
-
-
-
run('foo.js')
-
Run the file named by the first argument, returning the number of of milliseconds spent compiling and executing it.
-
- -
-
read('bar.js')
-
Reads the file named by the first argument, returning the content of the file as string.
-
- -
-
readline()
-
Read a single line from stdin.
-
readlineBuf([ buf ])
-
Emulate readline() on the specified string. The first call with a string argument sets the source buffer. Subsequent calls without an argument then read from this buffer line by line.
-
print([exp ...])
-
Evaluate and print expressions to stdout.
-
printErr([exp ...])
-
Evaluate and print expressions to stderr.
-
putstr([exp])
-
Evaluate and print expression without newline.
-
dateNow()
-
Return the current time with sub-ms precision.
-
help([name ...])
-
Display usage and help messages.
-
quit()
-
Quit the shell.
-
assertEq(actual, expected[, msg])
-
Throw if the first two arguments are not the same (both +0 or both -0, both NaN, or non-zero and ===).
-
startTimingMutator()
-
Start accounting time to mutator vs GC.
-
stopTimingMutator()
-
Stop accounting time to mutator vs GC and dump the results.
-
throwError()
-
Throw an error from JS_ReportError.
-
intern(str)
-
Internalize str in the atom table.
-
getslx(obj)
-
Get script line extent.
-
evalcx(s[, o])
-
Evaluate s in optional sandbox object o. if (s == '' && !o) return new o with eager standard classes, if (s == 'lazy' && !o) return new o with lazy standard classes
-
evalInWorker(str)
-
Evaluate str in a separate thread with its own runtime.
-
getSharedArrayBuffer()
-
Retrieve the SharedArrayBuffer object from the cross-worker mailbox. The object retrieved may not be identical to the object that was installed, but it references the same shared memory. getSharedArrayBuffer performs an ordering memory barrier.
-
setSharedArrayBuffer()
-
Install the SharedArrayBuffer object in the cross-worker mailbox. setSharedArrayBuffer performs an ordering memory barrier.
-
shapeOf(obj)
-
Get the shape of obj (an implementation detail).
-
groupOf(obj)
-
Get the group of obj (an implementation detail).
-
unwrappedObjectsHaveSameShape(obj1, obj2)
-
Returns true iff obj1 and obj2 have the same shape, false otherwise. Both objects are unwrapped first, so this can be used on objects from different globals.
-
sleep(dt)
-
Sleep for dt seconds.
-
compile(code)
-
Compiles a string to bytecode, potentially throwing.
-
parseModule(code)
-
Parses source text as a module and returns a Module object.
-
setModuleResolveHook(function(module, specifier) {})
-
Set the HostResolveImportedModule hook to function. This hook is used to look up a previously loaded module object. It should be implemented by the module loader.
-
getModuleLoadPath()
-
Return any --module-load-path argument passed to the shell. Used by the module loader.
-
parse(code)
-
Parses a string, potentially throwing.
-
syntaxParse(code)
-
Check the syntax of a string, returning success value
-
offThreadCompileScript(code[, options])
-
Compile code on a helper thread. To wait for the compilation to finish and run the code, call runOffThreadScript. If present, options may have properties saying how the code should be compiled: -
-
noScriptRval
-
use the no-script-rval compiler option (default: false)
-
fileName
-
filename for error messages and debug info
-
lineNumber
-
starting line number for error messages and debug info
-
columnNumber
-
starting column number for error messages and debug info
-
element
-
if present with value v, convert v to an object o and mark the source as being attached to the DOM element o. If the property is omitted or v is null, don't attribute the source to any DOM element.
-
elementAttributeName
-
if present and not undefined, the name of property of element that holds this code. This is what Debugger.Source.prototype.elementAttributeName returns.
-
-
-
runOffThreadScript()
-
Wait for off-thread compilation to complete. If an error occurred, throw the appropriate exception; otherwise, run the script and return its value.
-
offThreadCompileModule(code)
-
Compile code on a helper thread. To wait for the compilation to finish and get the module object, call finishOffThreadModule.
-
finishOffThreadModule()
-
Wait for off-thread compilation to complete. If an error occurred, throw the appropriate exception; otherwise, return the module object
-
timeout([seconds], [func])
-
Get/Set the limit in seconds for the execution time for the current context. A negative value (default) means that the execution time is unlimited. If a second argument is provided, it will be invoked when the timer elapses. Calling this function will replace any callback set by setInterruptCallback.
-
interruptIf(cond)
-
Requests interrupt callback if cond is true. If a callback function is set via timeout or setInterruptCallback, it will be called. No-op otherwise.
-
invokeInterruptCallback(fun)
-
Forcefully set the interrupt flag and invoke the interrupt handler. If a callback function is set via timeout or setInterruptCallback, it will be called. Before returning, fun is called with the return value of the interrupt handler.
-
setInterruptCallback(func)
-
Sets func as the interrupt callback function. Calling this function will replace any callback set by timeout.
-
enableLastWarning()
-
Enable storing the last warning.
-
disableLastWarning()
-
Disable storing the last warning.
-
getLastWarning()
-
Returns an object that represents the last warning.
-
clearLastWarning()
-
Clear the last warning.
-
elapsed()
-
Execution time elapsed for the current thread.
-
decompileFunction(func)
-
Decompile a function.
-
decompileThis()
-
Decompile the currently executing script.
-
thisFilename()
-
Return the filename of the current script
-
newGlobal([options])
-
Return a new global object in a new compartment. If options is given, it may have any of the following properties: -
-
sameZoneAs
-
the compartment will be in the same zone as the given object (defaults to a new zone)
-
invisibleToDebugger
-
the global will be invisible to the debugger (default false)
-
principal
-
if present, its value converted to a number must be an integer that fits in 32 bits; use that as the new compartment's principal. Shell principals are toys, meant only for testing; one shell principal subsumes another if its set bits are a superset of the other's. Thus, a principal of 0 subsumes nothing, while a principals of ~0 subsumes all other principals. The absence of a principal is treated as if its bits were 0xffff, for subsumption purposes. If this property is omitted, supply no principal.
-
-
-
createMappedArrayBuffer(filename, [offset, [size]])
-
Create an array buffer that mmaps the given file.
-
addPromiseReactions(promise, onResolve, onReject)
-
Calls the JS::AddPromiseReactions JSAPI function with the given arguments.
-
getMaxArgs()
-
Return the maximum number of supported args for a call.
-
objectEmulatingUndefined()
-
Return a new object obj for which typeof obj === "undefined", obj == null and obj == undefined (and vice versa for !=), and ToBoolean(obj) === false.
-
isCachingEnabled()
-
Return whether JS caching is enabled.
-
setCachingEnabled(b)
-
Enable or disable JS caching.
-
cacheEntry(code)
-
Return a new opaque object which emulates a cache entry of a script. This object encapsulates the code and its cached content. The cache entry is filled and read by the evaluate function by using it in place of the source, and by setting saveBytecode and loadBytecode options.
-
printProfilerEvents()
-
Register a callback with the profiler that prints javascript profiler events to stderr. Callback is only registered if profiling is enabled.
-
enableSingleStepProfiling()
-
This function will fail on platforms that don't support single-step profiling (currently everything but ARM-simulator). When enabled, at every instruction a backtrace will be recorded and stored in an array. Adjacent duplicate backtraces are discarded.
-
disableSingleStepProfiling()
-
Return the array of backtraces recorded by enableSingleStepProfiling.
-
enableSPSProfiling()
-
Enables SPS instrumentation and corresponding assertions, with slow assertions disabled.
-
enableSPSProfilingWithSlowAssertions()
-
Enables SPS instrumentation and corresponding assertions, with slow assertions enabled.
-
disableSPSProfiling()
-
Disables SPS instrumentation
-
isLatin1(s)
-
Return true iff the string's characters are stored as Latin1.
-
stackPointerInfo()
-
Return an int32 value which corresponds to the offset of the latest stack pointer, such that one can take the differences of 2 to estimate a frame-size.
-
entryPoints(params)
-
Carry out some JSAPI operation as directed by params, and return an array of objects describing which JavaScript entry points were invoked as a result. params is an object whose properties indicate what operation to perform. Here are the recognized groups of properties: -
-
{ function }
-
Call the object params.function with no arguments.
-
{ object, property }
-
Fetch the property named params.property of params.object.
-
{ ToString }
-
Apply JS::ToString to params.toString.
-
{ ToNumber }
-
Apply JS::ToNumber to params.toNumber.
-
{ eval }
-
Apply JS::Evaluate to params.eval.
-
- The return value is an array of strings, with one element for each JavaScript invocation that occurred as a result of the given operation. Each element is the name of the function invoked, or the string 'eval:FILENAME' if the code was invoked by eval or something similar.
-
drainJobQueue()
-
Take jobs from the shell's job queue in FIFO order and run them until the queue is empty.
-
setPromiseRejectionTrackerCallback()
-
Sets the callback to be invoked whenever a Promise rejection is unhandled or a previously-unhandled rejection becomes handled.
-
- -

Functions available only in DEBUG build

- -
-
disassemble([fun/code])
-
Return the disassembly for the given function or code. All disassembly functions take these options as leading string arguments: -
-
-r
-
disassemble recursively
-
-l
-
show line numbers
-
-S
-
omit source notes
-
-
-
dis([fun/code])
-
Disassemble functions into bytecodes.
-
disfile('foo.js')
-
Disassemble script file into bytecodes.
-
dissrc([fun/code])
-
Disassemble functions with source lines.
-
notes([fun])
-
Show source notes for functions.
-
stackDump(showArgs, showLocals, showThisProps)
-
Tries to print a lot of information about the current stack. Similar to the DumpJSStack() function in the browser.
-
arrayInfo(a1, a2, ...)
-
Report statistics about arrays.
-
- -

Functions available only if ENABLE_INTL_API is defined

- -
-
addIntlExtras(obj)
-
Adds various not-yet-standardized Intl functions as properties on the provided object (this should generally be Intl itself). The added functions and their behavior are experimental: don't depend upon them unless you're willing to update your code if these experimental APIs change underneath you.
-
- -

Functions available if --fuzzing-safe is not specified

- -
-
clone(fun[, scope])
-
Clone function object.
-
getSelfHostedValue()
-
Get a self-hosted value by its name. Note that these values don't get cached, so repeatedly getting the same value creates multiple distinct clones.
-
line2pc([fun,] line)
-
Map line number to PC.
-
pc2line(fun[, pc])
-
Map PC to line number.
-
nestedShell(shellArgs...)
-
Execute the given code in a new JS shell process, passing this nested shell the arguments passed to nestedShell. argv[0] of the nested shell will be argv[0] of the current shell (which is assumed to be the actual path to the shell. arguments[0] (of the call to nestedShell) will be argv[1], arguments[1] will be argv[2], etc.
-
assertFloat32(value, isFloat32)
-
In IonMonkey only, asserts that value has (resp. hasn't) the MIRType::Float32 if isFloat32 is true (resp. false).
-
assertRecoveredOnBailout(var)
-
In IonMonkey only, asserts that variable has RecoveredOnBailout flag.
-
withSourceHook(hook, fun)
-
Set this JS runtime's lazy source retrieval hook (that is, the hook used to find sources compiled with CompileOptions::LAZY_SOURCE) to hook; call fun with no arguments; and then restore the runtime's original hook. Return or throw whatever fun did. hook gets passed the requested code's URL, and should return a string. -

Notes:

- -
    -
  1. SpiderMonkey may assert if the returned code isn't close enough to the script's real code, so this function is not fuzzer-safe.
  2. -
  3. The runtime can have only one source retrieval hook active at a time. If fun is not careful, hook could be asked to retrieve the source code for compilations that occurred long before it was set, and that it knows nothing about. The reverse applies as well: the original hook, that we reinstate after the call to fun completes, might be asked for the source code of compilations that fun performed, and which, presumably, only hook knows how to find.
  4. -
-
-
wrapWithProto(obj)
-
Wrap an object into a noop wrapper with prototype semantics. Note: This is not fuzzing safe because it can be used to construct deeply nested wrapper chains that cannot exist in the wild.
-
trackedOpts(fun)
-
Returns an object describing the tracked optimizations of fun, if any. If fun is not a scripted function or has not been compiled by Ion, null is returned.
-
dumpScopeChain(obj)
-
Prints the scope chain of an interpreted function or a module.
-
crash([message])
-
Crashes the process with a MOZ_CRASH.
-
setARMHwCapFlags("flag1,flag2 flag3")
-
On non-ARM, no-op. On ARM, set the hardware capabilities. The list of flags is available by calling this function with help as the flag's name
-
wasmLoop(filename, imports)
-
Performs an AFL-style persistent loop reading data from the given file and passing it to thewasmEval function together with the specified imports object.
-
- -

テスト用関数

- -

Testing functions are available also on Firefox via Components.utils.getJSTestingFunctions()

- -

Functions always available

- -
-
gc([obj] | 'zone' [, 'shrinking'])
-
Run the garbage collector. When obj is given, GC only its zone. If zone is given, GC any zones that were scheduled for GC via schedulegc. If shrinking is passed as the optional second argument, perform a shrinking GC rather than a normal GC.
-
minorgc([aboutToOverflow])
-
Run a minor collector on the Nursery. When aboutToOverflow is true, marks the store buffer as about-to-overflow before collecting.
-
gcparam(name [, value])
-
Wrapper for JS_[GS]etGCParameter. The name is one of: -
    -
  • maxBytes
  • -
  • maxMallocBytes
  • -
  • gcBytes
  • -
  • gcNumber
  • -
  • mode
  • -
  • unusedChunks
  • -
  • totalChunks
  • -
  • sliceTimeBudget
  • -
  • markStackLimit
  • -
  • highFrequencyTimeLimit
  • -
  • highFrequencyLowLimit
  • -
  • highFrequencyHighLimit
  • -
  • highFrequencyHeapGrowthMax
  • -
  • highFrequencyHeapGrowthMin
  • -
  • lowFrequencyHeapGrowth
  • -
  • dynamicHeapGrowth
  • -
  • dynamicMarkSlice
  • -
  • allocationThreshold
  • -
  • minEmptyChunkCount
  • -
  • maxEmptyChunkCount
  • -
  • compactingEnabled
  • -
  • refreshFrameSlicesEnabled
  • -
-
-
relazifyFunctions(...)
-
Perform a GC and allow relazification of functions. Accepts the same arguments as gc().
-
getBuildConfiguration()
-
Return an object describing some of the configuration options SpiderMonkey was built with.
-
hasChild(parent, child)
-
Return true if child is a child of parent, as determined by a call to TraceChildren
-
setSavedStacksRNGState(seed)
-
Set this compartment's SavedStacks' RNG state.
-
getSavedFrameCount()
-
Return the number of SavedFrame instances stored in this compartment's SavedStacks cache.
-
saveStack([maxDepth [, compartment]])
-
Capture a stack. If maxDepth is given, capture at most maxDepth number of frames. If compartment is given, allocate the js::SavedFrame instances with the given object's compartment.
-
saveStack(object [, shouldIgnoreSelfHosted = true]])
-
Capture a stack back to the first frame whose principals are subsumed by the object's compartment's principals. If shouldIgnoreSelfHosted is given, control whether self-hosted frames are considered when checking principals.
-
callFunctionFromNativeFrame(function)
-
Call function with a (C++-)native frame on stack. Required for testing that SaveStack properly handles native frames.
-
callFunctionWithAsyncStack(function, stack, asyncCause)
-
Call function, using the provided stack as the async stack responsible for the call, and propagate its return value or the exception it throws. The function is called with no arguments, and this is undefined. The specified asyncCause is attached to the provided stack frame.
-
enableTrackAllocations()
-
Start capturing the JS stack at every allocation. Note that this sets an object metadata callback that will override any other object metadata callback that may be set.
-
disableTrackAllocations()
-
Stop capturing the JS stack at every allocation.
-
makeFinalizeObserver()
-
Get a special object whose finalization increases the counter returned by the finalizeCount function.
-
finalizeCount()
-
Return the current value of the finalization counter that is incremented each time an object returned by the makeFinalizeObserver is finalized.
-
resetFinalizeCount()
-
Reset the value returned by finalizeCount().
-
gcPreserveCode()
-
Preserve JIT code during garbage collections.
-
startgc([n [, 'shrinking']])
-
Start an incremental GC and run a slice that processes about n objects. If shrinking is passesd as the optional second argument, perform a shrinking GC rather than a normal GC.
-
gcslice([n])
-
Start or continue an an incremental GC, running a slice that processes about n objects.
-
abortgc()
-
Abort the current incremental GC.
-
fullcompartmentchecks(true|false)
-
If true, check for compartment mismatches before every GC.
-
nondeterministicGetWeakMapKeys(weakmap)
-
Return an array of the keys in the given WeakMap.
-
internalConst(name)
-
Query an internal constant for the engine. See InternalConst source for the list of constant names.
-
isProxy(obj)
-
If true, obj is a proxy of some sort
-
dumpHeap(['collectNurseryBeforeDump'], [filename])
-
Dump reachable and unreachable objects to the named file, or to stdout. If collectNurseryBeforeDump is specified, a minor GC is performed first, otherwise objects in the nursery are ignored.
-
terminate()
-
Terminate JavaScript execution, as if we had run out of memory or been terminated by the slow script dialog.
-
readSPSProfilingStack()
-
Reads the jit stack using ProfilingFrameIterator.
-
enableOsiPointRegisterChecks()
-
Emit extra code to verify live regs at the start of a VM call are not modified before its OsiPoint.
-
displayName(fn)
-
Gets the display name for a function, which can possibly be a guessed or inferred name based on where the function was defined. This can be different from the name property on the function.
-
isAsmJSCompilationAvailable
-
Returns whether asm.js compilation is currently available or whether it is disabled (e.g., by the debugger).
-
isSimdAvailable
-
Returns true if SIMD extensions are supported on this platform.
-
getCompilerOptions()
-
Return an object describing some of the JIT compiler options.
-
isAsmJSModule(fn)
-
Returns whether the given value is a function containing "use asm" that has been validated according to the asm.js spec.
-
isAsmJSModuleLoadedFromCache(fn)
-
Return whether the given asm.js module function has been loaded directly from the cache. This function throws an error if fn is not a validated asm.js module.
-
isAsmJSFunction(fn)
-
Returns whether the given value is a nested function in an asm.js module that has been both compile- and link-time validated.
-
wasmIsSupported()
-
Returns a boolean indicating whether WebAssembly is supported on the current device.
-
wasmTextToBinary(str)
-
Translates the given text wasm module into its binary encoding.
-
wasmBinaryToText(bin)
-
Translates binary encoding to text format
-
wasmExtractCode(module)
-
Extracts generated machine code from WebAssembly.Module.
-
isLazyFunction(fun)
-
True if fun is a lazy JSFunction.
-
isRelazifiableFunction(fun)
-
Ture if fun is a JSFunction with a relazifiable JSScript.
-
enableShellAllocationMetadataBuilder()
-
Use ShellAllocationMetadataBuilder to supply metadata for all newly created objects.
-
getAllocationMetadata(obj)
-
Get the metadata for an object.
-
bailout()
-
Force a bailout out of ionmonkey (if running in ionmonkey).
-
bailAfter(number)
-
Start a counter to bail once after passing the given amount of possible bailout positions in ionmonkey.
-
inJit()
-
Returns true when called within (jit-)compiled code. When jit compilation is disabled this function returns an error string. This function returns false in all other cases. Depending on truthiness, you should continue to wait for compilation to happen or stop execution.
-
inIon()
-
Returns true when called within ion. When ion is disabled or when compilation is abnormally slow to start, this function returns an error string. Otherwise, this function returns false. This behaviour ensures that a falsy value means that we are not in ion, but expect a compilation to occur in the future. Conversely, a truthy value means that we are either in ion or that there is litle or no chance of ion ever compiling the current script.
-
assertJitStackInvariants()
-
Iterates the Jit stack and check that stack invariants hold.
-
setCompilerOption(option, number)
-
Set a compiler option indexed in JSCompileOption enum to a number.
-
setIonCheckGraphCoherency(bool)
-
Set whether Ion should perform graph consistency (DEBUG-only) assertions. These assertions are valuable and should be generally enabled, however they can be very expensive for large (wasm) programs.
-
serialize(data, [transferables, [policy]])
-
Serialize data using JS_WriteStructuredClone. Returns a structured clone buffer object. policy must be an object. The following keys' string values will be used to determine whether the corresponding types may be serialized (value allow, the default) or not (value deny). If denied types are encountered a TypeError will be thrown during cloning. Valid keys: SharedArrayBuffer.
-
deserialize(clonebuffer)
-
Deserialize data generated by serialize.
-
detachArrayBuffer(buffer)
-
Detach the given ArrayBuffer object from its memory, i.e. as if it had been transferred to a WebWorker.
-
helperThreadCount()
-
Returns the number of helper threads available for off-main-thread tasks.
-
reportOutOfMemory()
-
Report OOM, then clear the exception and return undefined. For crash testing.
-
throwOutOfMemory()
-
Throw out of memory exception, for OOM handling testing.
-
reportLargeAllocationFailure()
-
Call the large allocation failure callback, as though a large malloc call failed, then return undefined. In Gecko, this sends a memory pressure notification, which can free up some memory.
-
findPath(start, target)
-
Return an array describing one of the shortest paths of GC heap edges from start to target, or undefined if target is unreachable from start. Each element of the array is either of the form: { node: {object or string}, edge: {string describing edge from node} } , if the node is a JavaScript object or value; or of the form: { type: {string describing node}, edge: {string describing edge} } , if the node is some internal thing that is not a proper JavaScript value (like a shape or a scope chain element). The destination of the i'th array element's edge is the node of the i+1'th array element; the destination of the last array element is implicitly target.
-
shortestPaths(start, targets, maxNumPaths)
-
Return an array of arrays of shortest retaining paths. There is an array of shortest retaining paths for each object in targets. The maximum number of paths in each of those arrays is bounded by maxNumPaths. Each element in a path is of the form { predecessor, edge }.
-
sharedMemoryEnabled()
-
Return true if SharedArrayBuffer and Atomics are enabled
-
evalReturningScope(scriptStr, [global])
-
Evaluate the script in a new scope and return the scope. If global is present, clone the script to global before executing.
-
cloneAndExecuteScript(source, global)
-
Compile source in the current compartment, clone it into global's compartment, and run it there.
-
backtrace()
-
Dump out a brief backtrace.
-
getBacktrace([options])
-
Return the current stack as a string. Takes an optional options object, which may contain any or all of the boolean properties options.args - show arguments to each function options.locals - show local variables in each frame options.thisprops - show the properties of the this object of each frame
-
byteSize(value)
-
Return the size in bytes occupied by value, or undefined if value is not allocated in memory.
-
byteSizeOfScript(f)
-
Return the size in bytes occupied by the function f's JSScript.
-
setImmutablePrototype(obj)
-
Try to make obj's [[Prototype]] immutable, such that subsequent attempts to change it will fail. Return true if obj's [[Prototype]] was successfully made immutable (or if it already was immutable), false otherwise. Throws in case of internal error, or if the operation doesn't even make sense (for example, because the object is a revoked proxy).
-
setLazyParsingDisabled(bool)
-
Explicitly disable lazy parsing in the current compartment. The default is that lazy parsing is not explicitly disabled.
-
setDiscardSource(bool)
-
Explicitly enable source discarding in the current compartment. The default is that source discarding is not explicitly enabled.
-
getConstructorName(object)
-
If the given object was created with new Ctor, return the constructor's display name. Otherwise, return null.
-
allocationMarker([options])
-
Return a freshly allocated object whose [[Class]] name is AllocationMarker. Such objects are allocated only by calls to this function, never implicitly by the system, making them suitable for use in allocation tooling tests. Takes an optional options object which may contain the following properties: * nursery: bool, whether to allocate the object in the nursery
-
setGCCallback({action:"...", options...})
-
Set the GC callback. action may be: -
-
minorGC
-
run a nursery collection
-
majorGC
-
run a major collection, nesting up to a given depth
-
-
-
getLcovInfo(global)
-
Generate LCOV tracefile for the given compartment. If no global are provided then the current global is used as the default one.
-
getModuleEnvironmentNames(module)
-
Get the list of a module environment's bound names for a specified module.
-
getModuleEnvironmentValue(module, name)
-
Get the value of a bound name in a module environment.
-
enableForEach()
-
Enables the deprecated, non-standard for-each.
-
disableForEach()
-
Disables the deprecated, non-standard for-each.
-
- -

Functions available only if SPIDERMONKEY_PROMISE is defined

- -
-
settlePromiseNow(promise)
-
'Settle' a promise immediately. This just marks the promise as resolved with a value of undefined and causes the firing of any onPromiseSettled hooks set on Debugger instances that are observing the given promise's global as a debuggee.
-
getWaitForAllPromise(densePromisesArray)
-
Calls the GetWaitForAllPromise JSAPI function and returns the result Promise.
-
resolvePromise(promise, resolution)
-
Resolve a Promise by calling the JSAPI function JS::ResolvePromise.
-
rejectPromise(promise, reason)
-
Reject a Promise by calling the JSAPI function JS::RejectPromise.
-
- -

Functions available only if SPIDERMONKEY_PROMISE is not defined

- -
-
makeFakePromise()
-
Create an object whose [[Class]] name is 'Promise' and call JS::dbg::onNewPromise on it before returning it. It doesn't actually have any of the other behavior associated with promises.
-
settleFakePromise(promise)
-
'Settle' a promise created by makeFakePromise(). This doesn't have any observable effects outside of firing any onPromiseSettled hooks set on Debugger instances that are observing the given promise's global as a debuggee.
-
- -

Functions available only if JS_GC_ZEAL is defined

- -
-
gczeal(level, [N])
-
Specifies how zealous the garbage collector should be. Some of these modes can be set simultaneously, by passing multiple level options, e.g. "2;4" will activate both modes 2 and 4. Modes can be specified by name or number. -

Values:

- -
-
0: (None)
-
Normal amount of collection (resets all modes)
-
1: (Poke)
-
Collect when roots are added or removed
-
2: (Alloc)
-
Collect when every N allocations (default: 100)
-
3: (FrameGC)
-
Collect when the window paints (browser only)
-
4: (VerifierPre)
-
Verify pre write barriers between instructions
-
5: (FrameVerifierPre)
-
Verify pre write barriers between paints
-
6: (StackRooting)
-
Verify stack rooting
-
7: (GenerationalGC)
-
Collect the nursery every N nursery allocations
-
8: (IncrementalRootsThenFinish)
-
Incremental GC in two slices: 1) mark roots 2) finish collection
-
9: (IncrementalMarkAllThenFinish)
-
Incremental GC in two slices: 1) mark all 2) new marking and finish
-
10: (IncrementalMultipleSlices)
-
Incremental GC in multiple slices
-
11: (IncrementalMarkingValidator)
-
Verify incremental marking
-
12: (ElementsBarrier)
-
Always use the individual element post-write barrier, regardless of elements size
-
13: (CheckHashTablesOnMinorGC)
-
Check internal hashtables on minor GC
-
14: (Compact)
-
Perform a shrinking collection every N allocations
-
15: (CheckHeapAfterGC)
-
Walk the heap to check its integrity after every GC
-
16: (CheckNursery)
-
Check nursery integrity on minor GC
-
-
-
schedulegc([num | obj])
-
If num is given, schedule a GC after num allocations. If obj is given, schedule a GC of obj's zone. Returns the number of allocations before the next trigger.
-
selectforgc(obj1, obj2, ...)
-
Schedule the given objects to be marked in the next GC slice.
-
verifyprebarriers()
-
Start or end a run of the pre-write barrier verifier.
-
verifypostbarriers()
-
Does nothing (the post-write barrier verifier has been remove).
-
gcstate()
-
Report the global GC state.
-
deterministicgc(true|false)
-
If true, only allow determinstic GCs to run.
-
- -

Functions available only if JS_TRACE_LOGGING is defined

- -
-
startTraceLogger()
-
Start logging the mainThread. Note: tracelogging starts automatically. Disable it by setting environment variable TLOPTIONS=disableMainThread
-
stopTraceLogger()
-
Stop logging the mainThread.
-
- -

Functions available only in nightly build

- -
-
objectAddress(obj)
-
Return the current address of the object. For debugging only--this address may change during a moving GC.
-
sharedAddress(obj)
-
Return the address of the shared storage of a SharedArrayBuffer.
-
- -

Functions available only in DEBUG build

- -
-
dumpObject()
-
Dump an internal representation of an object.
-
dumpStringRepresentation(str)
-
Print a human-readable description of how the string str is represented.
-
setRNGState(seed0, seed1)
-
Set this compartment's RNG state.
-
- -

Functions available only in DEBUG build or JS_OOM_BREAKPOINT is defined

- -
-
oomThreadTypes()
-
Get the number of thread types that can be used as an argument for oomAfterAllocations() and oomAtAllocation().
-
oomAfterAllocations(count [,threadType])
-
After count js_malloc memory allocations, fail every following allocation (return nullptr). The optional thread type limits the effect to the specified type of helper thread.
-
oomAtAllocation(count [,threadType])
-
After count js_malloc memory allocations, fail the next allocation (return nullptr). The optional thread type limits the effect to the specified type of helper thread.
-
resetOOMFailure()
-
Remove the allocation failure scheduled by either oomAfterAllocations() or oomAtAllocation() and return whether any allocation had been caused to fail.
-
oomTest(function, [expectExceptionOnFailure = true])
-
Test that the passed function behaves correctly under OOM conditions by repeatedly executing it and simulating allocation failure at successive allocations until the function completes without seeing a failure. By default this tests that an exception is raised if execution fails, but this can be disabled by passing false as the optional second parameter. This is also disabled when --fuzzing-safe is specified.
-
- -

Functions available only in DEBUG build if --fuzzing-safe is not specified and

- -
-
parseRegExp(pattern[, flags[, match_only])
-
Parses a RegExp pattern and returns a tree, potentially throwing.
-
disRegExp(regexp[, match_only[, input]])
-
Dumps RegExp bytecode.
-
-- cgit v1.2.3-54-g00ecf