Browse Source

test: update weak module for gc tests

Previous version of weak used for gc tests emitted a warning on OS X.
Updating to current version eliminates warning.

PR-URL: https://github.com/nodejs/node/pull/7014
Reviewed-By: Ben Noordhuis <info@bnoordhuis.nl>
Reviewed-By: James M Snell <jasnell@gmail.com>
v6.x
Rich Trott 9 years ago
committed by Rod Vagg
parent
commit
dea120f247
  1. 97
      test/gc/node_modules/bindings/README.md
  2. 166
      test/gc/node_modules/bindings/bindings.js
  3. 83
      test/gc/node_modules/bindings/package.json
  4. 13
      test/gc/node_modules/nan/LICENSE.md
  5. 403
      test/gc/node_modules/nan/README.md
  6. 1
      test/gc/node_modules/nan/include_dirs.js
  7. 2271
      test/gc/node_modules/nan/nan.h
  8. 88
      test/gc/node_modules/nan/nan_callbacks.h
  9. 512
      test/gc/node_modules/nan/nan_callbacks_12_inl.h
  10. 506
      test/gc/node_modules/nan/nan_callbacks_pre_12_inl.h
  11. 64
      test/gc/node_modules/nan/nan_converters.h
  12. 42
      test/gc/node_modules/nan/nan_converters_43_inl.h
  13. 42
      test/gc/node_modules/nan/nan_converters_pre_43_inl.h
  14. 404
      test/gc/node_modules/nan/nan_implementation_12_inl.h
  15. 264
      test/gc/node_modules/nan/nan_implementation_pre_12_inl.h
  16. 231
      test/gc/node_modules/nan/nan_maybe_43_inl.h
  17. 303
      test/gc/node_modules/nan/nan_maybe_pre_43_inl.h
  18. 340
      test/gc/node_modules/nan/nan_new.h
  19. 155
      test/gc/node_modules/nan/nan_object_wrap.h
  20. 129
      test/gc/node_modules/nan/nan_persistent_12_inl.h
  21. 242
      test/gc/node_modules/nan/nan_persistent_pre_12_inl.h
  22. 305
      test/gc/node_modules/nan/nan_string_bytes.h
  23. 87
      test/gc/node_modules/nan/nan_typedarray_contents.h
  24. 422
      test/gc/node_modules/nan/nan_weak.h
  25. 121
      test/gc/node_modules/nan/package.json
  26. 412
      test/gc/node_modules/nan/tools/1to2.js
  27. 14
      test/gc/node_modules/nan/tools/README.md
  28. 19
      test/gc/node_modules/nan/tools/package.json
  29. 1
      test/gc/node_modules/weak/.gitignore
  30. 2
      test/gc/node_modules/weak/LICENSE
  31. 91
      test/gc/node_modules/weak/README.md
  32. 49
      test/gc/node_modules/weak/appveyor.yml
  33. 13
      test/gc/node_modules/weak/binding.gyp
  34. 342
      test/gc/node_modules/weak/build/Makefile
  35. 6
      test/gc/node_modules/weak/build/binding.Makefile
  36. 56
      test/gc/node_modules/weak/build/config.gypi
  37. 611
      test/gc/node_modules/weak/build/gyp-mac-tool
  38. 169
      test/gc/node_modules/weak/build/weakref.target.mk
  39. 121
      test/gc/node_modules/weak/lib/weak.js
  40. 102
      test/gc/node_modules/weak/package.json
  41. 371
      test/gc/node_modules/weak/src/weakref.cc

97
test/gc/node_modules/bindings/README.md

@ -0,0 +1,97 @@
node-bindings
=============
### Helper module for loading your native module's .node file
This is a helper module for authors of Node.js native addon modules.
It is basically the "swiss army knife" of `require()`ing your native module's
`.node` file.
Throughout the course of Node's native addon history, addons have ended up being
compiled in a variety of different places, depending on which build tool and which
version of node was used. To make matters worse, now the _gyp_ build tool can
produce either a _Release_ or _Debug_ build, each being built into different
locations.
This module checks _all_ the possible locations that a native addon would be built
at, and returns the first one that loads successfully.
Installation
------------
Install with `npm`:
``` bash
$ npm install bindings
```
Or add it to the `"dependencies"` section of your _package.json_ file.
Example
-------
`require()`ing the proper bindings file for the current node version, platform
and architecture is as simple as:
``` js
var bindings = require('bindings')('binding.node')
// Use your bindings defined in your C files
bindings.your_c_function()
```
Nice Error Output
-----------------
When the `.node` file could not be loaded, `node-bindings` throws an Error with
a nice error message telling you exactly what was tried. You can also check the
`err.tries` Array property.
```
Error: Could not load the bindings file. Tried:
→ /Users/nrajlich/ref/build/binding.node
→ /Users/nrajlich/ref/build/Debug/binding.node
→ /Users/nrajlich/ref/build/Release/binding.node
→ /Users/nrajlich/ref/out/Debug/binding.node
→ /Users/nrajlich/ref/Debug/binding.node
→ /Users/nrajlich/ref/out/Release/binding.node
→ /Users/nrajlich/ref/Release/binding.node
→ /Users/nrajlich/ref/build/default/binding.node
→ /Users/nrajlich/ref/compiled/0.8.2/darwin/x64/binding.node
at bindings (/Users/nrajlich/ref/node_modules/bindings/bindings.js:84:13)
at Object.<anonymous> (/Users/nrajlich/ref/lib/ref.js:5:47)
at Module._compile (module.js:449:26)
at Object.Module._extensions..js (module.js:467:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
...
```
License
-------
(The MIT License)
Copyright (c) 2012 Nathan Rajlich &lt;nathan@tootallnate.net&gt;
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
'Software'), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

166
test/gc/node_modules/bindings/bindings.js

@ -0,0 +1,166 @@
/**
* Module dependencies.
*/
var fs = require('fs')
, path = require('path')
, join = path.join
, dirname = path.dirname
, exists = fs.existsSync || path.existsSync
, defaults = {
arrow: process.env.NODE_BINDINGS_ARROW || ' → '
, compiled: process.env.NODE_BINDINGS_COMPILED_DIR || 'compiled'
, platform: process.platform
, arch: process.arch
, version: process.versions.node
, bindings: 'bindings.node'
, try: [
// node-gyp's linked version in the "build" dir
[ 'module_root', 'build', 'bindings' ]
// node-waf and gyp_addon (a.k.a node-gyp)
, [ 'module_root', 'build', 'Debug', 'bindings' ]
, [ 'module_root', 'build', 'Release', 'bindings' ]
// Debug files, for development (legacy behavior, remove for node v0.9)
, [ 'module_root', 'out', 'Debug', 'bindings' ]
, [ 'module_root', 'Debug', 'bindings' ]
// Release files, but manually compiled (legacy behavior, remove for node v0.9)
, [ 'module_root', 'out', 'Release', 'bindings' ]
, [ 'module_root', 'Release', 'bindings' ]
// Legacy from node-waf, node <= 0.4.x
, [ 'module_root', 'build', 'default', 'bindings' ]
// Production "Release" buildtype binary (meh...)
, [ 'module_root', 'compiled', 'version', 'platform', 'arch', 'bindings' ]
]
}
/**
* The main `bindings()` function loads the compiled bindings for a given module.
* It uses V8's Error API to determine the parent filename that this function is
* being invoked from, which is then used to find the root directory.
*/
function bindings (opts) {
// Argument surgery
if (typeof opts == 'string') {
opts = { bindings: opts }
} else if (!opts) {
opts = {}
}
opts.__proto__ = defaults
// Get the module root
if (!opts.module_root) {
opts.module_root = exports.getRoot(exports.getFileName())
}
// Ensure the given bindings name ends with .node
if (path.extname(opts.bindings) != '.node') {
opts.bindings += '.node'
}
var tries = []
, i = 0
, l = opts.try.length
, n
, b
, err
for (; i<l; i++) {
n = join.apply(null, opts.try[i].map(function (p) {
return opts[p] || p
}))
tries.push(n)
try {
b = opts.path ? require.resolve(n) : require(n)
if (!opts.path) {
b.path = n
}
return b
} catch (e) {
if (!/not find/i.test(e.message)) {
throw e
}
}
}
err = new Error('Could not locate the bindings file. Tried:\n'
+ tries.map(function (a) { return opts.arrow + a }).join('\n'))
err.tries = tries
throw err
}
module.exports = exports = bindings
/**
* Gets the filename of the JavaScript file that invokes this function.
* Used to help find the root directory of a module.
* Optionally accepts an filename argument to skip when searching for the invoking filename
*/
exports.getFileName = function getFileName (calling_file) {
var origPST = Error.prepareStackTrace
, origSTL = Error.stackTraceLimit
, dummy = {}
, fileName
Error.stackTraceLimit = 10
Error.prepareStackTrace = function (e, st) {
for (var i=0, l=st.length; i<l; i++) {
fileName = st[i].getFileName()
if (fileName !== __filename) {
if (calling_file) {
if (fileName !== calling_file) {
return
}
} else {
return
}
}
}
}
// run the 'prepareStackTrace' function above
Error.captureStackTrace(dummy)
dummy.stack
// cleanup
Error.prepareStackTrace = origPST
Error.stackTraceLimit = origSTL
return fileName
}
/**
* Gets the root directory of a module, given an arbitrary filename
* somewhere in the module tree. The "root directory" is the directory
* containing the `package.json` file.
*
* In: /home/nate/node-native-module/lib/index.js
* Out: /home/nate/node-native-module
*/
exports.getRoot = function getRoot (file) {
var dir = dirname(file)
, prev
while (true) {
if (dir === '.') {
// Avoids an infinite loop in rare cases, like the REPL
dir = process.cwd()
}
if (exists(join(dir, 'package.json')) || exists(join(dir, 'node_modules'))) {
// Found the 'package.json' file or 'node_modules' dir; we're done
return dir
}
if (prev === dir) {
// Got to the top
throw new Error('Could not find module root given file: "' + file
+ '". Do you have a `package.json` file? ')
}
// Try the parent dir next
prev = dir
dir = join(dir, '..')
}
}

83
test/gc/node_modules/bindings/package.json

@ -0,0 +1,83 @@
{
"_args": [
[
"bindings@^1.2.1",
"/Users/trott/io.js/test/gc/node_modules/weak"
]
],
"_from": "bindings@>=1.2.1 <2.0.0",
"_id": "bindings@1.2.1",
"_inCache": true,
"_installable": true,
"_location": "/bindings",
"_npmUser": {
"email": "nathan@tootallnate.net",
"name": "tootallnate"
},
"_npmVersion": "1.4.14",
"_phantomChildren": {},
"_requested": {
"name": "bindings",
"raw": "bindings@^1.2.1",
"rawSpec": "^1.2.1",
"scope": null,
"spec": ">=1.2.1 <2.0.0",
"type": "range"
},
"_requiredBy": [
"/weak"
],
"_resolved": "https://registry.npmjs.org/bindings/-/bindings-1.2.1.tgz",
"_shasum": "14ad6113812d2d37d72e67b4cacb4bb726505f11",
"_shrinkwrap": null,
"_spec": "bindings@^1.2.1",
"_where": "/Users/trott/io.js/test/gc/node_modules/weak",
"author": {
"email": "nathan@tootallnate.net",
"name": "Nathan Rajlich",
"url": "http://tootallnate.net"
},
"bugs": {
"url": "https://github.com/TooTallNate/node-bindings/issues"
},
"dependencies": {},
"description": "Helper module for loading your native module's .node file",
"devDependencies": {},
"directories": {},
"dist": {
"shasum": "14ad6113812d2d37d72e67b4cacb4bb726505f11",
"tarball": "https://registry.npmjs.org/bindings/-/bindings-1.2.1.tgz"
},
"gitHead": "e404152ee27f8478ccbc7122ee051246e8e5ec02",
"homepage": "https://github.com/TooTallNate/node-bindings",
"keywords": [
"native",
"addon",
"bindings",
"gyp",
"waf",
"c",
"c++"
],
"license": "MIT",
"main": "./bindings.js",
"maintainers": [
{
"email": "nathan@tootallnate.net",
"name": "TooTallNate"
},
{
"email": "nathan@tootallnate.net",
"name": "tootallnate"
}
],
"name": "bindings",
"optionalDependencies": {},
"readme": "ERROR: No README data found!",
"repository": {
"type": "git",
"url": "git://github.com/TooTallNate/node-bindings.git"
},
"scripts": {},
"version": "1.2.1"
}

13
test/gc/node_modules/nan/LICENSE.md

@ -0,0 +1,13 @@
The MIT License (MIT)
=====================
Copyright (c) 2016 NAN contributors
-----------------------------------
*NAN contributors listed at <https://github.com/nodejs/nan#contributors>*
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

403
test/gc/node_modules/nan/README.md

@ -0,0 +1,403 @@
Native Abstractions for Node.js
===============================
**A header file filled with macro and utility goodness for making add-on development for Node.js easier across versions 0.8, 0.10, 0.12, 1, 4, 5 and 6.**
***Current version: 2.3.3***
*(See [CHANGELOG.md](https://github.com/nodejs/nan/blob/master/CHANGELOG.md) for complete ChangeLog)*
[![NPM](https://nodei.co/npm/nan.png?downloads=true&downloadRank=true)](https://nodei.co/npm/nan/) [![NPM](https://nodei.co/npm-dl/nan.png?months=6&height=3)](https://nodei.co/npm/nan/)
[![Build Status](https://api.travis-ci.org/nodejs/nan.svg?branch=master)](http://travis-ci.org/nodejs/nan)
[![Build status](https://ci.appveyor.com/api/projects/status/kh73pbm9dsju7fgh)](https://ci.appveyor.com/project/RodVagg/nan)
Thanks to the crazy changes in V8 (and some in Node core), keeping native addons compiling happily across versions, particularly 0.10 to 0.12 to 4.0, is a minor nightmare. The goal of this project is to store all logic necessary to develop native Node.js addons without having to inspect `NODE_MODULE_VERSION` and get yourself into a macro-tangle.
This project also contains some helper utilities that make addon development a bit more pleasant.
* **[News & Updates](#news)**
* **[Usage](#usage)**
* **[Example](#example)**
* **[API](#api)**
* **[Tests](#tests)**
* **[Governance & Contributing](#governance)**
<a name="news"></a>
## News & Updates
<a name="usage"></a>
## Usage
Simply add **NAN** as a dependency in the *package.json* of your Node addon:
``` bash
$ npm install --save nan
```
Pull in the path to **NAN** in your *binding.gyp* so that you can use `#include <nan.h>` in your *.cpp* files:
``` python
"include_dirs" : [
"<!(node -e \"require('nan')\")"
]
```
This works like a `-I<path-to-NAN>` when compiling your addon.
<a name="example"></a>
## Example
Just getting started with Nan? Take a look at the **[Node Add-on Examples](https://github.com/nodejs/node-addon-examples)**.
Refer to a [quick-start **Nan** Boilerplate](https://github.com/fcanas/node-native-boilerplate) for a ready-to-go project that utilizes basic Nan functionality.
For a simpler example, see the **[async pi estimation example](https://github.com/nodejs/nan/tree/master/examples/async_pi_estimate)** in the examples directory for full code and an explanation of what this Monte Carlo Pi estimation example does. Below are just some parts of the full example that illustrate the use of **NAN**.
Yet another example is **[nan-example-eol](https://github.com/CodeCharmLtd/nan-example-eol)**. It shows newline detection implemented as a native addon.
Also take a look at our comprehensive **[C++ test suite](https://github.com/nodejs/nan/tree/master/test/cpp)** which has a plehora of code snippets for your pasting pleasure.
<a name="api"></a>
## API
Additional to the NAN documentation below, please consult:
* [The V8 Getting Started Guide](https://developers.google.com/v8/get_started)
* [The V8 Embedders Guide](https://developers.google.com/v8/embed)
* [V8 API Documentation](http://v8docs.nodesource.com/)
* [Node Add-on Documentation](https://nodejs.org/api/addons.html)
<!-- START API -->
### JavaScript-accessible methods
A _template_ is a blueprint for JavaScript functions and objects in a context. You can use a template to wrap C++ functions and data structures within JavaScript objects so that they can be manipulated from JavaScript. See the V8 Embedders Guide section on [Templates](https://developers.google.com/v8/embed#templates) for further information.
In order to expose functionality to JavaScript via a template, you must provide it to V8 in a form that it understands. Across the versions of V8 supported by NAN, JavaScript-accessible method signatures vary widely, NAN fully abstracts method declaration and provides you with an interface that is similar to the most recent V8 API but is backward-compatible with older versions that still use the now-deceased `v8::Argument` type.
* **Method argument types**
- <a href="doc/methods.md#api_nan_function_callback_info"><b><code>Nan::FunctionCallbackInfo</code></b></a>
- <a href="doc/methods.md#api_nan_property_callback_info"><b><code>Nan::PropertyCallbackInfo</code></b></a>
- <a href="doc/methods.md#api_nan_return_value"><b><code>Nan::ReturnValue</code></b></a>
* **Method declarations**
- <a href="doc/methods.md#api_nan_method"><b>Method declaration</b></a>
- <a href="doc/methods.md#api_nan_getter"><b>Getter declaration</b></a>
- <a href="doc/methods.md#api_nan_setter"><b>Setter declaration</b></a>
- <a href="doc/methods.md#api_nan_property_getter"><b>Property getter declaration</b></a>
- <a href="doc/methods.md#api_nan_property_setter"><b>Property setter declaration</b></a>
- <a href="doc/methods.md#api_nan_property_enumerator"><b>Property enumerator declaration</b></a>
- <a href="doc/methods.md#api_nan_property_deleter"><b>Property deleter declaration</b></a>
- <a href="doc/methods.md#api_nan_property_query"><b>Property query declaration</b></a>
- <a href="doc/methods.md#api_nan_index_getter"><b>Index getter declaration</b></a>
- <a href="doc/methods.md#api_nan_index_setter"><b>Index setter declaration</b></a>
- <a href="doc/methods.md#api_nan_index_enumerator"><b>Index enumerator declaration</b></a>
- <a href="doc/methods.md#api_nan_index_deleter"><b>Index deleter declaration</b></a>
- <a href="doc/methods.md#api_nan_index_query"><b>Index query declaration</b></a>
* Method and template helpers
- <a href="doc/methods.md#api_nan_set_method"><b><code>Nan::SetMethod()</code></b></a>
- <a href="doc/methods.md#api_nan_set_prototype_method"><b><code>Nan::SetPrototypeMethod()</code></b></a>
- <a href="doc/methods.md#api_nan_set_accessor"><b><code>Nan::SetAccessor()</code></b></a>
- <a href="doc/methods.md#api_nan_set_named_property_handler"><b><code>Nan::SetNamedPropertyHandler()</code></b></a>
- <a href="doc/methods.md#api_nan_set_indexed_property_handler"><b><code>Nan::SetIndexedPropertyHandler()</code></b></a>
- <a href="doc/methods.md#api_nan_set_template"><b><code>Nan::SetTemplate()</code></b></a>
- <a href="doc/methods.md#api_nan_set_prototype_template"><b><code>Nan::SetPrototypeTemplate()</code></b></a>
- <a href="doc/methods.md#api_nan_set_instance_template"><b><code>Nan::SetInstanceTemplate()</code></b></a>
- <a href="doc/methods.md#api_nan_set_call_handler"><b><code>Nan::SetCallHandler()</code></b></a>
- <a href="doc/methods.md#api_nan_set_call_as_function_handler"><b><code>Nan::SetCallAsFunctionHandler()</code></b></a>
### Scopes
A _local handle_ is a pointer to an object. All V8 objects are accessed using handles, they are necessary because of the way the V8 garbage collector works.
A handle scope can be thought of as a container for any number of handles. When you've finished with your handles, instead of deleting each one individually you can simply delete their scope.
The creation of `HandleScope` objects is different across the supported versions of V8. Therefore, NAN provides its own implementations that can be used safely across these.
- <a href="doc/scopes.md#api_nan_handle_scope"><b><code>Nan::HandleScope</code></b></a>
- <a href="doc/scopes.md#api_nan_escapable_handle_scope"><b><code>Nan::EscapableHandleScope</code></b></a>
Also see the V8 Embedders Guide section on [Handles and Garbage Collection](https://developers.google.com/v8/embed#handles).
### Persistent references
An object reference that is independent of any `HandleScope` is a _persistent_ reference. Where a `Local` handle only lives as long as the `HandleScope` in which it was allocated, a `Persistent` handle remains valid until it is explicitly disposed.
Due to the evolution of the V8 API, it is necessary for NAN to provide a wrapper implementation of the `Persistent` classes to supply compatibility across the V8 versions supported.
- <a href="doc/persistent.md#api_nan_persistent_base"><b><code>Nan::PersistentBase & v8::PersistentBase</code></b></a>
- <a href="doc/persistent.md#api_nan_non_copyable_persistent_traits"><b><code>Nan::NonCopyablePersistentTraits & v8::NonCopyablePersistentTraits</code></b></a>
- <a href="doc/persistent.md#api_nan_copyable_persistent_traits"><b><code>Nan::CopyablePersistentTraits & v8::CopyablePersistentTraits</code></b></a>
- <a href="doc/persistent.md#api_nan_persistent"><b><code>Nan::Persistent</code></b></a>
- <a href="doc/persistent.md#api_nan_global"><b><code>Nan::Global</code></b></a>
- <a href="doc/persistent.md#api_nan_weak_callback_info"><b><code>Nan::WeakCallbackInfo</code></b></a>
- <a href="doc/persistent.md#api_nan_weak_callback_type"><b><code>Nan::WeakCallbackType</code></b></a>
Also see the V8 Embedders Guide section on [Handles and Garbage Collection](https://developers.google.com/v8/embed#handles).
### New
NAN provides a `Nan::New()` helper for the creation of new JavaScript objects in a way that's compatible across the supported versions of V8.
- <a href="doc/new.md#api_nan_new"><b><code>Nan::New()</code></b></a>
- <a href="doc/new.md#api_nan_undefined"><b><code>Nan::Undefined()</code></b></a>
- <a href="doc/new.md#api_nan_null"><b><code>Nan::Null()</code></b></a>
- <a href="doc/new.md#api_nan_true"><b><code>Nan::True()</code></b></a>
- <a href="doc/new.md#api_nan_false"><b><code>Nan::False()</code></b></a>
- <a href="doc/new.md#api_nan_empty_string"><b><code>Nan::EmptyString()</code></b></a>
### Converters
NAN contains functions that convert `v8::Value`s to other `v8::Value` types and native types. Since type conversion is not guaranteed to succeed, they return `Nan::Maybe` types. These converters can be used in place of `value->ToX()` and `value->XValue()` (where `X` is one of the types, e.g. `Boolean`) in a way that provides a consistent interface across V8 versions. Newer versions of V8 use the new `v8::Maybe` and `v8::MaybeLocal` types for these conversions, older versions don't have this functionality so it is provided by NAN.
- <a href="doc/converters.md#api_nan_to"><b><code>Nan::To()</code></b></a>
### Maybe Types
The `Nan::MaybeLocal` and `Nan::Maybe` types are monads that encapsulate `v8::Local` handles that _may be empty_.
* **Maybe Types**
- <a href="doc/maybe_types.md#api_nan_maybe_local"><b><code>Nan::MaybeLocal</code></b></a>
- <a href="doc/maybe_types.md#api_nan_maybe"><b><code>Nan::Maybe</code></b></a>
- <a href="doc/maybe_types.md#api_nan_nothing"><b><code>Nan::Nothing</code></b></a>
- <a href="doc/maybe_types.md#api_nan_just"><b><code>Nan::Just</code></b></a>
* **Maybe Helpers**
- <a href="doc/maybe_types.md#api_nan_call"><b><code>Nan::Call()</code></b></a>
- <a href="doc/maybe_types.md#api_nan_to_detail_string"><b><code>Nan::ToDetailString()</code></b></a>
- <a href="doc/maybe_types.md#api_nan_to_array_index"><b><code>Nan::ToArrayIndex()</code></b></a>
- <a href="doc/maybe_types.md#api_nan_equals"><b><code>Nan::Equals()</code></b></a>
- <a href="doc/maybe_types.md#api_nan_new_instance"><b><code>Nan::NewInstance()</code></b></a>
- <a href="doc/maybe_types.md#api_nan_get_function"><b><code>Nan::GetFunction()</code></b></a>
- <a href="doc/maybe_types.md#api_nan_set"><b><code>Nan::Set()</code></b></a>
- <a href="doc/maybe_types.md#api_nan_force_set"><b><code>Nan::ForceSet()</code></b></a>
- <a href="doc/maybe_types.md#api_nan_get"><b><code>Nan::Get()</code></b></a>
- <a href="doc/maybe_types.md#api_nan_get_property_attribute"><b><code>Nan::GetPropertyAttributes()</code></b></a>
- <a href="doc/maybe_types.md#api_nan_has"><b><code>Nan::Has()</code></b></a>
- <a href="doc/maybe_types.md#api_nan_delete"><b><code>Nan::Delete()</code></b></a>
- <a href="doc/maybe_types.md#api_nan_get_property_names"><b><code>Nan::GetPropertyNames()</code></b></a>
- <a href="doc/maybe_types.md#api_nan_get_own_property_names"><b><code>Nan::GetOwnPropertyNames()</code></b></a>
- <a href="doc/maybe_types.md#api_nan_set_prototype"><b><code>Nan::SetPrototype()</code></b></a>
- <a href="doc/maybe_types.md#api_nan_object_proto_to_string"><b><code>Nan::ObjectProtoToString()</code></b></a>
- <a href="doc/maybe_types.md#api_nan_has_own_property"><b><code>Nan::HasOwnProperty()</code></b></a>
- <a href="doc/maybe_types.md#api_nan_has_real_named_property"><b><code>Nan::HasRealNamedProperty()</code></b></a>
- <a href="doc/maybe_types.md#api_nan_has_real_indexed_property"><b><code>Nan::HasRealIndexedProperty()</code></b></a>
- <a href="doc/maybe_types.md#api_nan_has_real_named_callback_property"><b><code>Nan::HasRealNamedCallbackProperty()</code></b></a>
- <a href="doc/maybe_types.md#api_nan_get_real_named_property_in_prototype_chain"><b><code>Nan::GetRealNamedPropertyInPrototypeChain()</code></b></a>
- <a href="doc/maybe_types.md#api_nan_get_real_named_property"><b><code>Nan::GetRealNamedProperty()</code></b></a>
- <a href="doc/maybe_types.md#api_nan_call_as_function"><b><code>Nan::CallAsFunction()</code></b></a>
- <a href="doc/maybe_types.md#api_nan_call_as_constructor"><b><code>Nan::CallAsConstructor()</code></b></a>
- <a href="doc/maybe_types.md#api_nan_get_source_line"><b><code>Nan::GetSourceLine()</code></b></a>
- <a href="doc/maybe_types.md#api_nan_get_line_number"><b><code>Nan::GetLineNumber()</code></b></a>
- <a href="doc/maybe_types.md#api_nan_get_start_column"><b><code>Nan::GetStartColumn()</code></b></a>
- <a href="doc/maybe_types.md#api_nan_get_end_column"><b><code>Nan::GetEndColumn()</code></b></a>
- <a href="doc/maybe_types.md#api_nan_clone_element_at"><b><code>Nan::CloneElementAt()</code></b></a>
- <a href="doc/maybe_types.md#api_nan_make_maybe"><b><code>Nan::MakeMaybe()</code></b></a>
### Script
NAN provides a `v8::Script` helpers as the API has changed over the supported versions of V8.
- <a href="doc/script.md#api_nan_compile_script"><b><code>Nan::CompileScript()</code></b></a>
- <a href="doc/script.md#api_nan_run_script"><b><code>Nan::RunScript()</code></b></a>
### Errors
NAN includes helpers for creating, throwing and catching Errors as much of this functionality varies across the supported versions of V8 and must be abstracted.
Note that an Error object is simply a specialized form of `v8::Value`.
Also consult the V8 Embedders Guide section on [Exceptions](https://developers.google.com/v8/embed#exceptions) for more information.
- <a href="doc/errors.md#api_nan_error"><b><code>Nan::Error()</code></b></a>
- <a href="doc/errors.md#api_nan_range_error"><b><code>Nan::RangeError()</code></b></a>
- <a href="doc/errors.md#api_nan_reference_error"><b><code>Nan::ReferenceError()</code></b></a>
- <a href="doc/errors.md#api_nan_syntax_error"><b><code>Nan::SyntaxError()</code></b></a>
- <a href="doc/errors.md#api_nan_type_error"><b><code>Nan::TypeError()</code></b></a>
- <a href="doc/errors.md#api_nan_throw_error"><b><code>Nan::ThrowError()</code></b></a>
- <a href="doc/errors.md#api_nan_throw_range_error"><b><code>Nan::ThrowRangeError()</code></b></a>
- <a href="doc/errors.md#api_nan_throw_reference_error"><b><code>Nan::ThrowReferenceError()</code></b></a>
- <a href="doc/errors.md#api_nan_throw_syntax_error"><b><code>Nan::ThrowSyntaxError()</code></b></a>
- <a href="doc/errors.md#api_nan_throw_type_error"><b><code>Nan::ThrowTypeError()</code></b></a>
- <a href="doc/errors.md#api_nan_fatal_exception"><b><code>Nan::FatalException()</code></b></a>
- <a href="doc/errors.md#api_nan_errno_exception"><b><code>Nan::ErrnoException()</code></b></a>
- <a href="doc/errors.md#api_nan_try_catch"><b><code>Nan::TryCatch</code></b></a>
### Buffers
NAN's `node::Buffer` helpers exist as the API has changed across supported Node versions. Use these methods to ensure compatibility.
- <a href="doc/buffers.md#api_nan_new_buffer"><b><code>Nan::NewBuffer()</code></b></a>
- <a href="doc/buffers.md#api_nan_copy_buffer"><b><code>Nan::CopyBuffer()</code></b></a>
- <a href="doc/buffers.md#api_nan_free_callback"><b><code>Nan::FreeCallback()</code></b></a>
### Nan::Callback
`Nan::Callback` makes it easier to use `v8::Function` handles as callbacks. A class that wraps a `v8::Function` handle, protecting it from garbage collection and making it particularly useful for storage and use across asynchronous execution.
- <a href="doc/callback.md#api_nan_callback"><b><code>Nan::Callback</code></b></a>
### Asynchronous work helpers
`Nan::AsyncWorker` and `Nan::AsyncProgressWorker` are helper classes that make working with asynchronous code easier.
- <a href="doc/asyncworker.md#api_nan_async_worker"><b><code>Nan::AsyncWorker</code></b></a>
- <a href="doc/asyncworker.md#api_nan_async_progress_worker"><b><code>Nan::AsyncProgressWorker</code></b></a>
- <a href="doc/asyncworker.md#api_nan_async_queue_worker"><b><code>Nan::AsyncQueueWorker</code></b></a>
### Strings & Bytes
Miscellaneous string & byte encoding and decoding functionality provided for compatibility across supported versions of V8 and Node. Implemented by NAN to ensure that all encoding types are supported, even for older versions of Node where they are missing.
- <a href="doc/string_bytes.md#api_nan_encoding"><b><code>Nan::Encoding</code></b></a>
- <a href="doc/string_bytes.md#api_nan_encode"><b><code>Nan::Encode()</code></b></a>
- <a href="doc/string_bytes.md#api_nan_decode_bytes"><b><code>Nan::DecodeBytes()</code></b></a>
- <a href="doc/string_bytes.md#api_nan_decode_write"><b><code>Nan::DecodeWrite()</code></b></a>
### Object Wrappers
The `ObjectWrap` class can be used to make wrapped C++ objects and a factory of wrapped objects.
- <a href="doc/object_wrappers.md#api_nan_object_wrap"><b><code>Nan::ObjectWrap</code></b></a>
### V8 internals
The hooks to access V8 internals—including GC and statistics—are different across the supported versions of V8, therefore NAN provides its own hooks that call the appropriate V8 methods.
- <a href="doc/v8_internals.md#api_nan_gc_callback"><b><code>NAN_GC_CALLBACK()</code></b></a>
- <a href="doc/v8_internals.md#api_nan_add_gc_epilogue_callback"><b><code>Nan::AddGCEpilogueCallback()</code></b></a>
- <a href="doc/v8_internals.md#api_nan_remove_gc_epilogue_callback"><b><code>Nan::RemoveGCEpilogueCallback()</code></b></a>
- <a href="doc/v8_internals.md#api_nan_add_gc_prologue_callback"><b><code>Nan::AddGCPrologueCallback()</code></b></a>
- <a href="doc/v8_internals.md#api_nan_remove_gc_prologue_callback"><b><code>Nan::RemoveGCPrologueCallback()</code></b></a>
- <a href="doc/v8_internals.md#api_nan_get_heap_statistics"><b><code>Nan::GetHeapStatistics()</code></b></a>
- <a href="doc/v8_internals.md#api_nan_set_counter_function"><b><code>Nan::SetCounterFunction()</code></b></a>
- <a href="doc/v8_internals.md#api_nan_set_create_histogram_function"><b><code>Nan::SetCreateHistogramFunction()</code></b></a>
- <a href="doc/v8_internals.md#api_nan_set_add_histogram_sample_function"><b><code>Nan::SetAddHistogramSampleFunction()</code></b></a>
- <a href="doc/v8_internals.md#api_nan_idle_notification"><b><code>Nan::IdleNotification()</code></b></a>
- <a href="doc/v8_internals.md#api_nan_low_memory_notification"><b><code>Nan::LowMemoryNotification()</code></b></a>
- <a href="doc/v8_internals.md#api_nan_context_disposed_notification"><b><code>Nan::ContextDisposedNotification()</code></b></a>
- <a href="doc/v8_internals.md#api_nan_get_internal_field_pointer"><b><code>Nan::GetInternalFieldPointer()</code></b></a>
- <a href="doc/v8_internals.md#api_nan_set_internal_field_pointer"><b><code>Nan::SetInternalFieldPointer()</code></b></a>
- <a href="doc/v8_internals.md#api_nan_adjust_external_memory"><b><code>Nan::AdjustExternalMemory()</code></b></a>
### Miscellaneous V8 Helpers
- <a href="doc/v8_misc.md#api_nan_utf8_string"><b><code>Nan::Utf8String</code></b></a>
- <a href="doc/v8_misc.md#api_nan_get_current_context"><b><code>Nan::GetCurrentContext()</code></b></a>
- <a href="doc/v8_misc.md#api_nan_set_isolate_data"><b><code>Nan::SetIsolateData()</code></b></a>
- <a href="doc/v8_misc.md#api_nan_get_isolate_data"><b><code>Nan::GetIsolateData()</code></b></a>
- <a href="doc/v8_misc.md#api_nan_typedarray_contents"><b><code>Nan::TypedArrayContents</code></b></a>
### Miscellaneous Node Helpers
- <a href="doc/node_misc.md#api_nan_make_callback"><b><code>Nan::MakeCallback()</code></b></a>
- <a href="doc/node_misc.md#api_nan_module_init"><b><code>NAN_MODULE_INIT()</code></b></a>
- <a href="doc/node_misc.md#api_nan_export"><b><code>Nan::Export()</code></b></a>
<!-- END API -->
<a name="tests"></a>
### Tests
To run the NAN tests do:
``` sh
npm install
npm run-script rebuild-tests
npm test
```
Or just:
``` sh
npm install
make test
```
<a name="governance"></a>
## Governance & Contributing
NAN is governed by the [io.js](https://iojs.org/) Addon API Working Group
### Addon API Working Group (WG)
The NAN project is jointly governed by a Working Group which is responsible for high-level guidance of the project.
Members of the WG are also known as Collaborators, there is no distinction between the two, unlike other io.js projects.
The WG has final authority over this project including:
* Technical direction
* Project governance and process (including this policy)
* Contribution policy
* GitHub repository hosting
* Maintaining the list of additional Collaborators
For the current list of WG members, see the project [README.md](./README.md#collaborators).
Individuals making significant and valuable contributions are made members of the WG and given commit-access to the project. These individuals are identified by the WG and their addition to the WG is discussed via GitHub and requires unanimous consensus amongst those WG members participating in the discussion with a quorum of 50% of WG members required for acceptance of the vote.
_Note:_ If you make a significant contribution and are not considered for commit-access log an issue or contact a WG member directly.
For the current list of WG members / Collaborators, see the project [README.md](./README.md#collaborators).
### Consensus Seeking Process
The WG follows a [Consensus Seeking](http://en.wikipedia.org/wiki/Consensus-seeking_decision-making) decision making model.
Modifications of the contents of the NAN repository are made on a collaborative basis. Anybody with a GitHub account may propose a modification via pull request and it will be considered by the WG. All pull requests must be reviewed and accepted by a WG member with sufficient expertise who is able to take full responsibility for the change. In the case of pull requests proposed by an existing WG member, an additional WG member is required for sign-off. Consensus should be sought if additional WG members participate and there is disagreement around a particular modification.
If a change proposal cannot reach a consensus, a WG member can call for a vote amongst the members of the WG. Simple majority wins.
<a id="developers-certificate-of-origin"></a>
## Developer's Certificate of Origin 1.1
By making a contribution to this project, I certify that:
* (a) The contribution was created in whole or in part by me and I
have the right to submit it under the open source license
indicated in the file; or
* (b) The contribution is based upon previous work that, to the best
of my knowledge, is covered under an appropriate open source
license and I have the right under that license to submit that
work with modifications, whether created in whole or in part
by me, under the same open source license (unless I am
permitted to submit under a different license), as indicated
in the file; or
* (c) The contribution was provided directly to me by some other
person who certified (a), (b) or (c) and I have not modified
it.
* (d) I understand and agree that this project and the contribution
are public and that a record of the contribution (including all
personal information I submit with it, including my sign-off) is
maintained indefinitely and may be redistributed consistent with
this project or the open source license(s) involved.
<a name="collaborators"></a>
### WG Members / Collaborators
<table><tbody>
<tr><th align="left">Rod Vagg</th><td><a href="https://github.com/rvagg">GitHub/rvagg</a></td><td><a href="http://twitter.com/rvagg">Twitter/@rvagg</a></td></tr>
<tr><th align="left">Benjamin Byholm</th><td><a href="https://github.com/kkoopa/">GitHub/kkoopa</a></td><td>-</td></tr>
<tr><th align="left">Trevor Norris</th><td><a href="https://github.com/trevnorris">GitHub/trevnorris</a></td><td><a href="http://twitter.com/trevnorris">Twitter/@trevnorris</a></td></tr>
<tr><th align="left">Nathan Rajlich</th><td><a href="https://github.com/TooTallNate">GitHub/TooTallNate</a></td><td><a href="http://twitter.com/TooTallNate">Twitter/@TooTallNate</a></td></tr>
<tr><th align="left">Brett Lawson</th><td><a href="https://github.com/brett19">GitHub/brett19</a></td><td><a href="http://twitter.com/brett19x">Twitter/@brett19x</a></td></tr>
<tr><th align="left">Ben Noordhuis</th><td><a href="https://github.com/bnoordhuis">GitHub/bnoordhuis</a></td><td><a href="http://twitter.com/bnoordhuis">Twitter/@bnoordhuis</a></td></tr>
<tr><th align="left">David Siegel</th><td><a href="https://github.com/agnat">GitHub/agnat</a></td><td>-</td></tr>
</tbody></table>
## Licence &amp; copyright
Copyright (c) 2016 NAN WG Members / Collaborators (listed above).
Native Abstractions for Node.js is licensed under an MIT license. All rights not explicitly granted in the MIT license are reserved. See the included LICENSE file for more details.

1
test/gc/node_modules/nan/include_dirs.js

@ -0,0 +1 @@
console.log(require('path').relative('.', __dirname));

2271
test/gc/node_modules/nan/nan.h

File diff suppressed because it is too large

88
test/gc/node_modules/nan/nan_callbacks.h

@ -0,0 +1,88 @@
/*********************************************************************
* NAN - Native Abstractions for Node.js
*
* Copyright (c) 2016 NAN contributors
*
* MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md>
********************************************************************/
#ifndef NAN_CALLBACKS_H_
#define NAN_CALLBACKS_H_
template<typename T> class FunctionCallbackInfo;
template<typename T> class PropertyCallbackInfo;
template<typename T> class Global;
typedef void(*FunctionCallback)(const FunctionCallbackInfo<v8::Value>&);
typedef void(*GetterCallback)
(v8::Local<v8::String>, const PropertyCallbackInfo<v8::Value>&);
typedef void(*SetterCallback)(
v8::Local<v8::String>,
v8::Local<v8::Value>,
const PropertyCallbackInfo<void>&);
typedef void(*PropertyGetterCallback)(
v8::Local<v8::String>,
const PropertyCallbackInfo<v8::Value>&);
typedef void(*PropertySetterCallback)(
v8::Local<v8::String>,
v8::Local<v8::Value>,
const PropertyCallbackInfo<v8::Value>&);
typedef void(*PropertyEnumeratorCallback)
(const PropertyCallbackInfo<v8::Array>&);
typedef void(*PropertyDeleterCallback)(
v8::Local<v8::String>,
const PropertyCallbackInfo<v8::Boolean>&);
typedef void(*PropertyQueryCallback)(
v8::Local<v8::String>,
const PropertyCallbackInfo<v8::Integer>&);
typedef void(*IndexGetterCallback)(
uint32_t,
const PropertyCallbackInfo<v8::Value>&);
typedef void(*IndexSetterCallback)(
uint32_t,
v8::Local<v8::Value>,
const PropertyCallbackInfo<v8::Value>&);
typedef void(*IndexEnumeratorCallback)
(const PropertyCallbackInfo<v8::Array>&);
typedef void(*IndexDeleterCallback)(
uint32_t,
const PropertyCallbackInfo<v8::Boolean>&);
typedef void(*IndexQueryCallback)(
uint32_t,
const PropertyCallbackInfo<v8::Integer>&);
namespace imp {
typedef v8::Local<v8::AccessorSignature> Sig;
static const int kDataIndex = 0;
static const int kFunctionIndex = 1;
static const int kFunctionFieldCount = 2;
static const int kGetterIndex = 1;
static const int kSetterIndex = 2;
static const int kAccessorFieldCount = 3;
static const int kPropertyGetterIndex = 1;
static const int kPropertySetterIndex = 2;
static const int kPropertyEnumeratorIndex = 3;
static const int kPropertyDeleterIndex = 4;
static const int kPropertyQueryIndex = 5;
static const int kPropertyFieldCount = 6;
static const int kIndexPropertyGetterIndex = 1;
static const int kIndexPropertySetterIndex = 2;
static const int kIndexPropertyEnumeratorIndex = 3;
static const int kIndexPropertyDeleterIndex = 4;
static const int kIndexPropertyQueryIndex = 5;
static const int kIndexPropertyFieldCount = 6;
} // end of namespace imp
#if NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION
# include "nan_callbacks_12_inl.h" // NOLINT(build/include)
#else
# include "nan_callbacks_pre_12_inl.h" // NOLINT(build/include)
#endif
#endif // NAN_CALLBACKS_H_

512
test/gc/node_modules/nan/nan_callbacks_12_inl.h

@ -0,0 +1,512 @@
/*********************************************************************
* NAN - Native Abstractions for Node.js
*
* Copyright (c) 2016 NAN contributors
*
* MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md>
********************************************************************/
#ifndef NAN_CALLBACKS_12_INL_H_
#define NAN_CALLBACKS_12_INL_H_
template<typename T>
class ReturnValue {
v8::ReturnValue<T> value_;
public:
template <class S>
explicit inline ReturnValue(const v8::ReturnValue<S> &value) :
value_(value) {}
template <class S>
explicit inline ReturnValue(const ReturnValue<S>& that)
: value_(that.value_) {
TYPE_CHECK(T, S);
}
// Handle setters
template <typename S> inline void Set(const v8::Local<S> &handle) {
TYPE_CHECK(T, S);
value_.Set(handle);
}
template <typename S> inline void Set(const Global<S> &handle) {
TYPE_CHECK(T, S);
#if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 || \
(V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && \
(V8_MINOR_VERSION > 5 || (V8_MINOR_VERSION == 5 && \
defined(V8_BUILD_NUMBER) && V8_BUILD_NUMBER >= 8))))
value_.Set(handle);
#else
value_.Set(*reinterpret_cast<const v8::Persistent<S>*>(&handle));
const_cast<Global<S> &>(handle).Reset();
#endif
}
// Fast primitive setters
inline void Set(bool value) {
TYPE_CHECK(T, v8::Boolean);
value_.Set(value);
}
inline void Set(double i) {
TYPE_CHECK(T, v8::Number);
value_.Set(i);
}
inline void Set(int32_t i) {
TYPE_CHECK(T, v8::Integer);
value_.Set(i);
}
inline void Set(uint32_t i) {
TYPE_CHECK(T, v8::Integer);
value_.Set(i);
}
// Fast JS primitive setters
inline void SetNull() {
TYPE_CHECK(T, v8::Primitive);
value_.SetNull();
}
inline void SetUndefined() {
TYPE_CHECK(T, v8::Primitive);
value_.SetUndefined();
}
inline void SetEmptyString() {
TYPE_CHECK(T, v8::String);
value_.SetEmptyString();
}
// Convenience getter for isolate
inline v8::Isolate *GetIsolate() const {
return value_.GetIsolate();
}
// Pointer setter: Uncompilable to prevent inadvertent misuse.
template<typename S>
inline void Set(S *whatever) { TYPE_CHECK(S*, v8::Primitive); }
};
template<typename T>
class FunctionCallbackInfo {
const v8::FunctionCallbackInfo<T> &info_;
const v8::Local<v8::Value> data_;
public:
explicit inline FunctionCallbackInfo(
const v8::FunctionCallbackInfo<T> &info
, v8::Local<v8::Value> data) :
info_(info)
, data_(data) {}
inline ReturnValue<T> GetReturnValue() const {
return ReturnValue<T>(info_.GetReturnValue());
}
inline v8::Local<v8::Function> Callee() const { return info_.Callee(); }
inline v8::Local<v8::Value> Data() const { return data_; }
inline v8::Local<v8::Object> Holder() const { return info_.Holder(); }
inline bool IsConstructCall() const { return info_.IsConstructCall(); }
inline int Length() const { return info_.Length(); }
inline v8::Local<v8::Value> operator[](int i) const { return info_[i]; }
inline v8::Local<v8::Object> This() const { return info_.This(); }
inline v8::Isolate *GetIsolate() const { return info_.GetIsolate(); }
protected:
static const int kHolderIndex = 0;
static const int kIsolateIndex = 1;
static const int kReturnValueDefaultValueIndex = 2;
static const int kReturnValueIndex = 3;
static const int kDataIndex = 4;
static const int kCalleeIndex = 5;
static const int kContextSaveIndex = 6;
static const int kArgsLength = 7;
private:
NAN_DISALLOW_ASSIGN_COPY_MOVE(FunctionCallbackInfo)
};
template<typename T>
class PropertyCallbackInfo {
const v8::PropertyCallbackInfo<T> &info_;
const v8::Local<v8::Value> data_;
public:
explicit inline PropertyCallbackInfo(
const v8::PropertyCallbackInfo<T> &info
, const v8::Local<v8::Value> data) :
info_(info)
, data_(data) {}
inline v8::Isolate* GetIsolate() const { return info_.GetIsolate(); }
inline v8::Local<v8::Value> Data() const { return data_; }
inline v8::Local<v8::Object> This() const { return info_.This(); }
inline v8::Local<v8::Object> Holder() const { return info_.Holder(); }
inline ReturnValue<T> GetReturnValue() const {
return ReturnValue<T>(info_.GetReturnValue());
}
protected:
static const int kHolderIndex = 0;
static const int kIsolateIndex = 1;
static const int kReturnValueDefaultValueIndex = 2;
static const int kReturnValueIndex = 3;
static const int kDataIndex = 4;
static const int kThisIndex = 5;
static const int kArgsLength = 6;
private:
NAN_DISALLOW_ASSIGN_COPY_MOVE(PropertyCallbackInfo)
};
namespace imp {
static
void FunctionCallbackWrapper(const v8::FunctionCallbackInfo<v8::Value> &info) {
v8::Local<v8::Object> obj = info.Data().As<v8::Object>();
FunctionCallback callback = reinterpret_cast<FunctionCallback>(
reinterpret_cast<intptr_t>(
obj->GetInternalField(kFunctionIndex).As<v8::External>()->Value()));
FunctionCallbackInfo<v8::Value>
cbinfo(info, obj->GetInternalField(kDataIndex));
callback(cbinfo);
}
typedef void (*NativeFunction)(const v8::FunctionCallbackInfo<v8::Value> &);
#if NODE_MODULE_VERSION > NODE_0_12_MODULE_VERSION
static
void GetterCallbackWrapper(
v8::Local<v8::Name> property
, const v8::PropertyCallbackInfo<v8::Value> &info) {
v8::Local<v8::Object> obj = info.Data().As<v8::Object>();
PropertyCallbackInfo<v8::Value>
cbinfo(info, obj->GetInternalField(kDataIndex));
GetterCallback callback = reinterpret_cast<GetterCallback>(
reinterpret_cast<intptr_t>(
obj->GetInternalField(kGetterIndex).As<v8::External>()->Value()));
callback(property.As<v8::String>(), cbinfo);
}
typedef void (*NativeGetter)
(v8::Local<v8::Name>, const v8::PropertyCallbackInfo<v8::Value> &);
static
void SetterCallbackWrapper(
v8::Local<v8::Name> property
, v8::Local<v8::Value> value
, const v8::PropertyCallbackInfo<void> &info) {
v8::Local<v8::Object> obj = info.Data().As<v8::Object>();
PropertyCallbackInfo<void>
cbinfo(info, obj->GetInternalField(kDataIndex));
SetterCallback callback = reinterpret_cast<SetterCallback>(
reinterpret_cast<intptr_t>(
obj->GetInternalField(kSetterIndex).As<v8::External>()->Value()));
callback(property.As<v8::String>(), value, cbinfo);
}
typedef void (*NativeSetter)(
v8::Local<v8::Name>
, v8::Local<v8::Value>
, const v8::PropertyCallbackInfo<void> &);
#else
static
void GetterCallbackWrapper(
v8::Local<v8::String> property
, const v8::PropertyCallbackInfo<v8::Value> &info) {
v8::Local<v8::Object> obj = info.Data().As<v8::Object>();
PropertyCallbackInfo<v8::Value>
cbinfo(info, obj->GetInternalField(kDataIndex));
GetterCallback callback = reinterpret_cast<GetterCallback>(
reinterpret_cast<intptr_t>(
obj->GetInternalField(kGetterIndex).As<v8::External>()->Value()));
callback(property, cbinfo);
}
typedef void (*NativeGetter)
(v8::Local<v8::String>, const v8::PropertyCallbackInfo<v8::Value> &);
static
void SetterCallbackWrapper(
v8::Local<v8::String> property
, v8::Local<v8::Value> value
, const v8::PropertyCallbackInfo<void> &info) {
v8::Local<v8::Object> obj = info.Data().As<v8::Object>();
PropertyCallbackInfo<void>
cbinfo(info, obj->GetInternalField(kDataIndex));
SetterCallback callback = reinterpret_cast<SetterCallback>(
reinterpret_cast<intptr_t>(
obj->GetInternalField(kSetterIndex).As<v8::External>()->Value()));
callback(property, value, cbinfo);
}
typedef void (*NativeSetter)(
v8::Local<v8::String>
, v8::Local<v8::Value>
, const v8::PropertyCallbackInfo<void> &);
#endif
#if NODE_MODULE_VERSION > NODE_0_12_MODULE_VERSION
static
void PropertyGetterCallbackWrapper(
v8::Local<v8::Name> property
, const v8::PropertyCallbackInfo<v8::Value> &info) {
v8::Local<v8::Object> obj = info.Data().As<v8::Object>();
PropertyCallbackInfo<v8::Value>
cbinfo(info, obj->GetInternalField(kDataIndex));
PropertyGetterCallback callback = reinterpret_cast<PropertyGetterCallback>(
reinterpret_cast<intptr_t>(
obj->GetInternalField(kPropertyGetterIndex)
.As<v8::External>()->Value()));
callback(property.As<v8::String>(), cbinfo);
}
typedef void (*NativePropertyGetter)
(v8::Local<v8::Name>, const v8::PropertyCallbackInfo<v8::Value> &);
static
void PropertySetterCallbackWrapper(
v8::Local<v8::Name> property
, v8::Local<v8::Value> value
, const v8::PropertyCallbackInfo<v8::Value> &info) {
v8::Local<v8::Object> obj = info.Data().As<v8::Object>();
PropertyCallbackInfo<v8::Value>
cbinfo(info, obj->GetInternalField(kDataIndex));
PropertySetterCallback callback = reinterpret_cast<PropertySetterCallback>(
reinterpret_cast<intptr_t>(
obj->GetInternalField(kPropertySetterIndex)
.As<v8::External>()->Value()));
callback(property.As<v8::String>(), value, cbinfo);
}
typedef void (*NativePropertySetter)(
v8::Local<v8::Name>
, v8::Local<v8::Value>
, const v8::PropertyCallbackInfo<v8::Value> &);
static
void PropertyEnumeratorCallbackWrapper(
const v8::PropertyCallbackInfo<v8::Array> &info) {
v8::Local<v8::Object> obj = info.Data().As<v8::Object>();
PropertyCallbackInfo<v8::Array>
cbinfo(info, obj->GetInternalField(kDataIndex));
PropertyEnumeratorCallback callback =
reinterpret_cast<PropertyEnumeratorCallback>(reinterpret_cast<intptr_t>(
obj->GetInternalField(kPropertyEnumeratorIndex)
.As<v8::External>()->Value()));
callback(cbinfo);
}
typedef void (*NativePropertyEnumerator)
(const v8::PropertyCallbackInfo<v8::Array> &);
static
void PropertyDeleterCallbackWrapper(
v8::Local<v8::Name> property
, const v8::PropertyCallbackInfo<v8::Boolean> &info) {
v8::Local<v8::Object> obj = info.Data().As<v8::Object>();
PropertyCallbackInfo<v8::Boolean>
cbinfo(info, obj->GetInternalField(kDataIndex));
PropertyDeleterCallback callback = reinterpret_cast<PropertyDeleterCallback>(
reinterpret_cast<intptr_t>(
obj->GetInternalField(kPropertyDeleterIndex)
.As<v8::External>()->Value()));
callback(property.As<v8::String>(), cbinfo);
}
typedef void (NativePropertyDeleter)
(v8::Local<v8::Name>, const v8::PropertyCallbackInfo<v8::Boolean> &);
static
void PropertyQueryCallbackWrapper(
v8::Local<v8::Name> property
, const v8::PropertyCallbackInfo<v8::Integer> &info) {
v8::Local<v8::Object> obj = info.Data().As<v8::Object>();
PropertyCallbackInfo<v8::Integer>
cbinfo(info, obj->GetInternalField(kDataIndex));
PropertyQueryCallback callback = reinterpret_cast<PropertyQueryCallback>(
reinterpret_cast<intptr_t>(
obj->GetInternalField(kPropertyQueryIndex)
.As<v8::External>()->Value()));
callback(property.As<v8::String>(), cbinfo);
}
typedef void (*NativePropertyQuery)
(v8::Local<v8::Name>, const v8::PropertyCallbackInfo<v8::Integer> &);
#else
static
void PropertyGetterCallbackWrapper(
v8::Local<v8::String> property
, const v8::PropertyCallbackInfo<v8::Value> &info) {
v8::Local<v8::Object> obj = info.Data().As<v8::Object>();
PropertyCallbackInfo<v8::Value>
cbinfo(info, obj->GetInternalField(kDataIndex));
PropertyGetterCallback callback = reinterpret_cast<PropertyGetterCallback>(
reinterpret_cast<intptr_t>(
obj->GetInternalField(kPropertyGetterIndex)
.As<v8::External>()->Value()));
callback(property, cbinfo);
}
typedef void (*NativePropertyGetter)
(v8::Local<v8::String>, const v8::PropertyCallbackInfo<v8::Value> &);
static
void PropertySetterCallbackWrapper(
v8::Local<v8::String> property
, v8::Local<v8::Value> value
, const v8::PropertyCallbackInfo<v8::Value> &info) {
v8::Local<v8::Object> obj = info.Data().As<v8::Object>();
PropertyCallbackInfo<v8::Value>
cbinfo(info, obj->GetInternalField(kDataIndex));
PropertySetterCallback callback = reinterpret_cast<PropertySetterCallback>(
reinterpret_cast<intptr_t>(
obj->GetInternalField(kPropertySetterIndex)
.As<v8::External>()->Value()));
callback(property, value, cbinfo);
}
typedef void (*NativePropertySetter)(
v8::Local<v8::String>
, v8::Local<v8::Value>
, const v8::PropertyCallbackInfo<v8::Value> &);
static
void PropertyEnumeratorCallbackWrapper(
const v8::PropertyCallbackInfo<v8::Array> &info) {
v8::Local<v8::Object> obj = info.Data().As<v8::Object>();
PropertyCallbackInfo<v8::Array>
cbinfo(info, obj->GetInternalField(kDataIndex));
PropertyEnumeratorCallback callback =
reinterpret_cast<PropertyEnumeratorCallback>(reinterpret_cast<intptr_t>(
obj->GetInternalField(kPropertyEnumeratorIndex)
.As<v8::External>()->Value()));
callback(cbinfo);
}
typedef void (*NativePropertyEnumerator)
(const v8::PropertyCallbackInfo<v8::Array> &);
static
void PropertyDeleterCallbackWrapper(
v8::Local<v8::String> property
, const v8::PropertyCallbackInfo<v8::Boolean> &info) {
v8::Local<v8::Object> obj = info.Data().As<v8::Object>();
PropertyCallbackInfo<v8::Boolean>
cbinfo(info, obj->GetInternalField(kDataIndex));
PropertyDeleterCallback callback = reinterpret_cast<PropertyDeleterCallback>(
reinterpret_cast<intptr_t>(
obj->GetInternalField(kPropertyDeleterIndex)
.As<v8::External>()->Value()));
callback(property, cbinfo);
}
typedef void (NativePropertyDeleter)
(v8::Local<v8::String>, const v8::PropertyCallbackInfo<v8::Boolean> &);
static
void PropertyQueryCallbackWrapper(
v8::Local<v8::String> property
, const v8::PropertyCallbackInfo<v8::Integer> &info) {
v8::Local<v8::Object> obj = info.Data().As<v8::Object>();
PropertyCallbackInfo<v8::Integer>
cbinfo(info, obj->GetInternalField(kDataIndex));
PropertyQueryCallback callback = reinterpret_cast<PropertyQueryCallback>(
reinterpret_cast<intptr_t>(
obj->GetInternalField(kPropertyQueryIndex)
.As<v8::External>()->Value()));
callback(property, cbinfo);
}
typedef void (*NativePropertyQuery)
(v8::Local<v8::String>, const v8::PropertyCallbackInfo<v8::Integer> &);
#endif
static
void IndexGetterCallbackWrapper(
uint32_t index, const v8::PropertyCallbackInfo<v8::Value> &info) {
v8::Local<v8::Object> obj = info.Data().As<v8::Object>();
PropertyCallbackInfo<v8::Value>
cbinfo(info, obj->GetInternalField(kDataIndex));
IndexGetterCallback callback = reinterpret_cast<IndexGetterCallback>(
reinterpret_cast<intptr_t>(
obj->GetInternalField(kIndexPropertyGetterIndex)
.As<v8::External>()->Value()));
callback(index, cbinfo);
}
typedef void (*NativeIndexGetter)
(uint32_t, const v8::PropertyCallbackInfo<v8::Value> &);
static
void IndexSetterCallbackWrapper(
uint32_t index
, v8::Local<v8::Value> value
, const v8::PropertyCallbackInfo<v8::Value> &info) {
v8::Local<v8::Object> obj = info.Data().As<v8::Object>();
PropertyCallbackInfo<v8::Value>
cbinfo(info, obj->GetInternalField(kDataIndex));
IndexSetterCallback callback = reinterpret_cast<IndexSetterCallback>(
reinterpret_cast<intptr_t>(
obj->GetInternalField(kIndexPropertySetterIndex)
.As<v8::External>()->Value()));
callback(index, value, cbinfo);
}
typedef void (*NativeIndexSetter)(
uint32_t
, v8::Local<v8::Value>
, const v8::PropertyCallbackInfo<v8::Value> &);
static
void IndexEnumeratorCallbackWrapper(
const v8::PropertyCallbackInfo<v8::Array> &info) {
v8::Local<v8::Object> obj = info.Data().As<v8::Object>();
PropertyCallbackInfo<v8::Array>
cbinfo(info, obj->GetInternalField(kDataIndex));
IndexEnumeratorCallback callback = reinterpret_cast<IndexEnumeratorCallback>(
reinterpret_cast<intptr_t>(
obj->GetInternalField(
kIndexPropertyEnumeratorIndex).As<v8::External>()->Value()));
callback(cbinfo);
}
typedef void (*NativeIndexEnumerator)
(const v8::PropertyCallbackInfo<v8::Array> &);
static
void IndexDeleterCallbackWrapper(
uint32_t index, const v8::PropertyCallbackInfo<v8::Boolean> &info) {
v8::Local<v8::Object> obj = info.Data().As<v8::Object>();
PropertyCallbackInfo<v8::Boolean>
cbinfo(info, obj->GetInternalField(kDataIndex));
IndexDeleterCallback callback = reinterpret_cast<IndexDeleterCallback>(
reinterpret_cast<intptr_t>(
obj->GetInternalField(kIndexPropertyDeleterIndex)
.As<v8::External>()->Value()));
callback(index, cbinfo);
}
typedef void (*NativeIndexDeleter)
(uint32_t, const v8::PropertyCallbackInfo<v8::Boolean> &);
static
void IndexQueryCallbackWrapper(
uint32_t index, const v8::PropertyCallbackInfo<v8::Integer> &info) {
v8::Local<v8::Object> obj = info.Data().As<v8::Object>();
PropertyCallbackInfo<v8::Integer>
cbinfo(info, obj->GetInternalField(kDataIndex));
IndexQueryCallback callback = reinterpret_cast<IndexQueryCallback>(
reinterpret_cast<intptr_t>(
obj->GetInternalField(kIndexPropertyQueryIndex)
.As<v8::External>()->Value()));
callback(index, cbinfo);
}
typedef void (*NativeIndexQuery)
(uint32_t, const v8::PropertyCallbackInfo<v8::Integer> &);
} // end of namespace imp
#endif // NAN_CALLBACKS_12_INL_H_

506
test/gc/node_modules/nan/nan_callbacks_pre_12_inl.h

@ -0,0 +1,506 @@
/*********************************************************************
* NAN - Native Abstractions for Node.js
*
* Copyright (c) 2016 NAN contributors
*
* MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md>
********************************************************************/
#ifndef NAN_CALLBACKS_PRE_12_INL_H_
#define NAN_CALLBACKS_PRE_12_INL_H_
namespace imp {
template<typename T> class ReturnValueImp;
} // end of namespace imp
template<typename T>
class ReturnValue {
v8::Isolate *isolate_;
v8::Persistent<T> *value_;
friend class imp::ReturnValueImp<T>;
public:
template <class S>
explicit inline ReturnValue(v8::Isolate *isolate, v8::Persistent<S> *p) :
isolate_(isolate), value_(p) {}
template <class S>
explicit inline ReturnValue(const ReturnValue<S>& that)
: isolate_(that.isolate_), value_(that.value_) {
TYPE_CHECK(T, S);
}
// Handle setters
template <typename S> inline void Set(const v8::Local<S> &handle) {
TYPE_CHECK(T, S);
value_->Dispose();
*value_ = v8::Persistent<T>::New(handle);
}
template <typename S> inline void Set(const Global<S> &handle) {
TYPE_CHECK(T, S);
value_->Dispose();
*value_ = v8::Persistent<T>::New(handle.persistent);
const_cast<Global<S> &>(handle).Reset();
}
// Fast primitive setters
inline void Set(bool value) {
TYPE_CHECK(T, v8::Boolean);
value_->Dispose();
*value_ = v8::Persistent<T>::New(v8::Boolean::New(value));
}
inline void Set(double i) {
TYPE_CHECK(T, v8::Number);
value_->Dispose();
*value_ = v8::Persistent<T>::New(v8::Number::New(i));
}
inline void Set(int32_t i) {
TYPE_CHECK(T, v8::Integer);
value_->Dispose();
*value_ = v8::Persistent<T>::New(v8::Int32::New(i));
}
inline void Set(uint32_t i) {
TYPE_CHECK(T, v8::Integer);
value_->Dispose();
*value_ = v8::Persistent<T>::New(v8::Uint32::NewFromUnsigned(i));
}
// Fast JS primitive setters
inline void SetNull() {
TYPE_CHECK(T, v8::Primitive);
value_->Dispose();
*value_ = v8::Persistent<T>::New(v8::Null());
}
inline void SetUndefined() {
TYPE_CHECK(T, v8::Primitive);
value_->Dispose();
*value_ = v8::Persistent<T>::New(v8::Undefined());
}
inline void SetEmptyString() {
TYPE_CHECK(T, v8::String);
value_->Dispose();
*value_ = v8::Persistent<T>::New(v8::String::Empty());
}
// Convenience getter for isolate
inline v8::Isolate *GetIsolate() const {
return isolate_;
}
// Pointer setter: Uncompilable to prevent inadvertent misuse.
template<typename S>
inline void Set(S *whatever) { TYPE_CHECK(S*, v8::Primitive); }
};
template<typename T>
class FunctionCallbackInfo {
const v8::Arguments &args_;
v8::Local<v8::Value> data_;
ReturnValue<T> return_value_;
v8::Persistent<T> retval_;
public:
explicit inline FunctionCallbackInfo(
const v8::Arguments &args
, v8::Local<v8::Value> data) :
args_(args)
, data_(data)
, return_value_(args.GetIsolate(), &retval_)
, retval_(v8::Persistent<T>::New(v8::Undefined())) {}
inline ~FunctionCallbackInfo() {
retval_.Dispose();
retval_.Clear();
}
inline ReturnValue<T> GetReturnValue() const {
return ReturnValue<T>(return_value_);
}
inline v8::Local<v8::Function> Callee() const { return args_.Callee(); }
inline v8::Local<v8::Value> Data() const { return data_; }
inline v8::Local<v8::Object> Holder() const { return args_.Holder(); }
inline bool IsConstructCall() const { return args_.IsConstructCall(); }
inline int Length() const { return args_.Length(); }
inline v8::Local<v8::Value> operator[](int i) const { return args_[i]; }
inline v8::Local<v8::Object> This() const { return args_.This(); }
inline v8::Isolate *GetIsolate() const { return args_.GetIsolate(); }
protected:
static const int kHolderIndex = 0;
static const int kIsolateIndex = 1;
static const int kReturnValueDefaultValueIndex = 2;
static const int kReturnValueIndex = 3;
static const int kDataIndex = 4;
static const int kCalleeIndex = 5;
static const int kContextSaveIndex = 6;
static const int kArgsLength = 7;
private:
NAN_DISALLOW_ASSIGN_COPY_MOVE(FunctionCallbackInfo)
};
template<typename T>
class PropertyCallbackInfoBase {
const v8::AccessorInfo &info_;
const v8::Local<v8::Value> data_;
public:
explicit inline PropertyCallbackInfoBase(
const v8::AccessorInfo &info
, const v8::Local<v8::Value> data) :
info_(info)
, data_(data) {}
inline v8::Isolate* GetIsolate() const { return info_.GetIsolate(); }
inline v8::Local<v8::Value> Data() const { return data_; }
inline v8::Local<v8::Object> This() const { return info_.This(); }
inline v8::Local<v8::Object> Holder() const { return info_.Holder(); }
protected:
static const int kHolderIndex = 0;
static const int kIsolateIndex = 1;
static const int kReturnValueDefaultValueIndex = 2;
static const int kReturnValueIndex = 3;
static const int kDataIndex = 4;
static const int kThisIndex = 5;
static const int kArgsLength = 6;
private:
NAN_DISALLOW_ASSIGN_COPY_MOVE(PropertyCallbackInfoBase)
};
template<typename T>
class PropertyCallbackInfo : public PropertyCallbackInfoBase<T> {
ReturnValue<T> return_value_;
v8::Persistent<T> retval_;
public:
explicit inline PropertyCallbackInfo(
const v8::AccessorInfo &info
, const v8::Local<v8::Value> data) :
PropertyCallbackInfoBase<T>(info, data)
, return_value_(info.GetIsolate(), &retval_)
, retval_(v8::Persistent<T>::New(v8::Undefined())) {}
inline ~PropertyCallbackInfo() {
retval_.Dispose();
retval_.Clear();
}
inline ReturnValue<T> GetReturnValue() const { return return_value_; }
};
template<>
class PropertyCallbackInfo<v8::Array> :
public PropertyCallbackInfoBase<v8::Array> {
ReturnValue<v8::Array> return_value_;
v8::Persistent<v8::Array> retval_;
public:
explicit inline PropertyCallbackInfo(
const v8::AccessorInfo &info
, const v8::Local<v8::Value> data) :
PropertyCallbackInfoBase<v8::Array>(info, data)
, return_value_(info.GetIsolate(), &retval_)
, retval_(v8::Persistent<v8::Array>::New(v8::Local<v8::Array>())) {}
inline ~PropertyCallbackInfo() {
retval_.Dispose();
retval_.Clear();
}
inline ReturnValue<v8::Array> GetReturnValue() const {
return return_value_;
}
};
template<>
class PropertyCallbackInfo<v8::Boolean> :
public PropertyCallbackInfoBase<v8::Boolean> {
ReturnValue<v8::Boolean> return_value_;
v8::Persistent<v8::Boolean> retval_;
public:
explicit inline PropertyCallbackInfo(
const v8::AccessorInfo &info
, const v8::Local<v8::Value> data) :
PropertyCallbackInfoBase<v8::Boolean>(info, data)
, return_value_(info.GetIsolate(), &retval_)
, retval_(v8::Persistent<v8::Boolean>::New(v8::Local<v8::Boolean>())) {}
inline ~PropertyCallbackInfo() {
retval_.Dispose();
retval_.Clear();
}
inline ReturnValue<v8::Boolean> GetReturnValue() const {
return return_value_;
}
};
template<>
class PropertyCallbackInfo<v8::Integer> :
public PropertyCallbackInfoBase<v8::Integer> {
ReturnValue<v8::Integer> return_value_;
v8::Persistent<v8::Integer> retval_;
public:
explicit inline PropertyCallbackInfo(
const v8::AccessorInfo &info
, const v8::Local<v8::Value> data) :
PropertyCallbackInfoBase<v8::Integer>(info, data)
, return_value_(info.GetIsolate(), &retval_)
, retval_(v8::Persistent<v8::Integer>::New(v8::Local<v8::Integer>())) {}
inline ~PropertyCallbackInfo() {
retval_.Dispose();
retval_.Clear();
}
inline ReturnValue<v8::Integer> GetReturnValue() const {
return return_value_;
}
};
namespace imp {
template<typename T>
class ReturnValueImp : public ReturnValue<T> {
public:
explicit ReturnValueImp(ReturnValue<T> that) :
ReturnValue<T>(that) {}
NAN_INLINE v8::Handle<T> Value() {
return *ReturnValue<T>::value_;
}
};
static
v8::Handle<v8::Value> FunctionCallbackWrapper(const v8::Arguments &args) {
v8::Local<v8::Object> obj = args.Data().As<v8::Object>();
FunctionCallback callback = reinterpret_cast<FunctionCallback>(
reinterpret_cast<intptr_t>(
obj->GetInternalField(kFunctionIndex).As<v8::External>()->Value()));
FunctionCallbackInfo<v8::Value>
cbinfo(args, obj->GetInternalField(kDataIndex));
callback(cbinfo);
return ReturnValueImp<v8::Value>(cbinfo.GetReturnValue()).Value();
}
typedef v8::Handle<v8::Value> (*NativeFunction)(const v8::Arguments &);
static
v8::Handle<v8::Value> GetterCallbackWrapper(
v8::Local<v8::String> property, const v8::AccessorInfo &info) {
v8::Local<v8::Object> obj = info.Data().As<v8::Object>();
PropertyCallbackInfo<v8::Value>
cbinfo(info, obj->GetInternalField(kDataIndex));
GetterCallback callback = reinterpret_cast<GetterCallback>(
reinterpret_cast<intptr_t>(
obj->GetInternalField(kGetterIndex).As<v8::External>()->Value()));
callback(property, cbinfo);
return ReturnValueImp<v8::Value>(cbinfo.GetReturnValue()).Value();
}
typedef v8::Handle<v8::Value> (*NativeGetter)
(v8::Local<v8::String>, const v8::AccessorInfo &);
static
void SetterCallbackWrapper(
v8::Local<v8::String> property
, v8::Local<v8::Value> value
, const v8::AccessorInfo &info) {
v8::Local<v8::Object> obj = info.Data().As<v8::Object>();
PropertyCallbackInfo<void>
cbinfo(info, obj->GetInternalField(kDataIndex));
SetterCallback callback = reinterpret_cast<SetterCallback>(
reinterpret_cast<intptr_t>(
obj->GetInternalField(kSetterIndex).As<v8::External>()->Value()));
callback(property, value, cbinfo);
}
typedef void (*NativeSetter)
(v8::Local<v8::String>, v8::Local<v8::Value>, const v8::AccessorInfo &);
static
v8::Handle<v8::Value> PropertyGetterCallbackWrapper(
v8::Local<v8::String> property, const v8::AccessorInfo &info) {
v8::Local<v8::Object> obj = info.Data().As<v8::Object>();
PropertyCallbackInfo<v8::Value>
cbinfo(info, obj->GetInternalField(kDataIndex));
PropertyGetterCallback callback = reinterpret_cast<PropertyGetterCallback>(
reinterpret_cast<intptr_t>(
obj->GetInternalField(kPropertyGetterIndex)
.As<v8::External>()->Value()));
callback(property, cbinfo);
return ReturnValueImp<v8::Value>(cbinfo.GetReturnValue()).Value();
}
typedef v8::Handle<v8::Value> (*NativePropertyGetter)
(v8::Local<v8::String>, const v8::AccessorInfo &);
static
v8::Handle<v8::Value> PropertySetterCallbackWrapper(
v8::Local<v8::String> property
, v8::Local<v8::Value> value
, const v8::AccessorInfo &info) {
v8::Local<v8::Object> obj = info.Data().As<v8::Object>();
PropertyCallbackInfo<v8::Value>
cbinfo(info, obj->GetInternalField(kDataIndex));
PropertySetterCallback callback = reinterpret_cast<PropertySetterCallback>(
reinterpret_cast<intptr_t>(
obj->GetInternalField(kPropertySetterIndex)
.As<v8::External>()->Value()));
callback(property, value, cbinfo);
return ReturnValueImp<v8::Value>(cbinfo.GetReturnValue()).Value();
}
typedef v8::Handle<v8::Value> (*NativePropertySetter)
(v8::Local<v8::String>, v8::Local<v8::Value>, const v8::AccessorInfo &);
static
v8::Handle<v8::Array> PropertyEnumeratorCallbackWrapper(
const v8::AccessorInfo &info) {
v8::Local<v8::Object> obj = info.Data().As<v8::Object>();
PropertyCallbackInfo<v8::Array>
cbinfo(info, obj->GetInternalField(kDataIndex));
PropertyEnumeratorCallback callback =
reinterpret_cast<PropertyEnumeratorCallback>(reinterpret_cast<intptr_t>(
obj->GetInternalField(kPropertyEnumeratorIndex)
.As<v8::External>()->Value()));
callback(cbinfo);
return ReturnValueImp<v8::Array>(cbinfo.GetReturnValue()).Value();
}
typedef v8::Handle<v8::Array> (*NativePropertyEnumerator)
(const v8::AccessorInfo &);
static
v8::Handle<v8::Boolean> PropertyDeleterCallbackWrapper(
v8::Local<v8::String> property
, const v8::AccessorInfo &info) {
v8::Local<v8::Object> obj = info.Data().As<v8::Object>();
PropertyCallbackInfo<v8::Boolean>
cbinfo(info, obj->GetInternalField(kDataIndex));
PropertyDeleterCallback callback = reinterpret_cast<PropertyDeleterCallback>(
reinterpret_cast<intptr_t>(
obj->GetInternalField(kPropertyDeleterIndex)
.As<v8::External>()->Value()));
callback(property, cbinfo);
return ReturnValueImp<v8::Boolean>(cbinfo.GetReturnValue()).Value();
}
typedef v8::Handle<v8::Boolean> (NativePropertyDeleter)
(v8::Local<v8::String>, const v8::AccessorInfo &);
static
v8::Handle<v8::Integer> PropertyQueryCallbackWrapper(
v8::Local<v8::String> property, const v8::AccessorInfo &info) {
v8::Local<v8::Object> obj = info.Data().As<v8::Object>();
PropertyCallbackInfo<v8::Integer>
cbinfo(info, obj->GetInternalField(kDataIndex));
PropertyQueryCallback callback = reinterpret_cast<PropertyQueryCallback>(
reinterpret_cast<intptr_t>(
obj->GetInternalField(kPropertyQueryIndex)
.As<v8::External>()->Value()));
callback(property, cbinfo);
return ReturnValueImp<v8::Integer>(cbinfo.GetReturnValue()).Value();
}
typedef v8::Handle<v8::Integer> (*NativePropertyQuery)
(v8::Local<v8::String>, const v8::AccessorInfo &);
static
v8::Handle<v8::Value> IndexGetterCallbackWrapper(
uint32_t index, const v8::AccessorInfo &info) {
v8::Local<v8::Object> obj = info.Data().As<v8::Object>();
PropertyCallbackInfo<v8::Value>
cbinfo(info, obj->GetInternalField(kDataIndex));
IndexGetterCallback callback = reinterpret_cast<IndexGetterCallback>(
reinterpret_cast<intptr_t>(
obj->GetInternalField(kIndexPropertyGetterIndex)
.As<v8::External>()->Value()));
callback(index, cbinfo);
return ReturnValueImp<v8::Value>(cbinfo.GetReturnValue()).Value();
}
typedef v8::Handle<v8::Value> (*NativeIndexGetter)
(uint32_t, const v8::AccessorInfo &);
static
v8::Handle<v8::Value> IndexSetterCallbackWrapper(
uint32_t index
, v8::Local<v8::Value> value
, const v8::AccessorInfo &info) {
v8::Local<v8::Object> obj = info.Data().As<v8::Object>();
PropertyCallbackInfo<v8::Value>
cbinfo(info, obj->GetInternalField(kDataIndex));
IndexSetterCallback callback = reinterpret_cast<IndexSetterCallback>(
reinterpret_cast<intptr_t>(
obj->GetInternalField(kIndexPropertySetterIndex)
.As<v8::External>()->Value()));
callback(index, value, cbinfo);
return ReturnValueImp<v8::Value>(cbinfo.GetReturnValue()).Value();
}
typedef v8::Handle<v8::Value> (*NativeIndexSetter)
(uint32_t, v8::Local<v8::Value>, const v8::AccessorInfo &);
static
v8::Handle<v8::Array> IndexEnumeratorCallbackWrapper(
const v8::AccessorInfo &info) {
v8::Local<v8::Object> obj = info.Data().As<v8::Object>();
PropertyCallbackInfo<v8::Array>
cbinfo(info, obj->GetInternalField(kDataIndex));
IndexEnumeratorCallback callback = reinterpret_cast<IndexEnumeratorCallback>(
reinterpret_cast<intptr_t>(
obj->GetInternalField(kIndexPropertyEnumeratorIndex)
.As<v8::External>()->Value()));
callback(cbinfo);
return ReturnValueImp<v8::Array>(cbinfo.GetReturnValue()).Value();
}
typedef v8::Handle<v8::Array> (*NativeIndexEnumerator)
(const v8::AccessorInfo &);
static
v8::Handle<v8::Boolean> IndexDeleterCallbackWrapper(
uint32_t index, const v8::AccessorInfo &info) {
v8::Local<v8::Object> obj = info.Data().As<v8::Object>();
PropertyCallbackInfo<v8::Boolean>
cbinfo(info, obj->GetInternalField(kDataIndex));
IndexDeleterCallback callback = reinterpret_cast<IndexDeleterCallback>(
reinterpret_cast<intptr_t>(
obj->GetInternalField(kIndexPropertyDeleterIndex)
.As<v8::External>()->Value()));
callback(index, cbinfo);
return ReturnValueImp<v8::Boolean>(cbinfo.GetReturnValue()).Value();
}
typedef v8::Handle<v8::Boolean> (*NativeIndexDeleter)
(uint32_t, const v8::AccessorInfo &);
static
v8::Handle<v8::Integer> IndexQueryCallbackWrapper(
uint32_t index, const v8::AccessorInfo &info) {
v8::Local<v8::Object> obj = info.Data().As<v8::Object>();
PropertyCallbackInfo<v8::Integer>
cbinfo(info, obj->GetInternalField(kDataIndex));
IndexQueryCallback callback = reinterpret_cast<IndexQueryCallback>(
reinterpret_cast<intptr_t>(
obj->GetInternalField(kIndexPropertyQueryIndex)
.As<v8::External>()->Value()));
callback(index, cbinfo);
return ReturnValueImp<v8::Integer>(cbinfo.GetReturnValue()).Value();
}
typedef v8::Handle<v8::Integer> (*NativeIndexQuery)
(uint32_t, const v8::AccessorInfo &);
} // end of namespace imp
#endif // NAN_CALLBACKS_PRE_12_INL_H_

64
test/gc/node_modules/nan/nan_converters.h

@ -0,0 +1,64 @@
/*********************************************************************
* NAN - Native Abstractions for Node.js
*
* Copyright (c) 2016 NAN contributors
*
* MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md>
********************************************************************/
#ifndef NAN_CONVERTERS_H_
#define NAN_CONVERTERS_H_
namespace imp {
template<typename T> struct ToFactoryBase {
typedef MaybeLocal<T> return_t;
};
template<typename T> struct ValueFactoryBase { typedef Maybe<T> return_t; };
template<typename T> struct ToFactory;
#define X(TYPE) \
template<> \
struct ToFactory<v8::TYPE> : ToFactoryBase<v8::TYPE> { \
static inline return_t convert(v8::Local<v8::Value> val); \
};
X(Boolean)
X(Number)
X(String)
X(Object)
X(Integer)
X(Uint32)
X(Int32)
#undef X
#define X(TYPE) \
template<> \
struct ToFactory<TYPE> : ValueFactoryBase<TYPE> { \
static inline return_t convert(v8::Local<v8::Value> val); \
};
X(bool)
X(double)
X(int64_t)
X(uint32_t)
X(int32_t)
#undef X
} // end of namespace imp
template<typename T>
NAN_INLINE
typename imp::ToFactory<T>::return_t To(v8::Local<v8::Value> val) {
return imp::ToFactory<T>::convert(val);
}
#if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 || \
(V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3))
# include "nan_converters_43_inl.h"
#else
# include "nan_converters_pre_43_inl.h"
#endif
#endif // NAN_CONVERTERS_H_

42
test/gc/node_modules/nan/nan_converters_43_inl.h

@ -0,0 +1,42 @@
/*********************************************************************
* NAN - Native Abstractions for Node.js
*
* Copyright (c) 2016 NAN contributors
*
* MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md>
********************************************************************/
#ifndef NAN_CONVERTERS_43_INL_H_
#define NAN_CONVERTERS_43_INL_H_
#define X(TYPE) \
imp::ToFactory<v8::TYPE>::return_t \
imp::ToFactory<v8::TYPE>::convert(v8::Local<v8::Value> val) { \
return val->To ## TYPE(GetCurrentContext()); \
}
X(Boolean)
X(Number)
X(String)
X(Object)
X(Integer)
X(Uint32)
X(Int32)
#undef X
#define X(TYPE, NAME) \
imp::ToFactory<TYPE>::return_t \
imp::ToFactory<TYPE>::convert(v8::Local<v8::Value> val) { \
return val->NAME ## Value(GetCurrentContext()); \
}
X(bool, Boolean)
X(double, Number)
X(int64_t, Integer)
X(uint32_t, Uint32)
X(int32_t, Int32)
#undef X
#endif // NAN_CONVERTERS_43_INL_H_

42
test/gc/node_modules/nan/nan_converters_pre_43_inl.h

@ -0,0 +1,42 @@
/*********************************************************************
* NAN - Native Abstractions for Node.js
*
* Copyright (c) 2016 NAN contributors
*
* MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md>
********************************************************************/
#ifndef NAN_CONVERTERS_PRE_43_INL_H_
#define NAN_CONVERTERS_PRE_43_INL_H_
#define X(TYPE) \
imp::ToFactory<v8::TYPE>::return_t \
imp::ToFactory<v8::TYPE>::convert(v8::Local<v8::Value> val) { \
return MaybeLocal<v8::TYPE>(val->To ## TYPE()); \
}
X(Boolean)
X(Number)
X(String)
X(Object)
X(Integer)
X(Uint32)
X(Int32)
#undef X
#define X(TYPE, NAME) \
imp::ToFactory<TYPE>::return_t \
imp::ToFactory<TYPE>::convert(v8::Local<v8::Value> val) { \
return Just<TYPE>(val->NAME ##Value()); \
}
X(bool, Boolean)
X(double, Number)
X(int64_t, Integer)
X(uint32_t, Uint32)
X(int32_t, Int32)
#undef X
#endif // NAN_CONVERTERS_PRE_43_INL_H_

404
test/gc/node_modules/nan/nan_implementation_12_inl.h

@ -0,0 +1,404 @@
/*********************************************************************
* NAN - Native Abstractions for Node.js
*
* Copyright (c) 2016 NAN contributors
*
* MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md>
********************************************************************/
#ifndef NAN_IMPLEMENTATION_12_INL_H_
#define NAN_IMPLEMENTATION_12_INL_H_
//==============================================================================
// node v0.11 implementation
//==============================================================================
namespace imp {
//=== Array ====================================================================
Factory<v8::Array>::return_t
Factory<v8::Array>::New() {
return v8::Array::New(v8::Isolate::GetCurrent());
}
Factory<v8::Array>::return_t
Factory<v8::Array>::New(int length) {
return v8::Array::New(v8::Isolate::GetCurrent(), length);
}
//=== Boolean ==================================================================
Factory<v8::Boolean>::return_t
Factory<v8::Boolean>::New(bool value) {
return v8::Boolean::New(v8::Isolate::GetCurrent(), value);
}
//=== Boolean Object ===========================================================
Factory<v8::BooleanObject>::return_t
Factory<v8::BooleanObject>::New(bool value) {
return v8::BooleanObject::New(value).As<v8::BooleanObject>();
}
//=== Context ==================================================================
Factory<v8::Context>::return_t
Factory<v8::Context>::New( v8::ExtensionConfiguration* extensions
, v8::Local<v8::ObjectTemplate> tmpl
, v8::Local<v8::Value> obj) {
return v8::Context::New(v8::Isolate::GetCurrent(), extensions, tmpl, obj);
}
//=== Date =====================================================================
#if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 || \
(V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3))
Factory<v8::Date>::return_t
Factory<v8::Date>::New(double value) {
v8::Local<v8::Date> ret;
if (v8::Date::New(GetCurrentContext(), value).
ToLocal(reinterpret_cast<v8::Local<v8::Value>*>(&ret))) {
return v8::MaybeLocal<v8::Date>(ret);
} else {
return v8::MaybeLocal<v8::Date>(ret);
}
}
#else
Factory<v8::Date>::return_t
Factory<v8::Date>::New(double value) {
return Factory<v8::Date>::return_t(
v8::Date::New(v8::Isolate::GetCurrent(), value).As<v8::Date>());
}
#endif
//=== External =================================================================
Factory<v8::External>::return_t
Factory<v8::External>::New(void * value) {
return v8::External::New(v8::Isolate::GetCurrent(), value);
}
//=== Function =================================================================
Factory<v8::Function>::return_t
Factory<v8::Function>::New( FunctionCallback callback
, v8::Local<v8::Value> data) {
v8::Isolate *isolate = v8::Isolate::GetCurrent();
v8::EscapableHandleScope scope(isolate);
v8::Local<v8::ObjectTemplate> tpl = v8::ObjectTemplate::New(isolate);
tpl->SetInternalFieldCount(imp::kFunctionFieldCount);
v8::Local<v8::Object> obj = NewInstance(tpl).ToLocalChecked();
obj->SetInternalField(
imp::kFunctionIndex
, v8::External::New(isolate, reinterpret_cast<void *>(callback)));
v8::Local<v8::Value> val = v8::Local<v8::Value>::New(isolate, data);
if (!val.IsEmpty()) {
obj->SetInternalField(imp::kDataIndex, val);
}
return scope.Escape(v8::Function::New( isolate
, imp::FunctionCallbackWrapper
, obj));
}
//=== Function Template ========================================================
Factory<v8::FunctionTemplate>::return_t
Factory<v8::FunctionTemplate>::New( FunctionCallback callback
, v8::Local<v8::Value> data
, v8::Local<v8::Signature> signature) {
v8::Isolate *isolate = v8::Isolate::GetCurrent();
if (callback) {
v8::EscapableHandleScope scope(isolate);
v8::Local<v8::ObjectTemplate> tpl = v8::ObjectTemplate::New(isolate);
tpl->SetInternalFieldCount(imp::kFunctionFieldCount);
v8::Local<v8::Object> obj = NewInstance(tpl).ToLocalChecked();
obj->SetInternalField(
imp::kFunctionIndex
, v8::External::New(isolate, reinterpret_cast<void *>(callback)));
v8::Local<v8::Value> val = v8::Local<v8::Value>::New(isolate, data);
if (!val.IsEmpty()) {
obj->SetInternalField(imp::kDataIndex, val);
}
return scope.Escape(v8::FunctionTemplate::New( isolate
, imp::FunctionCallbackWrapper
, obj
, signature));
} else {
return v8::FunctionTemplate::New(isolate, 0, data, signature);
}
}
//=== Number ===================================================================
Factory<v8::Number>::return_t
Factory<v8::Number>::New(double value) {
return v8::Number::New(v8::Isolate::GetCurrent(), value);
}
//=== Number Object ============================================================
Factory<v8::NumberObject>::return_t
Factory<v8::NumberObject>::New(double value) {
return v8::NumberObject::New( v8::Isolate::GetCurrent()
, value).As<v8::NumberObject>();
}
//=== Integer, Int32 and Uint32 ================================================
template <typename T>
typename IntegerFactory<T>::return_t
IntegerFactory<T>::New(int32_t value) {
return To<T>(T::New(v8::Isolate::GetCurrent(), value));
}
template <typename T>
typename IntegerFactory<T>::return_t
IntegerFactory<T>::New(uint32_t value) {
return To<T>(T::NewFromUnsigned(v8::Isolate::GetCurrent(), value));
}
Factory<v8::Uint32>::return_t
Factory<v8::Uint32>::New(int32_t value) {
return To<v8::Uint32>(
v8::Uint32::NewFromUnsigned(v8::Isolate::GetCurrent(), value));
}
Factory<v8::Uint32>::return_t
Factory<v8::Uint32>::New(uint32_t value) {
return To<v8::Uint32>(
v8::Uint32::NewFromUnsigned(v8::Isolate::GetCurrent(), value));
}
//=== Object ===================================================================
Factory<v8::Object>::return_t
Factory<v8::Object>::New() {
return v8::Object::New(v8::Isolate::GetCurrent());
}
//=== Object Template ==========================================================
Factory<v8::ObjectTemplate>::return_t
Factory<v8::ObjectTemplate>::New() {
return v8::ObjectTemplate::New(v8::Isolate::GetCurrent());
}
//=== RegExp ===================================================================
#if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 || \
(V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3))
Factory<v8::RegExp>::return_t
Factory<v8::RegExp>::New(
v8::Local<v8::String> pattern
, v8::RegExp::Flags flags) {
return v8::RegExp::New(GetCurrentContext(), pattern, flags);
}
#else
Factory<v8::RegExp>::return_t
Factory<v8::RegExp>::New(
v8::Local<v8::String> pattern
, v8::RegExp::Flags flags) {
return Factory<v8::RegExp>::return_t(v8::RegExp::New(pattern, flags));
}
#endif
//=== Script ===================================================================
#if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 || \
(V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3))
Factory<v8::Script>::return_t
Factory<v8::Script>::New( v8::Local<v8::String> source) {
v8::ScriptCompiler::Source src(source);
return v8::ScriptCompiler::Compile(GetCurrentContext(), &src);
}
Factory<v8::Script>::return_t
Factory<v8::Script>::New( v8::Local<v8::String> source
, v8::ScriptOrigin const& origin) {
v8::ScriptCompiler::Source src(source, origin);
return v8::ScriptCompiler::Compile(GetCurrentContext(), &src);
}
#else
Factory<v8::Script>::return_t
Factory<v8::Script>::New( v8::Local<v8::String> source) {
v8::ScriptCompiler::Source src(source);
return Factory<v8::Script>::return_t(
v8::ScriptCompiler::Compile(v8::Isolate::GetCurrent(), &src));
}
Factory<v8::Script>::return_t
Factory<v8::Script>::New( v8::Local<v8::String> source
, v8::ScriptOrigin const& origin) {
v8::ScriptCompiler::Source src(source, origin);
return Factory<v8::Script>::return_t(
v8::ScriptCompiler::Compile(v8::Isolate::GetCurrent(), &src));
}
#endif
//=== Signature ================================================================
Factory<v8::Signature>::return_t
Factory<v8::Signature>::New(Factory<v8::Signature>::FTH receiver) {
return v8::Signature::New(v8::Isolate::GetCurrent(), receiver);
}
//=== String ===================================================================
Factory<v8::String>::return_t
Factory<v8::String>::New() {
return Factory<v8::String>::return_t(
v8::String::Empty(v8::Isolate::GetCurrent()));
}
#if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 || \
(V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3))
Factory<v8::String>::return_t
Factory<v8::String>::New(const char * value, int length) {
return v8::String::NewFromUtf8(
v8::Isolate::GetCurrent(), value, v8::NewStringType::kNormal, length);
}
Factory<v8::String>::return_t
Factory<v8::String>::New(std::string const& value) {
assert(value.size() <= INT_MAX && "string too long");
return v8::String::NewFromUtf8(v8::Isolate::GetCurrent(),
value.data(), v8::NewStringType::kNormal, static_cast<int>(value.size()));
}
Factory<v8::String>::return_t
Factory<v8::String>::New(const uint16_t * value, int length) {
return v8::String::NewFromTwoByte(v8::Isolate::GetCurrent(), value,
v8::NewStringType::kNormal, length);
}
Factory<v8::String>::return_t
Factory<v8::String>::New(v8::String::ExternalStringResource * value) {
return v8::String::NewExternalTwoByte(v8::Isolate::GetCurrent(), value);
}
Factory<v8::String>::return_t
Factory<v8::String>::New(ExternalOneByteStringResource * value) {
return v8::String::NewExternalOneByte(v8::Isolate::GetCurrent(), value);
}
#else
Factory<v8::String>::return_t
Factory<v8::String>::New(const char * value, int length) {
return Factory<v8::String>::return_t(
v8::String::NewFromUtf8(
v8::Isolate::GetCurrent()
, value
, v8::String::kNormalString
, length));
}
Factory<v8::String>::return_t
Factory<v8::String>::New(
std::string const& value) /* NOLINT(build/include_what_you_use) */ {
assert(value.size() <= INT_MAX && "string too long");
return Factory<v8::String>::return_t(
v8::String::NewFromUtf8(
v8::Isolate::GetCurrent()
, value.data()
, v8::String::kNormalString
, static_cast<int>(value.size())));
}
Factory<v8::String>::return_t
Factory<v8::String>::New(const uint16_t * value, int length) {
return Factory<v8::String>::return_t(
v8::String::NewFromTwoByte(
v8::Isolate::GetCurrent()
, value
, v8::String::kNormalString
, length));
}
Factory<v8::String>::return_t
Factory<v8::String>::New(v8::String::ExternalStringResource * value) {
return Factory<v8::String>::return_t(
v8::String::NewExternal(v8::Isolate::GetCurrent(), value));
}
Factory<v8::String>::return_t
Factory<v8::String>::New(ExternalOneByteStringResource * value) {
return Factory<v8::String>::return_t(
v8::String::NewExternal(v8::Isolate::GetCurrent(), value));
}
#endif
//=== String Object ============================================================
Factory<v8::StringObject>::return_t
Factory<v8::StringObject>::New(v8::Local<v8::String> value) {
return v8::StringObject::New(value).As<v8::StringObject>();
}
//=== Unbound Script ===========================================================
#if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 || \
(V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3))
Factory<v8::UnboundScript>::return_t
Factory<v8::UnboundScript>::New(v8::Local<v8::String> source) {
v8::ScriptCompiler::Source src(source);
return v8::ScriptCompiler::CompileUnboundScript(
v8::Isolate::GetCurrent(), &src);
}
Factory<v8::UnboundScript>::return_t
Factory<v8::UnboundScript>::New( v8::Local<v8::String> source
, v8::ScriptOrigin const& origin) {
v8::ScriptCompiler::Source src(source, origin);
return v8::ScriptCompiler::CompileUnboundScript(
v8::Isolate::GetCurrent(), &src);
}
#else
Factory<v8::UnboundScript>::return_t
Factory<v8::UnboundScript>::New(v8::Local<v8::String> source) {
v8::ScriptCompiler::Source src(source);
return Factory<v8::UnboundScript>::return_t(
v8::ScriptCompiler::CompileUnbound(v8::Isolate::GetCurrent(), &src));
}
Factory<v8::UnboundScript>::return_t
Factory<v8::UnboundScript>::New( v8::Local<v8::String> source
, v8::ScriptOrigin const& origin) {
v8::ScriptCompiler::Source src(source, origin);
return Factory<v8::UnboundScript>::return_t(
v8::ScriptCompiler::CompileUnbound(v8::Isolate::GetCurrent(), &src));
}
#endif
} // end of namespace imp
//=== Presistents and Handles ==================================================
#if NODE_MODULE_VERSION < IOJS_3_0_MODULE_VERSION
template <typename T>
inline v8::Local<T> New(v8::Handle<T> h) {
return v8::Local<T>::New(v8::Isolate::GetCurrent(), h);
}
#endif
template <typename T, typename M>
inline v8::Local<T> New(v8::Persistent<T, M> const& p) {
return v8::Local<T>::New(v8::Isolate::GetCurrent(), p);
}
template <typename T, typename M>
inline v8::Local<T> New(Persistent<T, M> const& p) {
return v8::Local<T>::New(v8::Isolate::GetCurrent(), p);
}
template <typename T>
inline v8::Local<T> New(Global<T> const& p) {
return v8::Local<T>::New(v8::Isolate::GetCurrent(), p);
}
#endif // NAN_IMPLEMENTATION_12_INL_H_

264
test/gc/node_modules/nan/nan_implementation_pre_12_inl.h

@ -0,0 +1,264 @@
/*********************************************************************
* NAN - Native Abstractions for Node.js
*
* Copyright (c) 2016 NAN contributors
*
* MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md>
********************************************************************/
#ifndef NAN_IMPLEMENTATION_PRE_12_INL_H_
#define NAN_IMPLEMENTATION_PRE_12_INL_H_
//==============================================================================
// node v0.10 implementation
//==============================================================================
namespace imp {
//=== Array ====================================================================
Factory<v8::Array>::return_t
Factory<v8::Array>::New() {
return v8::Array::New();
}
Factory<v8::Array>::return_t
Factory<v8::Array>::New(int length) {
return v8::Array::New(length);
}
//=== Boolean ==================================================================
Factory<v8::Boolean>::return_t
Factory<v8::Boolean>::New(bool value) {
return v8::Boolean::New(value)->ToBoolean();
}
//=== Boolean Object ===========================================================
Factory<v8::BooleanObject>::return_t
Factory<v8::BooleanObject>::New(bool value) {
return v8::BooleanObject::New(value).As<v8::BooleanObject>();
}
//=== Context ==================================================================
Factory<v8::Context>::return_t
Factory<v8::Context>::New( v8::ExtensionConfiguration* extensions
, v8::Local<v8::ObjectTemplate> tmpl
, v8::Local<v8::Value> obj) {
v8::Persistent<v8::Context> ctx = v8::Context::New(extensions, tmpl, obj);
v8::Local<v8::Context> lctx = v8::Local<v8::Context>::New(ctx);
ctx.Dispose();
return lctx;
}
//=== Date =====================================================================
Factory<v8::Date>::return_t
Factory<v8::Date>::New(double value) {
return Factory<v8::Date>::return_t(v8::Date::New(value).As<v8::Date>());
}
//=== External =================================================================
Factory<v8::External>::return_t
Factory<v8::External>::New(void * value) {
return v8::External::New(value);
}
//=== Function =================================================================
Factory<v8::Function>::return_t
Factory<v8::Function>::New( FunctionCallback callback
, v8::Local<v8::Value> data) {
return Factory<v8::FunctionTemplate>::New( callback
, data
, v8::Local<v8::Signature>()
)->GetFunction();
}
//=== FunctionTemplate =========================================================
Factory<v8::FunctionTemplate>::return_t
Factory<v8::FunctionTemplate>::New( FunctionCallback callback
, v8::Local<v8::Value> data
, v8::Local<v8::Signature> signature) {
if (callback) {
v8::HandleScope scope;
v8::Local<v8::ObjectTemplate> tpl = v8::ObjectTemplate::New();
tpl->SetInternalFieldCount(imp::kFunctionFieldCount);
v8::Local<v8::Object> obj = tpl->NewInstance();
obj->SetInternalField(
imp::kFunctionIndex
, v8::External::New(reinterpret_cast<void *>(callback)));
v8::Local<v8::Value> val = v8::Local<v8::Value>::New(data);
if (!val.IsEmpty()) {
obj->SetInternalField(imp::kDataIndex, val);
}
// Note(agnat): Emulate length argument here. Unfortunately, I couldn't find
// a way. Have at it though...
return scope.Close(
v8::FunctionTemplate::New(imp::FunctionCallbackWrapper
, obj
, signature));
} else {
return v8::FunctionTemplate::New(0, data, signature);
}
}
//=== Number ===================================================================
Factory<v8::Number>::return_t
Factory<v8::Number>::New(double value) {
return v8::Number::New(value);
}
//=== Number Object ============================================================
Factory<v8::NumberObject>::return_t
Factory<v8::NumberObject>::New(double value) {
return v8::NumberObject::New(value).As<v8::NumberObject>();
}
//=== Integer, Int32 and Uint32 ================================================
template <typename T>
typename IntegerFactory<T>::return_t
IntegerFactory<T>::New(int32_t value) {
return To<T>(T::New(value));
}
template <typename T>
typename IntegerFactory<T>::return_t
IntegerFactory<T>::New(uint32_t value) {
return To<T>(T::NewFromUnsigned(value));
}
Factory<v8::Uint32>::return_t
Factory<v8::Uint32>::New(int32_t value) {
return To<v8::Uint32>(v8::Uint32::NewFromUnsigned(value));
}
Factory<v8::Uint32>::return_t
Factory<v8::Uint32>::New(uint32_t value) {
return To<v8::Uint32>(v8::Uint32::NewFromUnsigned(value));
}
//=== Object ===================================================================
Factory<v8::Object>::return_t
Factory<v8::Object>::New() {
return v8::Object::New();
}
//=== Object Template ==========================================================
Factory<v8::ObjectTemplate>::return_t
Factory<v8::ObjectTemplate>::New() {
return v8::ObjectTemplate::New();
}
//=== RegExp ===================================================================
Factory<v8::RegExp>::return_t
Factory<v8::RegExp>::New(
v8::Local<v8::String> pattern
, v8::RegExp::Flags flags) {
return Factory<v8::RegExp>::return_t(v8::RegExp::New(pattern, flags));
}
//=== Script ===================================================================
Factory<v8::Script>::return_t
Factory<v8::Script>::New( v8::Local<v8::String> source) {
return Factory<v8::Script>::return_t(v8::Script::New(source));
}
Factory<v8::Script>::return_t
Factory<v8::Script>::New( v8::Local<v8::String> source
, v8::ScriptOrigin const& origin) {
return Factory<v8::Script>::return_t(
v8::Script::New(source, const_cast<v8::ScriptOrigin*>(&origin)));
}
//=== Signature ================================================================
Factory<v8::Signature>::return_t
Factory<v8::Signature>::New(Factory<v8::Signature>::FTH receiver) {
return v8::Signature::New(receiver);
}
//=== String ===================================================================
Factory<v8::String>::return_t
Factory<v8::String>::New() {
return Factory<v8::String>::return_t(v8::String::Empty());
}
Factory<v8::String>::return_t
Factory<v8::String>::New(const char * value, int length) {
return Factory<v8::String>::return_t(v8::String::New(value, length));
}
Factory<v8::String>::return_t
Factory<v8::String>::New(
std::string const& value) /* NOLINT(build/include_what_you_use) */ {
assert(value.size() <= INT_MAX && "string too long");
return Factory<v8::String>::return_t(
v8::String::New( value.data(), static_cast<int>(value.size())));
}
Factory<v8::String>::return_t
Factory<v8::String>::New(const uint16_t * value, int length) {
return Factory<v8::String>::return_t(v8::String::New(value, length));
}
Factory<v8::String>::return_t
Factory<v8::String>::New(v8::String::ExternalStringResource * value) {
return Factory<v8::String>::return_t(v8::String::NewExternal(value));
}
Factory<v8::String>::return_t
Factory<v8::String>::New(v8::String::ExternalAsciiStringResource * value) {
return Factory<v8::String>::return_t(v8::String::NewExternal(value));
}
//=== String Object ============================================================
Factory<v8::StringObject>::return_t
Factory<v8::StringObject>::New(v8::Local<v8::String> value) {
return v8::StringObject::New(value).As<v8::StringObject>();
}
} // end of namespace imp
//=== Presistents and Handles ==================================================
template <typename T>
inline v8::Local<T> New(v8::Handle<T> h) {
return v8::Local<T>::New(h);
}
template <typename T>
inline v8::Local<T> New(v8::Persistent<T> const& p) {
return v8::Local<T>::New(p);
}
template <typename T, typename M>
inline v8::Local<T> New(Persistent<T, M> const& p) {
return v8::Local<T>::New(p.persistent);
}
template <typename T>
inline v8::Local<T> New(Global<T> const& p) {
return v8::Local<T>::New(p.persistent);
}
#endif // NAN_IMPLEMENTATION_PRE_12_INL_H_

231
test/gc/node_modules/nan/nan_maybe_43_inl.h

@ -0,0 +1,231 @@
/*********************************************************************
* NAN - Native Abstractions for Node.js
*
* Copyright (c) 2016 NAN contributors
*
* MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md>
********************************************************************/
#ifndef NAN_MAYBE_43_INL_H_
#define NAN_MAYBE_43_INL_H_
template<typename T>
using MaybeLocal = v8::MaybeLocal<T>;
template<typename T>
using Maybe = v8::Maybe<T>;
template<typename T>
NAN_INLINE Maybe<T> Nothing() {
return v8::Nothing<T>();
}
template<typename T>
NAN_INLINE Maybe<T> Just(const T& t) {
return v8::Just<T>(t);
}
v8::Local<v8::Context> GetCurrentContext();
NAN_INLINE
MaybeLocal<v8::String> ToDetailString(v8::Local<v8::Value> val) {
return val->ToDetailString(GetCurrentContext());
}
NAN_INLINE
MaybeLocal<v8::Uint32> ToArrayIndex(v8::Local<v8::Value> val) {
return val->ToArrayIndex(GetCurrentContext());
}
NAN_INLINE
Maybe<bool> Equals(v8::Local<v8::Value> a, v8::Local<v8::Value>(b)) {
return a->Equals(GetCurrentContext(), b);
}
NAN_INLINE
MaybeLocal<v8::Object> NewInstance(v8::Local<v8::Function> h) {
return h->NewInstance(GetCurrentContext());
}
NAN_INLINE
MaybeLocal<v8::Object> NewInstance(
v8::Local<v8::Function> h
, int argc
, v8::Local<v8::Value> argv[]) {
return h->NewInstance(GetCurrentContext(), argc, argv);
}
NAN_INLINE
MaybeLocal<v8::Object> NewInstance(v8::Local<v8::ObjectTemplate> h) {
return h->NewInstance(GetCurrentContext());
}
NAN_INLINE MaybeLocal<v8::Function> GetFunction(
v8::Local<v8::FunctionTemplate> t) {
return t->GetFunction(GetCurrentContext());
}
NAN_INLINE Maybe<bool> Set(
v8::Local<v8::Object> obj
, v8::Local<v8::Value> key
, v8::Local<v8::Value> value) {
return obj->Set(GetCurrentContext(), key, value);
}
NAN_INLINE Maybe<bool> Set(
v8::Local<v8::Object> obj
, uint32_t index
, v8::Local<v8::Value> value) {
return obj->Set(GetCurrentContext(), index, value);
}
NAN_INLINE Maybe<bool> ForceSet(
v8::Local<v8::Object> obj
, v8::Local<v8::Value> key
, v8::Local<v8::Value> value
, v8::PropertyAttribute attribs = v8::None) {
return obj->ForceSet(GetCurrentContext(), key, value, attribs);
}
NAN_INLINE MaybeLocal<v8::Value> Get(
v8::Local<v8::Object> obj
, v8::Local<v8::Value> key) {
return obj->Get(GetCurrentContext(), key);
}
NAN_INLINE
MaybeLocal<v8::Value> Get(v8::Local<v8::Object> obj, uint32_t index) {
return obj->Get(GetCurrentContext(), index);
}
NAN_INLINE v8::PropertyAttribute GetPropertyAttributes(
v8::Local<v8::Object> obj
, v8::Local<v8::Value> key) {
return obj->GetPropertyAttributes(GetCurrentContext(), key).FromJust();
}
NAN_INLINE Maybe<bool> Has(
v8::Local<v8::Object> obj
, v8::Local<v8::String> key) {
return obj->Has(GetCurrentContext(), key);
}
NAN_INLINE Maybe<bool> Has(v8::Local<v8::Object> obj, uint32_t index) {
return obj->Has(GetCurrentContext(), index);
}
NAN_INLINE Maybe<bool> Delete(
v8::Local<v8::Object> obj
, v8::Local<v8::String> key) {
return obj->Delete(GetCurrentContext(), key);
}
NAN_INLINE
Maybe<bool> Delete(v8::Local<v8::Object> obj, uint32_t index) {
return obj->Delete(GetCurrentContext(), index);
}
NAN_INLINE
MaybeLocal<v8::Array> GetPropertyNames(v8::Local<v8::Object> obj) {
return obj->GetPropertyNames(GetCurrentContext());
}
NAN_INLINE
MaybeLocal<v8::Array> GetOwnPropertyNames(v8::Local<v8::Object> obj) {
return obj->GetOwnPropertyNames(GetCurrentContext());
}
NAN_INLINE Maybe<bool> SetPrototype(
v8::Local<v8::Object> obj
, v8::Local<v8::Value> prototype) {
return obj->SetPrototype(GetCurrentContext(), prototype);
}
NAN_INLINE MaybeLocal<v8::String> ObjectProtoToString(
v8::Local<v8::Object> obj) {
return obj->ObjectProtoToString(GetCurrentContext());
}
NAN_INLINE Maybe<bool> HasOwnProperty(
v8::Local<v8::Object> obj
, v8::Local<v8::String> key) {
return obj->HasOwnProperty(GetCurrentContext(), key);
}
NAN_INLINE Maybe<bool> HasRealNamedProperty(
v8::Local<v8::Object> obj
, v8::Local<v8::String> key) {
return obj->HasRealNamedProperty(GetCurrentContext(), key);
}
NAN_INLINE Maybe<bool> HasRealIndexedProperty(
v8::Local<v8::Object> obj
, uint32_t index) {
return obj->HasRealIndexedProperty(GetCurrentContext(), index);
}
NAN_INLINE Maybe<bool> HasRealNamedCallbackProperty(
v8::Local<v8::Object> obj
, v8::Local<v8::String> key) {
return obj->HasRealNamedCallbackProperty(GetCurrentContext(), key);
}
NAN_INLINE MaybeLocal<v8::Value> GetRealNamedPropertyInPrototypeChain(
v8::Local<v8::Object> obj
, v8::Local<v8::String> key) {
return obj->GetRealNamedPropertyInPrototypeChain(GetCurrentContext(), key);
}
NAN_INLINE MaybeLocal<v8::Value> GetRealNamedProperty(
v8::Local<v8::Object> obj
, v8::Local<v8::String> key) {
return obj->GetRealNamedProperty(GetCurrentContext(), key);
}
NAN_INLINE MaybeLocal<v8::Value> CallAsFunction(
v8::Local<v8::Object> obj
, v8::Local<v8::Object> recv
, int argc
, v8::Local<v8::Value> argv[]) {
return obj->CallAsFunction(GetCurrentContext(), recv, argc, argv);
}
NAN_INLINE MaybeLocal<v8::Value> CallAsConstructor(
v8::Local<v8::Object> obj
, int argc, v8::Local<v8::Value> argv[]) {
return obj->CallAsConstructor(GetCurrentContext(), argc, argv);
}
NAN_INLINE
MaybeLocal<v8::String> GetSourceLine(v8::Local<v8::Message> msg) {
return msg->GetSourceLine(GetCurrentContext());
}
NAN_INLINE Maybe<int> GetLineNumber(v8::Local<v8::Message> msg) {
return msg->GetLineNumber(GetCurrentContext());
}
NAN_INLINE Maybe<int> GetStartColumn(v8::Local<v8::Message> msg) {
return msg->GetStartColumn(GetCurrentContext());
}
NAN_INLINE Maybe<int> GetEndColumn(v8::Local<v8::Message> msg) {
return msg->GetEndColumn(GetCurrentContext());
}
NAN_INLINE MaybeLocal<v8::Object> CloneElementAt(
v8::Local<v8::Array> array
, uint32_t index) {
return array->CloneElementAt(GetCurrentContext(), index);
}
NAN_INLINE MaybeLocal<v8::Value> Call(
v8::Local<v8::Function> fun
, v8::Local<v8::Object> recv
, int argc
, v8::Local<v8::Value> argv[]) {
return fun->Call(GetCurrentContext(), recv, argc, argv);
}
#endif // NAN_MAYBE_43_INL_H_

303
test/gc/node_modules/nan/nan_maybe_pre_43_inl.h

@ -0,0 +1,303 @@
/*********************************************************************
* NAN - Native Abstractions for Node.js
*
* Copyright (c) 2016 NAN contributors
*
* MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md>
********************************************************************/
#ifndef NAN_MAYBE_PRE_43_INL_H_
#define NAN_MAYBE_PRE_43_INL_H_
template<typename T>
class MaybeLocal {
public:
NAN_INLINE MaybeLocal() : val_(v8::Local<T>()) {}
template<typename S>
# if NODE_MODULE_VERSION >= NODE_0_12_MODULE_VERSION
NAN_INLINE MaybeLocal(v8::Local<S> that) : val_(that) {}
# else
NAN_INLINE MaybeLocal(v8::Local<S> that) :
val_(*reinterpret_cast<v8::Local<T>*>(&that)) {}
# endif
NAN_INLINE bool IsEmpty() const { return val_.IsEmpty(); }
template<typename S>
NAN_INLINE bool ToLocal(v8::Local<S> *out) const {
*out = val_;
return !IsEmpty();
}
NAN_INLINE v8::Local<T> ToLocalChecked() const {
#if defined(V8_ENABLE_CHECKS)
assert(!IsEmpty() && "ToLocalChecked is Empty");
#endif // V8_ENABLE_CHECKS
return val_;
}
template<typename S>
NAN_INLINE v8::Local<S> FromMaybe(v8::Local<S> default_value) const {
return IsEmpty() ? default_value : val_;
}
private:
v8::Local<T> val_;
};
template<typename T>
class Maybe {
public:
NAN_INLINE bool IsNothing() const { return !has_value_; }
NAN_INLINE bool IsJust() const { return has_value_; }
NAN_INLINE T FromJust() const {
#if defined(V8_ENABLE_CHECKS)
assert(IsJust() && "FromJust is Nothing");
#endif // V8_ENABLE_CHECKS
return value_;
}
NAN_INLINE T FromMaybe(const T& default_value) const {
return has_value_ ? value_ : default_value;
}
NAN_INLINE bool operator==(const Maybe &other) const {
return (IsJust() == other.IsJust()) &&
(!IsJust() || FromJust() == other.FromJust());
}
NAN_INLINE bool operator!=(const Maybe &other) const {
return !operator==(other);
}
private:
Maybe() : has_value_(false) {}
explicit Maybe(const T& t) : has_value_(true), value_(t) {}
bool has_value_;
T value_;
template<typename U>
friend Maybe<U> Nothing();
template<typename U>
friend Maybe<U> Just(const U& u);
};
template<typename T>
inline Maybe<T> Nothing() {
return Maybe<T>();
}
template<typename T>
inline Maybe<T> Just(const T& t) {
return Maybe<T>(t);
}
NAN_INLINE
MaybeLocal<v8::String> ToDetailString(v8::Handle<v8::Value> val) {
return MaybeLocal<v8::String>(val->ToDetailString());
}
NAN_INLINE
MaybeLocal<v8::Uint32> ToArrayIndex(v8::Handle<v8::Value> val) {
return MaybeLocal<v8::Uint32>(val->ToArrayIndex());
}
NAN_INLINE
Maybe<bool> Equals(v8::Handle<v8::Value> a, v8::Handle<v8::Value>(b)) {
return Just<bool>(a->Equals(b));
}
NAN_INLINE
MaybeLocal<v8::Object> NewInstance(v8::Handle<v8::Function> h) {
return MaybeLocal<v8::Object>(h->NewInstance());
}
NAN_INLINE
MaybeLocal<v8::Object> NewInstance(
v8::Local<v8::Function> h
, int argc
, v8::Local<v8::Value> argv[]) {
return MaybeLocal<v8::Object>(h->NewInstance(argc, argv));
}
NAN_INLINE
MaybeLocal<v8::Object> NewInstance(v8::Handle<v8::ObjectTemplate> h) {
return MaybeLocal<v8::Object>(h->NewInstance());
}
NAN_INLINE
MaybeLocal<v8::Function> GetFunction(v8::Handle<v8::FunctionTemplate> t) {
return MaybeLocal<v8::Function>(t->GetFunction());
}
NAN_INLINE Maybe<bool> Set(
v8::Handle<v8::Object> obj
, v8::Handle<v8::Value> key
, v8::Handle<v8::Value> value) {
return Just<bool>(obj->Set(key, value));
}
NAN_INLINE Maybe<bool> Set(
v8::Handle<v8::Object> obj
, uint32_t index
, v8::Handle<v8::Value> value) {
return Just<bool>(obj->Set(index, value));
}
NAN_INLINE Maybe<bool> ForceSet(
v8::Handle<v8::Object> obj
, v8::Handle<v8::Value> key
, v8::Handle<v8::Value> value
, v8::PropertyAttribute attribs = v8::None) {
return Just<bool>(obj->ForceSet(key, value, attribs));
}
NAN_INLINE MaybeLocal<v8::Value> Get(
v8::Handle<v8::Object> obj
, v8::Handle<v8::Value> key) {
return MaybeLocal<v8::Value>(obj->Get(key));
}
NAN_INLINE MaybeLocal<v8::Value> Get(
v8::Handle<v8::Object> obj
, uint32_t index) {
return MaybeLocal<v8::Value>(obj->Get(index));
}
NAN_INLINE Maybe<v8::PropertyAttribute> GetPropertyAttributes(
v8::Handle<v8::Object> obj
, v8::Handle<v8::Value> key) {
return Just<v8::PropertyAttribute>(obj->GetPropertyAttributes(key));
}
NAN_INLINE Maybe<bool> Has(
v8::Handle<v8::Object> obj
, v8::Handle<v8::String> key) {
return Just<bool>(obj->Has(key));
}
NAN_INLINE Maybe<bool> Has(
v8::Handle<v8::Object> obj
, uint32_t index) {
return Just<bool>(obj->Has(index));
}
NAN_INLINE Maybe<bool> Delete(
v8::Handle<v8::Object> obj
, v8::Handle<v8::String> key) {
return Just<bool>(obj->Delete(key));
}
NAN_INLINE Maybe<bool> Delete(
v8::Handle<v8::Object> obj
, uint32_t index) {
return Just<bool>(obj->Delete(index));
}
NAN_INLINE
MaybeLocal<v8::Array> GetPropertyNames(v8::Handle<v8::Object> obj) {
return MaybeLocal<v8::Array>(obj->GetPropertyNames());
}
NAN_INLINE
MaybeLocal<v8::Array> GetOwnPropertyNames(v8::Handle<v8::Object> obj) {
return MaybeLocal<v8::Array>(obj->GetOwnPropertyNames());
}
NAN_INLINE Maybe<bool> SetPrototype(
v8::Handle<v8::Object> obj
, v8::Handle<v8::Value> prototype) {
return Just<bool>(obj->SetPrototype(prototype));
}
NAN_INLINE MaybeLocal<v8::String> ObjectProtoToString(
v8::Handle<v8::Object> obj) {
return MaybeLocal<v8::String>(obj->ObjectProtoToString());
}
NAN_INLINE Maybe<bool> HasOwnProperty(
v8::Handle<v8::Object> obj
, v8::Handle<v8::String> key) {
return Just<bool>(obj->HasOwnProperty(key));
}
NAN_INLINE Maybe<bool> HasRealNamedProperty(
v8::Handle<v8::Object> obj
, v8::Handle<v8::String> key) {
return Just<bool>(obj->HasRealNamedProperty(key));
}
NAN_INLINE Maybe<bool> HasRealIndexedProperty(
v8::Handle<v8::Object> obj
, uint32_t index) {
return Just<bool>(obj->HasRealIndexedProperty(index));
}
NAN_INLINE Maybe<bool> HasRealNamedCallbackProperty(
v8::Handle<v8::Object> obj
, v8::Handle<v8::String> key) {
return Just<bool>(obj->HasRealNamedCallbackProperty(key));
}
NAN_INLINE MaybeLocal<v8::Value> GetRealNamedPropertyInPrototypeChain(
v8::Handle<v8::Object> obj
, v8::Handle<v8::String> key) {
return MaybeLocal<v8::Value>(
obj->GetRealNamedPropertyInPrototypeChain(key));
}
NAN_INLINE MaybeLocal<v8::Value> GetRealNamedProperty(
v8::Handle<v8::Object> obj
, v8::Handle<v8::String> key) {
return MaybeLocal<v8::Value>(obj->GetRealNamedProperty(key));
}
NAN_INLINE MaybeLocal<v8::Value> CallAsFunction(
v8::Handle<v8::Object> obj
, v8::Handle<v8::Object> recv
, int argc
, v8::Handle<v8::Value> argv[]) {
return MaybeLocal<v8::Value>(obj->CallAsFunction(recv, argc, argv));
}
NAN_INLINE MaybeLocal<v8::Value> CallAsConstructor(
v8::Handle<v8::Object> obj
, int argc
, v8::Local<v8::Value> argv[]) {
return MaybeLocal<v8::Value>(obj->CallAsConstructor(argc, argv));
}
NAN_INLINE
MaybeLocal<v8::String> GetSourceLine(v8::Handle<v8::Message> msg) {
return MaybeLocal<v8::String>(msg->GetSourceLine());
}
NAN_INLINE Maybe<int> GetLineNumber(v8::Handle<v8::Message> msg) {
return Just<int>(msg->GetLineNumber());
}
NAN_INLINE Maybe<int> GetStartColumn(v8::Handle<v8::Message> msg) {
return Just<int>(msg->GetStartColumn());
}
NAN_INLINE Maybe<int> GetEndColumn(v8::Handle<v8::Message> msg) {
return Just<int>(msg->GetEndColumn());
}
NAN_INLINE MaybeLocal<v8::Object> CloneElementAt(
v8::Handle<v8::Array> array
, uint32_t index) {
return MaybeLocal<v8::Object>(array->CloneElementAt(index));
}
NAN_INLINE MaybeLocal<v8::Value> Call(
v8::Local<v8::Function> fun
, v8::Local<v8::Object> recv
, int argc
, v8::Local<v8::Value> argv[]) {
return MaybeLocal<v8::Value>(fun->Call(recv, argc, argv));
}
#endif // NAN_MAYBE_PRE_43_INL_H_

340
test/gc/node_modules/nan/nan_new.h

@ -0,0 +1,340 @@
/*********************************************************************
* NAN - Native Abstractions for Node.js
*
* Copyright (c) 2016 NAN contributors
*
* MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md>
********************************************************************/
#ifndef NAN_NEW_H_
#define NAN_NEW_H_
namespace imp { // scnr
// TODO(agnat): Generalize
template <typename T> v8::Local<T> To(v8::Local<v8::Integer> i);
template <>
inline
v8::Local<v8::Integer>
To<v8::Integer>(v8::Local<v8::Integer> i) {
return Nan::To<v8::Integer>(i).ToLocalChecked();
}
template <>
inline
v8::Local<v8::Int32>
To<v8::Int32>(v8::Local<v8::Integer> i) {
return Nan::To<v8::Int32>(i).ToLocalChecked();
}
template <>
inline
v8::Local<v8::Uint32>
To<v8::Uint32>(v8::Local<v8::Integer> i) {
return Nan::To<v8::Uint32>(i).ToLocalChecked();
}
template <typename T> struct FactoryBase {
typedef v8::Local<T> return_t;
};
template <typename T> struct MaybeFactoryBase {
typedef MaybeLocal<T> return_t;
};
template <typename T> struct Factory;
template <>
struct Factory<v8::Array> : FactoryBase<v8::Array> {
static inline return_t New();
static inline return_t New(int length);
};
template <>
struct Factory<v8::Boolean> : FactoryBase<v8::Boolean> {
static inline return_t New(bool value);
};
template <>
struct Factory<v8::BooleanObject> : FactoryBase<v8::BooleanObject> {
static inline return_t New(bool value);
};
template <>
struct Factory<v8::Context> : FactoryBase<v8::Context> {
static inline
return_t
New( v8::ExtensionConfiguration* extensions = NULL
, v8::Local<v8::ObjectTemplate> tmpl = v8::Local<v8::ObjectTemplate>()
, v8::Local<v8::Value> obj = v8::Local<v8::Value>());
};
template <>
struct Factory<v8::Date> : MaybeFactoryBase<v8::Date> {
static inline return_t New(double value);
};
template <>
struct Factory<v8::External> : FactoryBase<v8::External> {
static inline return_t New(void *value);
};
template <>
struct Factory<v8::Function> : FactoryBase<v8::Function> {
static inline
return_t
New( FunctionCallback callback
, v8::Local<v8::Value> data = v8::Local<v8::Value>());
};
template <>
struct Factory<v8::FunctionTemplate> : FactoryBase<v8::FunctionTemplate> {
static inline
return_t
New( FunctionCallback callback = NULL
, v8::Local<v8::Value> data = v8::Local<v8::Value>()
, v8::Local<v8::Signature> signature = v8::Local<v8::Signature>());
};
template <>
struct Factory<v8::Number> : FactoryBase<v8::Number> {
static inline return_t New(double value);
};
template <>
struct Factory<v8::NumberObject> : FactoryBase<v8::NumberObject> {
static inline return_t New(double value);
};
template <typename T>
struct IntegerFactory : FactoryBase<T> {
typedef typename FactoryBase<T>::return_t return_t;
static inline return_t New(int32_t value);
static inline return_t New(uint32_t value);
};
template <>
struct Factory<v8::Integer> : IntegerFactory<v8::Integer> {};
template <>
struct Factory<v8::Int32> : IntegerFactory<v8::Int32> {};
template <>
struct Factory<v8::Uint32> : FactoryBase<v8::Uint32> {
static inline return_t New(int32_t value);
static inline return_t New(uint32_t value);
};
template <>
struct Factory<v8::Object> : FactoryBase<v8::Object> {
static inline return_t New();
};
template <>
struct Factory<v8::ObjectTemplate> : FactoryBase<v8::ObjectTemplate> {
static inline return_t New();
};
template <>
struct Factory<v8::RegExp> : MaybeFactoryBase<v8::RegExp> {
static inline return_t New(
v8::Local<v8::String> pattern, v8::RegExp::Flags flags);
};
template <>
struct Factory<v8::Script> : MaybeFactoryBase<v8::Script> {
static inline return_t New( v8::Local<v8::String> source);
static inline return_t New( v8::Local<v8::String> source
, v8::ScriptOrigin const& origin);
};
template <>
struct Factory<v8::Signature> : FactoryBase<v8::Signature> {
typedef v8::Local<v8::FunctionTemplate> FTH;
static inline return_t New(FTH receiver = FTH());
};
template <>
struct Factory<v8::String> : MaybeFactoryBase<v8::String> {
static inline return_t New();
static inline return_t New(const char *value, int length = -1);
static inline return_t New(const uint16_t *value, int length = -1);
static inline return_t New(std::string const& value);
static inline return_t New(v8::String::ExternalStringResource * value);
static inline return_t New(ExternalOneByteStringResource * value);
};
template <>
struct Factory<v8::StringObject> : FactoryBase<v8::StringObject> {
static inline return_t New(v8::Local<v8::String> value);
};
} // end of namespace imp
#if (NODE_MODULE_VERSION >= 12)
namespace imp {
template <>
struct Factory<v8::UnboundScript> : MaybeFactoryBase<v8::UnboundScript> {
static inline return_t New( v8::Local<v8::String> source);
static inline return_t New( v8::Local<v8::String> source
, v8::ScriptOrigin const& origin);
};
} // end of namespace imp
# include "nan_implementation_12_inl.h"
#else // NODE_MODULE_VERSION >= 12
# include "nan_implementation_pre_12_inl.h"
#endif
//=== API ======================================================================
template <typename T>
typename imp::Factory<T>::return_t
New() {
return imp::Factory<T>::New();
}
template <typename T, typename A0>
typename imp::Factory<T>::return_t
New(A0 arg0) {
return imp::Factory<T>::New(arg0);
}
template <typename T, typename A0, typename A1>
typename imp::Factory<T>::return_t
New(A0 arg0, A1 arg1) {
return imp::Factory<T>::New(arg0, arg1);
}
template <typename T, typename A0, typename A1, typename A2>
typename imp::Factory<T>::return_t
New(A0 arg0, A1 arg1, A2 arg2) {
return imp::Factory<T>::New(arg0, arg1, arg2);
}
template <typename T, typename A0, typename A1, typename A2, typename A3>
typename imp::Factory<T>::return_t
New(A0 arg0, A1 arg1, A2 arg2, A3 arg3) {
return imp::Factory<T>::New(arg0, arg1, arg2, arg3);
}
// Note(agnat): When passing overloaded function pointers to template functions
// as generic arguments the compiler needs help in picking the right overload.
// These two functions handle New<Function> and New<FunctionTemplate> with
// all argument variations.
// v8::Function and v8::FunctionTemplate with one or two arguments
template <typename T>
typename imp::Factory<T>::return_t
New( FunctionCallback callback
, v8::Local<v8::Value> data = v8::Local<v8::Value>()) {
return imp::Factory<T>::New(callback, data);
}
// v8::Function and v8::FunctionTemplate with three arguments
template <typename T, typename A2>
typename imp::Factory<T>::return_t
New( FunctionCallback callback
, v8::Local<v8::Value> data = v8::Local<v8::Value>()
, A2 a2 = A2()) {
return imp::Factory<T>::New(callback, data, a2);
}
// Convenience
#if NODE_MODULE_VERSION < IOJS_3_0_MODULE_VERSION
template <typename T> inline v8::Local<T> New(v8::Handle<T> h);
#endif
#if NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION
template <typename T, typename M>
inline v8::Local<T> New(v8::Persistent<T, M> const& p);
#else
template <typename T> inline v8::Local<T> New(v8::Persistent<T> const& p);
#endif
template <typename T, typename M>
inline v8::Local<T> New(Persistent<T, M> const& p);
template <typename T>
inline v8::Local<T> New(Global<T> const& p);
inline
imp::Factory<v8::Boolean>::return_t
New(bool value) {
return New<v8::Boolean>(value);
}
inline
imp::Factory<v8::Int32>::return_t
New(int32_t value) {
return New<v8::Int32>(value);
}
inline
imp::Factory<v8::Uint32>::return_t
New(uint32_t value) {
return New<v8::Uint32>(value);
}
inline
imp::Factory<v8::Number>::return_t
New(double value) {
return New<v8::Number>(value);
}
inline
imp::Factory<v8::String>::return_t
New(std::string const& value) { // NOLINT(build/include_what_you_use)
return New<v8::String>(value);
}
inline
imp::Factory<v8::String>::return_t
New(const char * value, int length) {
return New<v8::String>(value, length);
}
inline
imp::Factory<v8::String>::return_t
New(const uint16_t * value, int length) {
return New<v8::String>(value, length);
}
inline
imp::Factory<v8::String>::return_t
New(const char * value) {
return New<v8::String>(value);
}
inline
imp::Factory<v8::String>::return_t
New(const uint16_t * value) {
return New<v8::String>(value);
}
inline
imp::Factory<v8::String>::return_t
New(v8::String::ExternalStringResource * value) {
return New<v8::String>(value);
}
inline
imp::Factory<v8::String>::return_t
New(ExternalOneByteStringResource * value) {
return New<v8::String>(value);
}
inline
imp::Factory<v8::RegExp>::return_t
New(v8::Local<v8::String> pattern, v8::RegExp::Flags flags) {
return New<v8::RegExp>(pattern, flags);
}
#endif // NAN_NEW_H_

155
test/gc/node_modules/nan/nan_object_wrap.h

@ -0,0 +1,155 @@
/*********************************************************************
* NAN - Native Abstractions for Node.js
*
* Copyright (c) 2016 NAN contributors
*
* MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md>
********************************************************************/
#ifndef NAN_OBJECT_WRAP_H_
#define NAN_OBJECT_WRAP_H_
class ObjectWrap {
public:
ObjectWrap() {
refs_ = 0;
}
virtual ~ObjectWrap() {
if (persistent().IsEmpty()) {
return;
}
assert(persistent().IsNearDeath());
persistent().ClearWeak();
persistent().Reset();
}
template <class T>
static inline T* Unwrap(v8::Local<v8::Object> object) {
assert(!object.IsEmpty());
assert(object->InternalFieldCount() > 0);
// Cast to ObjectWrap before casting to T. A direct cast from void
// to T won't work right when T has more than one base class.
void* ptr = GetInternalFieldPointer(object, 0);
ObjectWrap* wrap = static_cast<ObjectWrap*>(ptr);
return static_cast<T*>(wrap);
}
inline v8::Local<v8::Object> handle() {
return New(persistent());
}
inline Persistent<v8::Object>& persistent() {
return handle_;
}
protected:
inline void Wrap(v8::Local<v8::Object> object) {
assert(persistent().IsEmpty());
assert(object->InternalFieldCount() > 0);
SetInternalFieldPointer(object, 0, this);
persistent().Reset(object);
MakeWeak();
}
#if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 || \
(V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3))
inline void MakeWeak() {
persistent().v8::PersistentBase<v8::Object>::SetWeak(
this, WeakCallback, v8::WeakCallbackType::kParameter);
persistent().MarkIndependent();
}
#elif NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION
inline void MakeWeak() {
persistent().v8::PersistentBase<v8::Object>::SetWeak(this, WeakCallback);
persistent().MarkIndependent();
}
#else
inline void MakeWeak() {
persistent().persistent.MakeWeak(this, WeakCallback);
persistent().MarkIndependent();
}
#endif
/* Ref() marks the object as being attached to an event loop.
* Refed objects will not be garbage collected, even if
* all references are lost.
*/
virtual void Ref() {
assert(!persistent().IsEmpty());
persistent().ClearWeak();
refs_++;
}
/* Unref() marks an object as detached from the event loop. This is its
* default state. When an object with a "weak" reference changes from
* attached to detached state it will be freed. Be careful not to access
* the object after making this call as it might be gone!
* (A "weak reference" means an object that only has a
* persistant handle.)
*
* DO NOT CALL THIS FROM DESTRUCTOR
*/
virtual void Unref() {
assert(!persistent().IsEmpty());
assert(!persistent().IsWeak());
assert(refs_ > 0);
if (--refs_ == 0)
MakeWeak();
}
int refs_; // ro
private:
NAN_DISALLOW_ASSIGN_COPY_MOVE(ObjectWrap)
#if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 || \
(V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3))
static void
WeakCallback(v8::WeakCallbackInfo<ObjectWrap> const& info) {
ObjectWrap* wrap = info.GetParameter();
assert(wrap->refs_ == 0);
assert(wrap->handle_.IsNearDeath());
wrap->handle_.Reset();
delete wrap;
}
#elif NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION
static void
WeakCallback(v8::WeakCallbackData<v8::Object, ObjectWrap> const& data) {
ObjectWrap* wrap = data.GetParameter();
assert(wrap->refs_ == 0);
assert(wrap->handle_.IsNearDeath());
wrap->handle_.Reset();
delete wrap;
}
#else
static void WeakCallback(v8::Persistent<v8::Value> value, void *data) {
ObjectWrap *wrap = static_cast<ObjectWrap*>(data);
assert(wrap->refs_ == 0);
assert(wrap->handle_.IsNearDeath());
wrap->handle_.Reset();
delete wrap;
}
#endif
Persistent<v8::Object> handle_;
};
#endif // NAN_OBJECT_WRAP_H_

129
test/gc/node_modules/nan/nan_persistent_12_inl.h

@ -0,0 +1,129 @@
/*********************************************************************
* NAN - Native Abstractions for Node.js
*
* Copyright (c) 2016 NAN contributors
*
* MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md>
********************************************************************/
#ifndef NAN_PERSISTENT_12_INL_H_
#define NAN_PERSISTENT_12_INL_H_
template<typename T, typename M> class Persistent :
public v8::Persistent<T, M> {
public:
NAN_INLINE Persistent() : v8::Persistent<T, M>() {}
template<typename S> NAN_INLINE Persistent(v8::Local<S> that) :
v8::Persistent<T, M>(v8::Isolate::GetCurrent(), that) {}
template<typename S, typename M2>
NAN_INLINE Persistent(const v8::Persistent<S, M2> &that) :
v8::Persistent<T, M2>(v8::Isolate::GetCurrent(), that) {}
NAN_INLINE void Reset() { v8::PersistentBase<T>::Reset(); }
template <typename S>
NAN_INLINE void Reset(const v8::Local<S> &other) {
v8::PersistentBase<T>::Reset(v8::Isolate::GetCurrent(), other);
}
template <typename S>
NAN_INLINE void Reset(const v8::PersistentBase<S> &other) {
v8::PersistentBase<T>::Reset(v8::Isolate::GetCurrent(), other);
}
template<typename P>
NAN_INLINE void SetWeak(
P *parameter
, typename WeakCallbackInfo<P>::Callback callback
, WeakCallbackType type);
private:
NAN_INLINE T *operator*() const { return *PersistentBase<T>::persistent; }
template<typename S, typename M2>
NAN_INLINE void Copy(const Persistent<S, M2> &that) {
TYPE_CHECK(T, S);
this->Reset();
if (!that.IsEmpty()) {
this->Reset(that);
M::Copy(that, this);
}
}
};
#if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 || \
(V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3))
template<typename T>
class Global : public v8::Global<T> {
public:
NAN_INLINE Global() : v8::Global<T>() {}
template<typename S> NAN_INLINE Global(v8::Local<S> that) :
v8::Global<T>(v8::Isolate::GetCurrent(), that) {}
template<typename S>
NAN_INLINE Global(const v8::PersistentBase<S> &that) :
v8::Global<S>(v8::Isolate::GetCurrent(), that) {}
NAN_INLINE void Reset() { v8::PersistentBase<T>::Reset(); }
template <typename S>
NAN_INLINE void Reset(const v8::Local<S> &other) {
v8::PersistentBase<T>::Reset(v8::Isolate::GetCurrent(), other);
}
template <typename S>
NAN_INLINE void Reset(const v8::PersistentBase<S> &other) {
v8::PersistentBase<T>::Reset(v8::Isolate::GetCurrent(), other);
}
template<typename P>
NAN_INLINE void SetWeak(
P *parameter
, typename WeakCallbackInfo<P>::Callback callback
, WeakCallbackType type) {
reinterpret_cast<Persistent<T>*>(this)->SetWeak(
parameter, callback, type);
}
};
#else
template<typename T>
class Global : public v8::UniquePersistent<T> {
public:
NAN_INLINE Global() : v8::UniquePersistent<T>() {}
template<typename S> NAN_INLINE Global(v8::Local<S> that) :
v8::UniquePersistent<T>(v8::Isolate::GetCurrent(), that) {}
template<typename S>
NAN_INLINE Global(const v8::PersistentBase<S> &that) :
v8::UniquePersistent<S>(v8::Isolate::GetCurrent(), that) {}
NAN_INLINE void Reset() { v8::PersistentBase<T>::Reset(); }
template <typename S>
NAN_INLINE void Reset(const v8::Local<S> &other) {
v8::PersistentBase<T>::Reset(v8::Isolate::GetCurrent(), other);
}
template <typename S>
NAN_INLINE void Reset(const v8::PersistentBase<S> &other) {
v8::PersistentBase<T>::Reset(v8::Isolate::GetCurrent(), other);
}
template<typename P>
NAN_INLINE void SetWeak(
P *parameter
, typename WeakCallbackInfo<P>::Callback callback
, WeakCallbackType type) {
reinterpret_cast<Persistent<T>*>(this)->SetWeak(
parameter, callback, type);
}
};
#endif
#endif // NAN_PERSISTENT_12_INL_H_

242
test/gc/node_modules/nan/nan_persistent_pre_12_inl.h

@ -0,0 +1,242 @@
/*********************************************************************
* NAN - Native Abstractions for Node.js
*
* Copyright (c) 2016 NAN contributors
*
* MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md>
********************************************************************/
#ifndef NAN_PERSISTENT_PRE_12_INL_H_
#define NAN_PERSISTENT_PRE_12_INL_H_
template<typename T>
class PersistentBase {
v8::Persistent<T> persistent;
template<typename U>
friend v8::Local<U> New(const PersistentBase<U> &p);
template<typename U, typename M>
friend v8::Local<U> New(const Persistent<U, M> &p);
template<typename U>
friend v8::Local<U> New(const Global<U> &p);
template<typename S> friend class ReturnValue;
public:
NAN_INLINE PersistentBase() :
persistent() {}
NAN_INLINE void Reset() {
persistent.Dispose();
persistent.Clear();
}
template<typename S>
NAN_INLINE void Reset(const v8::Local<S> &other) {
TYPE_CHECK(T, S);
if (!persistent.IsEmpty()) {
persistent.Dispose();
}
if (other.IsEmpty()) {
persistent.Clear();
} else {
persistent = v8::Persistent<T>::New(other);
}
}
template<typename S>
NAN_INLINE void Reset(const PersistentBase<S> &other) {
TYPE_CHECK(T, S);
if (!persistent.IsEmpty()) {
persistent.Dispose();
}
if (other.IsEmpty()) {
persistent.Clear();
} else {
persistent = v8::Persistent<T>::New(other.persistent);
}
}
NAN_INLINE bool IsEmpty() const { return persistent.IsEmpty(); }
NAN_INLINE void Empty() { persistent.Clear(); }
template<typename S>
NAN_INLINE bool operator==(const PersistentBase<S> &that) {
return this->persistent == that.persistent;
}
template<typename S>
NAN_INLINE bool operator==(const v8::Local<S> &that) {
return this->persistent == that;
}
template<typename S>
NAN_INLINE bool operator!=(const PersistentBase<S> &that) {
return !operator==(that);
}
template<typename S>
NAN_INLINE bool operator!=(const v8::Local<S> &that) {
return !operator==(that);
}
template<typename P>
NAN_INLINE void SetWeak(
P *parameter
, typename WeakCallbackInfo<P>::Callback callback
, WeakCallbackType type);
NAN_INLINE void ClearWeak() { persistent.ClearWeak(); }
NAN_INLINE void MarkIndependent() { persistent.MarkIndependent(); }
NAN_INLINE bool IsIndependent() const { return persistent.IsIndependent(); }
NAN_INLINE bool IsNearDeath() const { return persistent.IsNearDeath(); }
NAN_INLINE bool IsWeak() const { return persistent.IsWeak(); }
private:
NAN_INLINE explicit PersistentBase(v8::Persistent<T> that) :
persistent(that) { }
NAN_INLINE explicit PersistentBase(T *val) : persistent(val) {}
template<typename S, typename M> friend class Persistent;
template<typename S> friend class Global;
friend class ObjectWrap;
};
template<typename T>
class NonCopyablePersistentTraits {
public:
typedef Persistent<T, NonCopyablePersistentTraits<T> >
NonCopyablePersistent;
static const bool kResetInDestructor = false;
template<typename S, typename M>
NAN_INLINE static void Copy(const Persistent<S, M> &source,
NonCopyablePersistent *dest) {
Uncompilable<v8::Object>();
}
template<typename O> NAN_INLINE static void Uncompilable() {
TYPE_CHECK(O, v8::Primitive);
}
};
template<typename T>
struct CopyablePersistentTraits {
typedef Persistent<T, CopyablePersistentTraits<T> > CopyablePersistent;
static const bool kResetInDestructor = true;
template<typename S, typename M>
static NAN_INLINE void Copy(const Persistent<S, M> &source,
CopyablePersistent *dest) {}
};
template<typename T, typename M> class Persistent :
public PersistentBase<T> {
public:
NAN_INLINE Persistent() {}
template<typename S> NAN_INLINE Persistent(v8::Handle<S> that)
: PersistentBase<T>(v8::Persistent<T>::New(that)) {
TYPE_CHECK(T, S);
}
NAN_INLINE Persistent(const Persistent &that) : PersistentBase<T>() {
Copy(that);
}
template<typename S, typename M2>
NAN_INLINE Persistent(const Persistent<S, M2> &that) :
PersistentBase<T>() {
Copy(that);
}
NAN_INLINE Persistent &operator=(const Persistent &that) {
Copy(that);
return *this;
}
template <class S, class M2>
NAN_INLINE Persistent &operator=(const Persistent<S, M2> &that) {
Copy(that);
return *this;
}
NAN_INLINE ~Persistent() {
if (M::kResetInDestructor) this->Reset();
}
private:
NAN_INLINE T *operator*() const { return *PersistentBase<T>::persistent; }
template<typename S, typename M2>
NAN_INLINE void Copy(const Persistent<S, M2> &that) {
TYPE_CHECK(T, S);
this->Reset();
if (!that.IsEmpty()) {
this->persistent = v8::Persistent<T>::New(that.persistent);
M::Copy(that, this);
}
}
};
template<typename T>
class Global : public PersistentBase<T> {
struct RValue {
NAN_INLINE explicit RValue(Global* obj) : object(obj) {}
Global* object;
};
public:
NAN_INLINE Global() : PersistentBase<T>(0) { }
template <typename S>
NAN_INLINE Global(v8::Local<S> that)
: PersistentBase<T>(v8::Persistent<T>::New(that)) {
TYPE_CHECK(T, S);
}
template <typename S>
NAN_INLINE Global(const PersistentBase<S> &that)
: PersistentBase<T>(that) {
TYPE_CHECK(T, S);
}
/**
* Move constructor.
*/
NAN_INLINE Global(RValue rvalue)
: PersistentBase<T>(rvalue.object->persistent) {
rvalue.object->Reset();
}
NAN_INLINE ~Global() { this->Reset(); }
/**
* Move via assignment.
*/
template<typename S>
NAN_INLINE Global &operator=(Global<S> rhs) {
TYPE_CHECK(T, S);
this->Reset(rhs.persistent);
rhs.Reset();
return *this;
}
/**
* Cast operator for moves.
*/
NAN_INLINE operator RValue() { return RValue(this); }
/**
* Pass allows returning uniques from functions, etc.
*/
Global Pass() { return Global(RValue(this)); }
private:
Global(Global &);
void operator=(Global &);
template<typename S> friend class ReturnValue;
};
#endif // NAN_PERSISTENT_PRE_12_INL_H_

305
test/gc/node_modules/nan/nan_string_bytes.h

@ -0,0 +1,305 @@
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
#ifndef NAN_STRING_BYTES_H_
#define NAN_STRING_BYTES_H_
// Decodes a v8::Local<v8::String> or Buffer to a raw char*
namespace imp {
using v8::Local;
using v8::Object;
using v8::String;
using v8::Value;
//// Base 64 ////
#define base64_encoded_size(size) ((size + 2 - ((size + 2) % 3)) / 3 * 4)
//// HEX ////
static bool contains_non_ascii_slow(const char* buf, size_t len) {
for (size_t i = 0; i < len; ++i) {
if (buf[i] & 0x80) return true;
}
return false;
}
static bool contains_non_ascii(const char* src, size_t len) {
if (len < 16) {
return contains_non_ascii_slow(src, len);
}
const unsigned bytes_per_word = sizeof(void*);
const unsigned align_mask = bytes_per_word - 1;
const unsigned unaligned = reinterpret_cast<uintptr_t>(src) & align_mask;
if (unaligned > 0) {
const unsigned n = bytes_per_word - unaligned;
if (contains_non_ascii_slow(src, n)) return true;
src += n;
len -= n;
}
#if defined(__x86_64__) || defined(_WIN64)
const uintptr_t mask = 0x8080808080808080ll;
#else
const uintptr_t mask = 0x80808080l;
#endif
const uintptr_t* srcw = reinterpret_cast<const uintptr_t*>(src);
for (size_t i = 0, n = len / bytes_per_word; i < n; ++i) {
if (srcw[i] & mask) return true;
}
const unsigned remainder = len & align_mask;
if (remainder > 0) {
const size_t offset = len - remainder;
if (contains_non_ascii_slow(src + offset, remainder)) return true;
}
return false;
}
static void force_ascii_slow(const char* src, char* dst, size_t len) {
for (size_t i = 0; i < len; ++i) {
dst[i] = src[i] & 0x7f;
}
}
static void force_ascii(const char* src, char* dst, size_t len) {
if (len < 16) {
force_ascii_slow(src, dst, len);
return;
}
const unsigned bytes_per_word = sizeof(void*);
const unsigned align_mask = bytes_per_word - 1;
const unsigned src_unalign = reinterpret_cast<uintptr_t>(src) & align_mask;
const unsigned dst_unalign = reinterpret_cast<uintptr_t>(dst) & align_mask;
if (src_unalign > 0) {
if (src_unalign == dst_unalign) {
const unsigned unalign = bytes_per_word - src_unalign;
force_ascii_slow(src, dst, unalign);
src += unalign;
dst += unalign;
len -= src_unalign;
} else {
force_ascii_slow(src, dst, len);
return;
}
}
#if defined(__x86_64__) || defined(_WIN64)
const uintptr_t mask = ~0x8080808080808080ll;
#else
const uintptr_t mask = ~0x80808080l;
#endif
const uintptr_t* srcw = reinterpret_cast<const uintptr_t*>(src);
uintptr_t* dstw = reinterpret_cast<uintptr_t*>(dst);
for (size_t i = 0, n = len / bytes_per_word; i < n; ++i) {
dstw[i] = srcw[i] & mask;
}
const unsigned remainder = len & align_mask;
if (remainder > 0) {
const size_t offset = len - remainder;
force_ascii_slow(src + offset, dst + offset, remainder);
}
}
static size_t base64_encode(const char* src,
size_t slen,
char* dst,
size_t dlen) {
// We know how much we'll write, just make sure that there's space.
assert(dlen >= base64_encoded_size(slen) &&
"not enough space provided for base64 encode");
dlen = base64_encoded_size(slen);
unsigned a;
unsigned b;
unsigned c;
unsigned i;
unsigned k;
unsigned n;
static const char table[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz"
"0123456789+/";
i = 0;
k = 0;
n = slen / 3 * 3;
while (i < n) {
a = src[i + 0] & 0xff;
b = src[i + 1] & 0xff;
c = src[i + 2] & 0xff;
dst[k + 0] = table[a >> 2];
dst[k + 1] = table[((a & 3) << 4) | (b >> 4)];
dst[k + 2] = table[((b & 0x0f) << 2) | (c >> 6)];
dst[k + 3] = table[c & 0x3f];
i += 3;
k += 4;
}
if (n != slen) {
switch (slen - n) {
case 1:
a = src[i + 0] & 0xff;
dst[k + 0] = table[a >> 2];
dst[k + 1] = table[(a & 3) << 4];
dst[k + 2] = '=';
dst[k + 3] = '=';
break;
case 2:
a = src[i + 0] & 0xff;
b = src[i + 1] & 0xff;
dst[k + 0] = table[a >> 2];
dst[k + 1] = table[((a & 3) << 4) | (b >> 4)];
dst[k + 2] = table[(b & 0x0f) << 2];
dst[k + 3] = '=';
break;
}
}
return dlen;
}
static size_t hex_encode(const char* src, size_t slen, char* dst, size_t dlen) {
// We know how much we'll write, just make sure that there's space.
assert(dlen >= slen * 2 &&
"not enough space provided for hex encode");
dlen = slen * 2;
for (uint32_t i = 0, k = 0; k < dlen; i += 1, k += 2) {
static const char hex[] = "0123456789abcdef";
uint8_t val = static_cast<uint8_t>(src[i]);
dst[k + 0] = hex[val >> 4];
dst[k + 1] = hex[val & 15];
}
return dlen;
}
static Local<Value> Encode(const char* buf,
size_t buflen,
enum Encoding encoding) {
assert(buflen <= node::Buffer::kMaxLength);
if (!buflen && encoding != BUFFER)
return New("").ToLocalChecked();
Local<String> val;
switch (encoding) {
case BUFFER:
return CopyBuffer(buf, buflen).ToLocalChecked();
case ASCII:
if (contains_non_ascii(buf, buflen)) {
char* out = new char[buflen];
force_ascii(buf, out, buflen);
val = New<String>(out, buflen).ToLocalChecked();
delete[] out;
} else {
val = New<String>(buf, buflen).ToLocalChecked();
}
break;
case UTF8:
val = New<String>(buf, buflen).ToLocalChecked();
break;
case BINARY: {
// TODO(isaacs) use ExternalTwoByteString?
const unsigned char *cbuf = reinterpret_cast<const unsigned char*>(buf);
uint16_t * twobytebuf = new uint16_t[buflen];
for (size_t i = 0; i < buflen; i++) {
// XXX is the following line platform independent?
twobytebuf[i] = cbuf[i];
}
val = New<String>(twobytebuf, buflen).ToLocalChecked();
delete[] twobytebuf;
break;
}
case BASE64: {
size_t dlen = base64_encoded_size(buflen);
char* dst = new char[dlen];
size_t written = base64_encode(buf, buflen, dst, dlen);
assert(written == dlen);
val = New<String>(dst, dlen).ToLocalChecked();
delete[] dst;
break;
}
case UCS2: {
const uint16_t* data = reinterpret_cast<const uint16_t*>(buf);
val = New<String>(data, buflen / 2).ToLocalChecked();
break;
}
case HEX: {
size_t dlen = buflen * 2;
char* dst = new char[dlen];
size_t written = hex_encode(buf, buflen, dst, dlen);
assert(written == dlen);
val = New<String>(dst, dlen).ToLocalChecked();
delete[] dst;
break;
}
default:
assert(0 && "unknown encoding");
break;
}
return val;
}
#undef base64_encoded_size
} // end of namespace imp
#endif // NAN_STRING_BYTES_H_

87
test/gc/node_modules/nan/nan_typedarray_contents.h

@ -0,0 +1,87 @@
/*********************************************************************
* NAN - Native Abstractions for Node.js
*
* Copyright (c) 2016 NAN contributors
*
* MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md>
********************************************************************/
#ifndef NAN_TYPEDARRAY_CONTENTS_H_
#define NAN_TYPEDARRAY_CONTENTS_H_
template<typename T>
class TypedArrayContents {
public:
NAN_INLINE explicit TypedArrayContents(v8::Local<v8::Value> from) :
length_(0), data_(NULL) {
size_t length = 0;
void* data = NULL;
#if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 || \
(V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3))
if (from->IsArrayBufferView()) {
v8::Local<v8::ArrayBufferView> array =
v8::Local<v8::ArrayBufferView>::Cast(from);
const size_t byte_length = array->ByteLength();
const ptrdiff_t byte_offset = array->ByteOffset();
v8::Local<v8::ArrayBuffer> buffer = array->Buffer();
length = byte_length / sizeof(T);
data = static_cast<char*>(buffer->GetContents().Data()) + byte_offset;
}
#else
if (from->IsObject() && !from->IsNull()) {
v8::Local<v8::Object> array = v8::Local<v8::Object>::Cast(from);
MaybeLocal<v8::Value> buffer = Get(array,
New<v8::String>("buffer").ToLocalChecked());
MaybeLocal<v8::Value> byte_length = Get(array,
New<v8::String>("byteLength").ToLocalChecked());
MaybeLocal<v8::Value> byte_offset = Get(array,
New<v8::String>("byteOffset").ToLocalChecked());
if (!buffer.IsEmpty() &&
!byte_length.IsEmpty() && byte_length.ToLocalChecked()->IsUint32() &&
!byte_offset.IsEmpty() && byte_offset.ToLocalChecked()->IsUint32()) {
data = array->GetIndexedPropertiesExternalArrayData();
if(data) {
length = byte_length.ToLocalChecked()->Uint32Value() / sizeof(T);
}
}
}
#endif
#if defined(_MSC_VER) && _MSC_VER >= 1900 || __cplusplus >= 201103L
assert(reinterpret_cast<uintptr_t>(data) % alignof (T) == 0);
#elif defined(_MSC_VER) && _MSC_VER >= 1600 || defined(__GNUC__)
assert(reinterpret_cast<uintptr_t>(data) % __alignof(T) == 0);
#else
assert(reinterpret_cast<uintptr_t>(data) % sizeof (T) == 0);
#endif
length_ = length;
data_ = static_cast<T*>(data);
}
NAN_INLINE size_t length() const { return length_; }
NAN_INLINE T* operator*() { return data_; }
NAN_INLINE const T* operator*() const { return data_; }
private:
NAN_DISALLOW_ASSIGN_COPY_MOVE(TypedArrayContents)
//Disable heap allocation
void *operator new(size_t size);
void operator delete(void *, size_t);
size_t length_;
T* data_;
};
#endif // NAN_TYPEDARRAY_CONTENTS_H_

422
test/gc/node_modules/nan/nan_weak.h

@ -0,0 +1,422 @@
/*********************************************************************
* NAN - Native Abstractions for Node.js
*
* Copyright (c) 2016 NAN contributors
*
* MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md>
********************************************************************/
#ifndef NAN_WEAK_H_
#define NAN_WEAK_H_
static const int kInternalFieldsInWeakCallback = 2;
static const int kNoInternalFieldIndex = -1;
#if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 || \
(V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3))
# define NAN_WEAK_PARAMETER_CALLBACK_DATA_TYPE_ \
v8::WeakCallbackInfo<WeakCallbackInfo<T> > const&
# define NAN_WEAK_TWOFIELD_CALLBACK_DATA_TYPE_ \
NAN_WEAK_PARAMETER_CALLBACK_DATA_TYPE_
# define NAN_WEAK_PARAMETER_CALLBACK_SIG_ NAN_WEAK_PARAMETER_CALLBACK_DATA_TYPE_
# define NAN_WEAK_TWOFIELD_CALLBACK_SIG_ NAN_WEAK_TWOFIELD_CALLBACK_DATA_TYPE_
#elif NODE_MODULE_VERSION > IOJS_1_1_MODULE_VERSION
# define NAN_WEAK_PARAMETER_CALLBACK_DATA_TYPE_ \
v8::PhantomCallbackData<WeakCallbackInfo<T> > const&
# define NAN_WEAK_TWOFIELD_CALLBACK_DATA_TYPE_ \
NAN_WEAK_PARAMETER_CALLBACK_DATA_TYPE_
# define NAN_WEAK_PARAMETER_CALLBACK_SIG_ NAN_WEAK_PARAMETER_CALLBACK_DATA_TYPE_
# define NAN_WEAK_TWOFIELD_CALLBACK_SIG_ NAN_WEAK_TWOFIELD_CALLBACK_DATA_TYPE_
#elif NODE_MODULE_VERSION > NODE_0_12_MODULE_VERSION
# define NAN_WEAK_PARAMETER_CALLBACK_DATA_TYPE_ \
v8::PhantomCallbackData<WeakCallbackInfo<T> > const&
# define NAN_WEAK_TWOFIELD_CALLBACK_DATA_TYPE_ \
v8::InternalFieldsCallbackData<WeakCallbackInfo<T>, void> const&
# define NAN_WEAK_PARAMETER_CALLBACK_SIG_ NAN_WEAK_PARAMETER_CALLBACK_DATA_TYPE_
# define NAN_WEAK_TWOFIELD_CALLBACK_SIG_ NAN_WEAK_TWOFIELD_CALLBACK_DATA_TYPE_
#elif NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION
# define NAN_WEAK_CALLBACK_DATA_TYPE_ \
v8::WeakCallbackData<S, WeakCallbackInfo<T> > const&
# define NAN_WEAK_CALLBACK_SIG_ NAN_WEAK_CALLBACK_DATA_TYPE_
#else
# define NAN_WEAK_CALLBACK_DATA_TYPE_ void *
# define NAN_WEAK_CALLBACK_SIG_ \
v8::Persistent<v8::Value>, NAN_WEAK_CALLBACK_DATA_TYPE_
#endif
template<typename T>
class WeakCallbackInfo {
public:
typedef void (*Callback)(const WeakCallbackInfo<T>& data);
WeakCallbackInfo(
Persistent<v8::Value> *persistent
, Callback callback
, void *parameter
, void *field1 = 0
, void *field2 = 0) :
callback_(callback), isolate_(0), parameter_(parameter) {
std::memcpy(&persistent_, persistent, sizeof (v8::Persistent<v8::Value>));
internal_fields_[0] = field1;
internal_fields_[1] = field2;
}
NAN_INLINE v8::Isolate *GetIsolate() const { return isolate_; }
NAN_INLINE T *GetParameter() const { return static_cast<T*>(parameter_); }
NAN_INLINE void *GetInternalField(int index) const {
assert((index == 0 || index == 1) && "internal field index out of bounds");
if (index == 0) {
return internal_fields_[0];
} else {
return internal_fields_[1];
}
}
private:
NAN_DISALLOW_ASSIGN_COPY_MOVE(WeakCallbackInfo)
Callback callback_;
v8::Isolate *isolate_;
void *parameter_;
void *internal_fields_[kInternalFieldsInWeakCallback];
v8::Persistent<v8::Value> persistent_;
template<typename S, typename M> friend class Persistent;
template<typename S> friend class PersistentBase;
#if NODE_MODULE_VERSION <= NODE_0_12_MODULE_VERSION
# if NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION
template<typename S>
static void invoke(NAN_WEAK_CALLBACK_SIG_ data);
template<typename S>
static WeakCallbackInfo *unwrap(NAN_WEAK_CALLBACK_DATA_TYPE_ data);
# else
static void invoke(NAN_WEAK_CALLBACK_SIG_ data);
static WeakCallbackInfo *unwrap(NAN_WEAK_CALLBACK_DATA_TYPE_ data);
# endif
#else
static void invokeparameter(NAN_WEAK_PARAMETER_CALLBACK_SIG_ data);
static void invoketwofield(NAN_WEAK_TWOFIELD_CALLBACK_SIG_ data);
static WeakCallbackInfo *unwrapparameter(
NAN_WEAK_PARAMETER_CALLBACK_DATA_TYPE_ data);
static WeakCallbackInfo *unwraptwofield(
NAN_WEAK_TWOFIELD_CALLBACK_DATA_TYPE_ data);
#endif
};
#if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 || \
(V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3))
template<typename T>
void
WeakCallbackInfo<T>::invokeparameter(NAN_WEAK_PARAMETER_CALLBACK_SIG_ data) {
WeakCallbackInfo<T> *cbinfo = unwrapparameter(data);
if (data.IsFirstPass()) {
cbinfo->persistent_.Reset();
data.SetSecondPassCallback(invokeparameter);
} else {
cbinfo->callback_(*cbinfo);
delete cbinfo;
}
}
template<typename T>
void
WeakCallbackInfo<T>::invoketwofield(NAN_WEAK_TWOFIELD_CALLBACK_SIG_ data) {
WeakCallbackInfo<T> *cbinfo = unwraptwofield(data);
if (data.IsFirstPass()) {
cbinfo->persistent_.Reset();
data.SetSecondPassCallback(invoketwofield);
} else {
cbinfo->callback_(*cbinfo);
delete cbinfo;
}
}
template<typename T>
WeakCallbackInfo<T> *WeakCallbackInfo<T>::unwrapparameter(
NAN_WEAK_PARAMETER_CALLBACK_DATA_TYPE_ data) {
WeakCallbackInfo<T> *cbinfo =
static_cast<WeakCallbackInfo<T>*>(data.GetParameter());
cbinfo->isolate_ = data.GetIsolate();
return cbinfo;
}
template<typename T>
WeakCallbackInfo<T> *WeakCallbackInfo<T>::unwraptwofield(
NAN_WEAK_TWOFIELD_CALLBACK_DATA_TYPE_ data) {
WeakCallbackInfo<T> *cbinfo =
static_cast<WeakCallbackInfo<T>*>(data.GetInternalField(0));
cbinfo->isolate_ = data.GetIsolate();
return cbinfo;
}
#undef NAN_WEAK_PARAMETER_CALLBACK_SIG_
#undef NAN_WEAK_TWOFIELD_CALLBACK_SIG_
#undef NAN_WEAK_PARAMETER_CALLBACK_DATA_TYPE_
#undef NAN_WEAK_TWOFIELD_CALLBACK_DATA_TYPE_
# elif NODE_MODULE_VERSION > NODE_0_12_MODULE_VERSION
template<typename T>
void
WeakCallbackInfo<T>::invokeparameter(NAN_WEAK_PARAMETER_CALLBACK_SIG_ data) {
WeakCallbackInfo<T> *cbinfo = unwrapparameter(data);
cbinfo->persistent_.Reset();
cbinfo->callback_(*cbinfo);
delete cbinfo;
}
template<typename T>
void
WeakCallbackInfo<T>::invoketwofield(NAN_WEAK_TWOFIELD_CALLBACK_SIG_ data) {
WeakCallbackInfo<T> *cbinfo = unwraptwofield(data);
cbinfo->persistent_.Reset();
cbinfo->callback_(*cbinfo);
delete cbinfo;
}
template<typename T>
WeakCallbackInfo<T> *WeakCallbackInfo<T>::unwrapparameter(
NAN_WEAK_PARAMETER_CALLBACK_DATA_TYPE_ data) {
WeakCallbackInfo<T> *cbinfo =
static_cast<WeakCallbackInfo<T>*>(data.GetParameter());
cbinfo->isolate_ = data.GetIsolate();
return cbinfo;
}
template<typename T>
WeakCallbackInfo<T> *WeakCallbackInfo<T>::unwraptwofield(
NAN_WEAK_TWOFIELD_CALLBACK_DATA_TYPE_ data) {
WeakCallbackInfo<T> *cbinfo =
static_cast<WeakCallbackInfo<T>*>(data.GetInternalField1());
cbinfo->isolate_ = data.GetIsolate();
return cbinfo;
}
#undef NAN_WEAK_PARAMETER_CALLBACK_SIG_
#undef NAN_WEAK_TWOFIELD_CALLBACK_SIG_
#undef NAN_WEAK_PARAMETER_CALLBACK_DATA_TYPE_
#undef NAN_WEAK_TWOFIELD_CALLBACK_DATA_TYPE_
#elif NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION
template<typename T>
template<typename S>
void WeakCallbackInfo<T>::invoke(NAN_WEAK_CALLBACK_SIG_ data) {
WeakCallbackInfo<T> *cbinfo = unwrap(data);
cbinfo->persistent_.Reset();
cbinfo->callback_(*cbinfo);
delete cbinfo;
}
template<typename T>
template<typename S>
WeakCallbackInfo<T> *WeakCallbackInfo<T>::unwrap(
NAN_WEAK_CALLBACK_DATA_TYPE_ data) {
void *parameter = data.GetParameter();
WeakCallbackInfo<T> *cbinfo =
static_cast<WeakCallbackInfo<T>*>(parameter);
cbinfo->isolate_ = data.GetIsolate();
return cbinfo;
}
#undef NAN_WEAK_CALLBACK_SIG_
#undef NAN_WEAK_CALLBACK_DATA_TYPE_
#else
template<typename T>
void WeakCallbackInfo<T>::invoke(NAN_WEAK_CALLBACK_SIG_ data) {
WeakCallbackInfo<T> *cbinfo = unwrap(data);
cbinfo->persistent_.Dispose();
cbinfo->persistent_.Clear();
cbinfo->callback_(*cbinfo);
delete cbinfo;
}
template<typename T>
WeakCallbackInfo<T> *WeakCallbackInfo<T>::unwrap(
NAN_WEAK_CALLBACK_DATA_TYPE_ data) {
WeakCallbackInfo<T> *cbinfo =
static_cast<WeakCallbackInfo<T>*>(data);
cbinfo->isolate_ = v8::Isolate::GetCurrent();
return cbinfo;
}
#undef NAN_WEAK_CALLBACK_SIG_
#undef NAN_WEAK_CALLBACK_DATA_TYPE_
#endif
#if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 || \
(V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3))
template<typename T, typename M>
template<typename P>
NAN_INLINE void Persistent<T, M>::SetWeak(
P *parameter
, typename WeakCallbackInfo<P>::Callback callback
, WeakCallbackType type) {
WeakCallbackInfo<P> *wcbd;
if (type == WeakCallbackType::kParameter) {
wcbd = new WeakCallbackInfo<P>(
reinterpret_cast<Persistent<v8::Value>*>(this)
, callback
, parameter);
v8::PersistentBase<T>::SetWeak(
wcbd
, WeakCallbackInfo<P>::invokeparameter
, type);
} else {
v8::Local<T>* self = reinterpret_cast<v8::Local<T>*>(this);
assert((*self)->IsObject());
int count = (*self)->InternalFieldCount();
void *internal_fields[kInternalFieldsInWeakCallback] = {0, 0};
for (int i = 0; i < count && i < kInternalFieldsInWeakCallback; i++) {
internal_fields[i] = (*self)->GetAlignedPointerFromInternalField(i);
}
wcbd = new WeakCallbackInfo<P>(
reinterpret_cast<Persistent<v8::Value>*>(this)
, callback
, 0
, internal_fields[0]
, internal_fields[1]);
(*self)->SetAlignedPointerInInternalField(0, wcbd);
v8::PersistentBase<T>::SetWeak(
static_cast<WeakCallbackInfo<P>*>(0)
, WeakCallbackInfo<P>::invoketwofield
, type);
}
}
#elif NODE_MODULE_VERSION > IOJS_1_1_MODULE_VERSION
template<typename T, typename M>
template<typename P>
NAN_INLINE void Persistent<T, M>::SetWeak(
P *parameter
, typename WeakCallbackInfo<P>::Callback callback
, WeakCallbackType type) {
WeakCallbackInfo<P> *wcbd;
if (type == WeakCallbackType::kParameter) {
wcbd = new WeakCallbackInfo<P>(
reinterpret_cast<Persistent<v8::Value>*>(this)
, callback
, parameter);
v8::PersistentBase<T>::SetPhantom(
wcbd
, WeakCallbackInfo<P>::invokeparameter);
} else {
v8::Local<T>* self = reinterpret_cast<v8::Local<T>*>(this);
assert((*self)->IsObject());
int count = (*self)->InternalFieldCount();
void *internal_fields[kInternalFieldsInWeakCallback] = {0, 0};
for (int i = 0; i < count && i < kInternalFieldsInWeakCallback; i++) {
internal_fields[i] = (*self)->GetAlignedPointerFromInternalField(i);
}
wcbd = new WeakCallbackInfo<P>(
reinterpret_cast<Persistent<v8::Value>*>(this)
, callback
, 0
, internal_fields[0]
, internal_fields[1]);
(*self)->SetAlignedPointerInInternalField(0, wcbd);
v8::PersistentBase<T>::SetPhantom(
static_cast<WeakCallbackInfo<P>*>(0)
, WeakCallbackInfo<P>::invoketwofield
, 0
, count > 1 ? 1 : kNoInternalFieldIndex);
}
}
#elif NODE_MODULE_VERSION > NODE_0_12_MODULE_VERSION
template<typename T, typename M>
template<typename P>
NAN_INLINE void Persistent<T, M>::SetWeak(
P *parameter
, typename WeakCallbackInfo<P>::Callback callback
, WeakCallbackType type) {
WeakCallbackInfo<P> *wcbd;
if (type == WeakCallbackType::kParameter) {
wcbd = new WeakCallbackInfo<P>(
reinterpret_cast<Persistent<v8::Value>*>(this)
, callback
, parameter);
v8::PersistentBase<T>::SetPhantom(
wcbd
, WeakCallbackInfo<P>::invokeparameter);
} else {
v8::Local<T>* self = reinterpret_cast<v8::Local<T>*>(this);
assert((*self)->IsObject());
int count = (*self)->InternalFieldCount();
void *internal_fields[kInternalFieldsInWeakCallback] = {0, 0};
for (int i = 0; i < count && i < kInternalFieldsInWeakCallback; i++) {
internal_fields[i] = (*self)->GetAlignedPointerFromInternalField(i);
}
wcbd = new WeakCallbackInfo<P>(
reinterpret_cast<Persistent<v8::Value>*>(this)
, callback
, 0
, internal_fields[0]
, internal_fields[1]);
(*self)->SetAlignedPointerInInternalField(0, wcbd);
v8::PersistentBase<T>::SetPhantom(
WeakCallbackInfo<P>::invoketwofield
, 0
, count > 1 ? 1 : kNoInternalFieldIndex);
}
}
#elif NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION
template<typename T, typename M>
template<typename P>
NAN_INLINE void Persistent<T, M>::SetWeak(
P *parameter
, typename WeakCallbackInfo<P>::Callback callback
, WeakCallbackType type) {
WeakCallbackInfo<P> *wcbd;
if (type == WeakCallbackType::kParameter) {
wcbd = new WeakCallbackInfo<P>(
reinterpret_cast<Persistent<v8::Value>*>(this)
, callback
, parameter);
v8::PersistentBase<T>::SetWeak(wcbd, WeakCallbackInfo<P>::invoke);
} else {
v8::Local<T>* self = reinterpret_cast<v8::Local<T>*>(this);
assert((*self)->IsObject());
int count = (*self)->InternalFieldCount();
void *internal_fields[kInternalFieldsInWeakCallback] = {0, 0};
for (int i = 0; i < count && i < kInternalFieldsInWeakCallback; i++) {
internal_fields[i] = (*self)->GetAlignedPointerFromInternalField(i);
}
wcbd = new WeakCallbackInfo<P>(
reinterpret_cast<Persistent<v8::Value>*>(this)
, callback
, 0
, internal_fields[0]
, internal_fields[1]);
v8::PersistentBase<T>::SetWeak(wcbd, WeakCallbackInfo<P>::invoke);
}
}
#else
template<typename T>
template<typename P>
NAN_INLINE void PersistentBase<T>::SetWeak(
P *parameter
, typename WeakCallbackInfo<P>::Callback callback
, WeakCallbackType type) {
WeakCallbackInfo<P> *wcbd;
if (type == WeakCallbackType::kParameter) {
wcbd = new WeakCallbackInfo<P>(
reinterpret_cast<Persistent<v8::Value>*>(this)
, callback
, parameter);
persistent.MakeWeak(wcbd, WeakCallbackInfo<P>::invoke);
} else {
v8::Local<T>* self = reinterpret_cast<v8::Local<T>*>(this);
assert((*self)->IsObject());
int count = (*self)->InternalFieldCount();
void *internal_fields[kInternalFieldsInWeakCallback] = {0, 0};
for (int i = 0; i < count && i < kInternalFieldsInWeakCallback; i++) {
internal_fields[i] = (*self)->GetPointerFromInternalField(i);
}
wcbd = new WeakCallbackInfo<P>(
reinterpret_cast<Persistent<v8::Value>*>(this)
, callback
, 0
, internal_fields[0]
, internal_fields[1]);
persistent.MakeWeak(wcbd, WeakCallbackInfo<P>::invoke);
}
}
#endif
#endif // NAN_WEAK_H_

121
test/gc/node_modules/nan/package.json

@ -0,0 +1,121 @@
{
"_args": [
[
"nan@^2.0.5",
"/Users/trott/io.js/test/gc/node_modules/weak"
]
],
"_from": "nan@>=2.0.5 <3.0.0",
"_id": "nan@2.3.3",
"_inCache": true,
"_installable": true,
"_location": "/nan",
"_nodeVersion": "5.0.0",
"_npmOperationalInternal": {
"host": "packages-16-east.internal.npmjs.com",
"tmp": "tmp/nan-2.3.3.tgz_1462313618725_0.044748055282980204"
},
"_npmUser": {
"email": "bbyholm@abo.fi",
"name": "kkoopa"
},
"_npmVersion": "3.3.6",
"_phantomChildren": {},
"_requested": {
"name": "nan",
"raw": "nan@^2.0.5",
"rawSpec": "^2.0.5",
"scope": null,
"spec": ">=2.0.5 <3.0.0",
"type": "range"
},
"_requiredBy": [
"/weak"
],
"_resolved": "https://registry.npmjs.org/nan/-/nan-2.3.3.tgz",
"_shasum": "64dd83c9704a83648b6c72b401f6384bd94ef16f",
"_shrinkwrap": null,
"_spec": "nan@^2.0.5",
"_where": "/Users/trott/io.js/test/gc/node_modules/weak",
"bugs": {
"url": "https://github.com/nodejs/nan/issues"
},
"contributors": [
{
"email": "r@va.gg",
"name": "Rod Vagg",
"url": "https://github.com/rvagg"
},
{
"email": "bbyholm@abo.fi",
"name": "Benjamin Byholm",
"url": "https://github.com/kkoopa/"
},
{
"email": "trev.norris@gmail.com",
"name": "Trevor Norris",
"url": "https://github.com/trevnorris"
},
{
"email": "nathan@tootallnate.net",
"name": "Nathan Rajlich",
"url": "https://github.com/TooTallNate"
},
{
"email": "brett19@gmail.com",
"name": "Brett Lawson",
"url": "https://github.com/brett19"
},
{
"email": "info@bnoordhuis.nl",
"name": "Ben Noordhuis",
"url": "https://github.com/bnoordhuis"
},
{
"email": "david@artcom.de",
"name": "David Siegel",
"url": "https://github.com/agnat"
}
],
"dependencies": {},
"description": "Native Abstractions for Node.js: C++ header for Node 0.8 -> 6 compatibility",
"devDependencies": {
"bindings": "~1.2.1",
"commander": "^2.8.1",
"glob": "^5.0.14",
"node-gyp": "~3.0.1",
"tap": "~0.7.1",
"xtend": "~4.0.0"
},
"directories": {},
"dist": {
"shasum": "64dd83c9704a83648b6c72b401f6384bd94ef16f",
"tarball": "https://registry.npmjs.org/nan/-/nan-2.3.3.tgz"
},
"homepage": "https://github.com/nodejs/nan#readme",
"license": "MIT",
"main": "include_dirs.js",
"maintainers": [
{
"email": "rod@vagg.org",
"name": "rvagg"
},
{
"email": "bbyholm@abo.fi",
"name": "kkoopa"
}
],
"name": "nan",
"optionalDependencies": {},
"readme": "ERROR: No README data found!",
"repository": {
"type": "git",
"url": "git://github.com/nodejs/nan.git"
},
"scripts": {
"docs": "doc/.build.sh",
"rebuild-tests": "node-gyp rebuild --msvs_version=2013 --directory test",
"test": "tap --gc --stderr test/js/*-test.js"
},
"version": "2.3.3"
}

412
test/gc/node_modules/nan/tools/1to2.js

@ -0,0 +1,412 @@
#!/usr/bin/env node
/*********************************************************************
* NAN - Native Abstractions for Node.js
*
* Copyright (c) 2016 NAN contributors
*
* MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md>
********************************************************************/
var commander = require('commander'),
fs = require('fs'),
glob = require('glob'),
groups = [],
total = 0,
warning1 = '/* ERROR: Rewrite using Buffer */\n',
warning2 = '\\/\\* ERROR\\: Rewrite using Buffer \\*\\/\\n',
length,
i;
fs.readFile(__dirname + '/package.json', 'utf8', function (err, data) {
if (err) {
throw err;
}
commander
.version(JSON.parse(data).version)
.usage('[options] <file ...>')
.parse(process.argv);
if (!process.argv.slice(2).length) {
commander.outputHelp();
}
});
/* construct strings representing regular expressions
each expression contains a unique group allowing for identification of the match
the index of this key group, relative to the regular expression in question,
is indicated by the first array member */
/* simple substistutions, key group is the entire match, 0 */
groups.push([0, [
'_NAN_',
'NODE_SET_METHOD',
'NODE_SET_PROTOTYPE_METHOD',
'NanAsciiString',
'NanEscapeScope',
'NanReturnValue',
'NanUcs2String'].join('|')]);
/* substitutions of parameterless macros, key group is 1 */
groups.push([1, ['(', [
'NanEscapableScope',
'NanReturnNull',
'NanReturnUndefined',
'NanScope'].join('|'), ')\\(\\)'].join('')]);
/* replace TryCatch with NanTryCatch once, gobbling possible namespace, key group 2 */
groups.push([2, '(?:(?:v8\\:\\:)?|(Nan)?)(TryCatch)']);
/* NanNew("string") will likely not fail a ToLocalChecked(), key group 1 */
groups.push([1, ['(NanNew)', '(\\("[^\\"]*"[^\\)]*\\))(?!\\.ToLocalChecked\\(\\))'].join('')]);
/* Removed v8 APIs, warn that the code needs rewriting using node::Buffer, key group 2 */
groups.push([2, ['(', warning2, ')?', '^.*?(', [
'GetIndexedPropertiesExternalArrayDataLength',
'GetIndexedPropertiesExternalArrayData',
'GetIndexedPropertiesExternalArrayDataType',
'GetIndexedPropertiesPixelData',
'GetIndexedPropertiesPixelDataLength',
'HasIndexedPropertiesInExternalArrayData',
'HasIndexedPropertiesInPixelData',
'SetIndexedPropertiesToExternalArrayData',
'SetIndexedPropertiesToPixelData'].join('|'), ')'].join('')]);
/* No need for NanScope in V8-exposed methods, key group 2 */
groups.push([2, ['((', [
'NAN_METHOD',
'NAN_GETTER',
'NAN_SETTER',
'NAN_PROPERTY_GETTER',
'NAN_PROPERTY_SETTER',
'NAN_PROPERTY_ENUMERATOR',
'NAN_PROPERTY_DELETER',
'NAN_PROPERTY_QUERY',
'NAN_INDEX_GETTER',
'NAN_INDEX_SETTER',
'NAN_INDEX_ENUMERATOR',
'NAN_INDEX_DELETER',
'NAN_INDEX_QUERY'].join('|'), ')\\([^\\)]*\\)\\s*\\{)\\s*NanScope\\(\\)\\s*;'].join('')]);
/* v8::Value::ToXXXXXXX returns v8::MaybeLocal<T>, key group 3 */
groups.push([3, ['([\\s\\(\\)])([^\\s\\(\\)]+)->(', [
'Boolean',
'Number',
'String',
'Object',
'Integer',
'Uint32',
'Int32'].join('|'), ')\\('].join('')]);
/* v8::Value::XXXXXXXValue returns v8::Maybe<T>, key group 3 */
groups.push([3, ['([\\s\\(\\)])([^\\s\\(\\)]+)->((?:', [
'Boolean',
'Number',
'Integer',
'Uint32',
'Int32'].join('|'), ')Value)\\('].join('')]);
/* NAN_WEAK_CALLBACK macro was removed, write out callback definition, key group 1 */
groups.push([1, '(NAN_WEAK_CALLBACK)\\(([^\\s\\)]+)\\)']);
/* node::ObjectWrap and v8::Persistent have been replaced with Nan implementations, key group 1 */
groups.push([1, ['(', [
'NanDisposePersistent',
'NanObjectWrapHandle'].join('|'), ')\\s*\\(\\s*([^\\s\\)]+)'].join('')]);
/* Since NanPersistent there is no need for NanMakeWeakPersistent, key group 1 */
groups.push([1, '(NanMakeWeakPersistent)\\s*\\(\\s*([^\\s,]+)\\s*,\\s*']);
/* Many methods of v8::Object and others now return v8::MaybeLocal<T>, key group 3 */
groups.push([3, ['([\\s])([^\\s]+)->(', [
'GetEndColumn',
'GetFunction',
'GetLineNumber',
'NewInstance',
'GetPropertyNames',
'GetOwnPropertyNames',
'GetSourceLine',
'GetStartColumn',
'ObjectProtoToString',
'ToArrayIndex',
'ToDetailString',
'CallAsConstructor',
'CallAsFunction',
'CloneElementAt',
'Delete',
'ForceSet',
'Get',
'GetPropertyAttributes',
'GetRealNamedProperty',
'GetRealNamedPropertyInPrototypeChain',
'Has',
'HasOwnProperty',
'HasRealIndexedProperty',
'HasRealNamedCallbackProperty',
'HasRealNamedProperty',
'Set',
'SetAccessor',
'SetIndexedPropertyHandler',
'SetNamedPropertyHandler',
'SetPrototype'].join('|'), ')\\('].join('')]);
/* You should get an error if any of these fail anyways,
or handle the error better, it is indicated either way, key group 2 */
groups.push([2, ['NanNew(<(?:v8\\:\\:)?(', ['Date', 'String', 'RegExp'].join('|'), ')>)(\\([^\\)]*\\))(?!\\.ToLocalChecked\\(\\))'].join('')]);
/* v8::Value::Equals now returns a v8::Maybe, key group 3 */
groups.push([3, '([\\s\\(\\)])([^\\s\\(\\)]+)->(Equals)\\(([^\\s\\)]+)']);
/* NanPersistent makes this unnecessary, key group 1 */
groups.push([1, '(NanAssignPersistent)(?:<v8\\:\\:[^>]+>)?\\(([^,]+),\\s*']);
/* args has been renamed to info, key group 2 */
groups.push([2, '(\\W)(args)(\\W)'])
/* node::ObjectWrap was replaced with NanObjectWrap, key group 2 */
groups.push([2, '(\\W)(?:node\\:\\:)?(ObjectWrap)(\\W)']);
/* v8::Persistent was replaced with NanPersistent, key group 2 */
groups.push([2, '(\\W)(?:v8\\:\\:)?(Persistent)(\\W)']);
/* counts the number of capturing groups in a well-formed regular expression,
ignoring non-capturing groups and escaped parentheses */
function groupcount(s) {
var positive = s.match(/\((?!\?)/g),
negative = s.match(/\\\(/g);
return (positive ? positive.length : 0) - (negative ? negative.length : 0);
}
/* compute the absolute position of each key group in the joined master RegExp */
for (i = 1, length = groups.length; i < length; i++) {
total += groupcount(groups[i - 1][1]);
groups[i][0] += total;
}
/* create the master RegExp, whis is the union of all the groups' expressions */
master = new RegExp(groups.map(function (a) { return a[1]; }).join('|'), 'gm');
/* replacement function for String.replace, receives 21 arguments */
function replace() {
/* simple expressions */
switch (arguments[groups[0][0]]) {
case '_NAN_':
return 'NAN_';
case 'NODE_SET_METHOD':
return 'NanSetMethod';
case 'NODE_SET_PROTOTYPE_METHOD':
return 'NanSetPrototypeMethod';
case 'NanAsciiString':
return 'NanUtf8String';
case 'NanEscapeScope':
return 'scope.Escape';
case 'NanReturnNull':
return 'info.GetReturnValue().SetNull';
case 'NanReturnValue':
return 'info.GetReturnValue().Set';
case 'NanUcs2String':
return 'v8::String::Value';
default:
}
/* macros without arguments */
switch (arguments[groups[1][0]]) {
case 'NanEscapableScope':
return 'NanEscapableScope scope'
case 'NanReturnUndefined':
return 'return';
case 'NanScope':
return 'NanScope scope';
default:
}
/* TryCatch, emulate negative backref */
if (arguments[groups[2][0]] === 'TryCatch') {
return arguments[groups[2][0] - 1] ? arguments[0] : 'NanTryCatch';
}
/* NanNew("foo") --> NanNew("foo").ToLocalChecked() */
if (arguments[groups[3][0]] === 'NanNew') {
return [arguments[0], '.ToLocalChecked()'].join('');
}
/* insert warning for removed functions as comment on new line above */
switch (arguments[groups[4][0]]) {
case 'GetIndexedPropertiesExternalArrayData':
case 'GetIndexedPropertiesExternalArrayDataLength':
case 'GetIndexedPropertiesExternalArrayDataType':
case 'GetIndexedPropertiesPixelData':
case 'GetIndexedPropertiesPixelDataLength':
case 'HasIndexedPropertiesInExternalArrayData':
case 'HasIndexedPropertiesInPixelData':
case 'SetIndexedPropertiesToExternalArrayData':
case 'SetIndexedPropertiesToPixelData':
return arguments[groups[4][0] - 1] ? arguments[0] : [warning1, arguments[0]].join('');
default:
}
/* remove unnecessary NanScope() */
switch (arguments[groups[5][0]]) {
case 'NAN_GETTER':
case 'NAN_METHOD':
case 'NAN_SETTER':
case 'NAN_INDEX_DELETER':
case 'NAN_INDEX_ENUMERATOR':
case 'NAN_INDEX_GETTER':
case 'NAN_INDEX_QUERY':
case 'NAN_INDEX_SETTER':
case 'NAN_PROPERTY_DELETER':
case 'NAN_PROPERTY_ENUMERATOR':
case 'NAN_PROPERTY_GETTER':
case 'NAN_PROPERTY_QUERY':
case 'NAN_PROPERTY_SETTER':
return arguments[groups[5][0] - 1];
default:
}
/* Value converstion */
switch (arguments[groups[6][0]]) {
case 'Boolean':
case 'Int32':
case 'Integer':
case 'Number':
case 'Object':
case 'String':
case 'Uint32':
return [arguments[groups[6][0] - 2], 'NanTo<v8::', arguments[groups[6][0]], '>(', arguments[groups[6][0] - 1]].join('');
default:
}
/* other value conversion */
switch (arguments[groups[7][0]]) {
case 'BooleanValue':
return [arguments[groups[7][0] - 2], 'NanTo<bool>(', arguments[groups[7][0] - 1]].join('');
case 'Int32Value':
return [arguments[groups[7][0] - 2], 'NanTo<int32_t>(', arguments[groups[7][0] - 1]].join('');
case 'IntegerValue':
return [arguments[groups[7][0] - 2], 'NanTo<int64_t>(', arguments[groups[7][0] - 1]].join('');
case 'Uint32Value':
return [arguments[groups[7][0] - 2], 'NanTo<uint32_t>(', arguments[groups[7][0] - 1]].join('');
default:
}
/* NAN_WEAK_CALLBACK */
if (arguments[groups[8][0]] === 'NAN_WEAK_CALLBACK') {
return ['template<typename T>\nvoid ',
arguments[groups[8][0] + 1], '(const NanWeakCallbackInfo<T> &data)'].join('');
}
/* use methods on NAN classes instead */
switch (arguments[groups[9][0]]) {
case 'NanDisposePersistent':
return [arguments[groups[9][0] + 1], '.Reset('].join('');
case 'NanObjectWrapHandle':
return [arguments[groups[9][0] + 1], '->handle('].join('');
default:
}
/* use method on NanPersistent instead */
if (arguments[groups[10][0]] === 'NanMakeWeakPersistent') {
return arguments[groups[10][0] + 1] + '.SetWeak(';
}
/* These return Maybes, the upper ones take no arguments */
switch (arguments[groups[11][0]]) {
case 'GetEndColumn':
case 'GetFunction':
case 'GetLineNumber':
case 'GetOwnPropertyNames':
case 'GetPropertyNames':
case 'GetSourceLine':
case 'GetStartColumn':
case 'NewInstance':
case 'ObjectProtoToString':
case 'ToArrayIndex':
case 'ToDetailString':
return [arguments[groups[11][0] - 2], 'Nan', arguments[groups[11][0]], '(', arguments[groups[11][0] - 1]].join('');
case 'CallAsConstructor':
case 'CallAsFunction':
case 'CloneElementAt':
case 'Delete':
case 'ForceSet':
case 'Get':
case 'GetPropertyAttributes':
case 'GetRealNamedProperty':
case 'GetRealNamedPropertyInPrototypeChain':
case 'Has':
case 'HasOwnProperty':
case 'HasRealIndexedProperty':
case 'HasRealNamedCallbackProperty':
case 'HasRealNamedProperty':
case 'Set':
case 'SetAccessor':
case 'SetIndexedPropertyHandler':
case 'SetNamedPropertyHandler':
case 'SetPrototype':
return [arguments[groups[11][0] - 2], 'Nan', arguments[groups[11][0]], '(', arguments[groups[11][0] - 1], ', '].join('');
default:
}
/* Automatic ToLocalChecked(), take it or leave it */
switch (arguments[groups[12][0]]) {
case 'Date':
case 'String':
case 'RegExp':
return ['NanNew', arguments[groups[12][0] - 1], arguments[groups[12][0] + 1], '.ToLocalChecked()'].join('');
default:
}
/* NanEquals is now required for uniformity */
if (arguments[groups[13][0]] === 'Equals') {
return [arguments[groups[13][0] - 1], 'NanEquals(', arguments[groups[13][0] - 1], ', ', arguments[groups[13][0] + 1]].join('');
}
/* use method on replacement class instead */
if (arguments[groups[14][0]] === 'NanAssignPersistent') {
return [arguments[groups[14][0] + 1], '.Reset('].join('');
}
/* args --> info */
if (arguments[groups[15][0]] === 'args') {
return [arguments[groups[15][0] - 1], 'info', arguments[groups[15][0] + 1]].join('');
}
/* ObjectWrap --> NanObjectWrap */
if (arguments[groups[16][0]] === 'ObjectWrap') {
return [arguments[groups[16][0] - 1], 'NanObjectWrap', arguments[groups[16][0] + 1]].join('');
}
/* Persistent --> NanPersistent */
if (arguments[groups[17][0]] === 'Persistent') {
return [arguments[groups[17][0] - 1], 'NanPersistent', arguments[groups[17][0] + 1]].join('');
}
/* This should not happen. A switch is probably missing a case if it does. */
throw 'Unhandled match: ' + arguments[0];
}
/* reads a file, runs replacement and writes it back */
function processFile(file) {
fs.readFile(file, {encoding: 'utf8'}, function (err, data) {
if (err) {
throw err;
}
/* run replacement twice, might need more runs */
fs.writeFile(file, data.replace(master, replace).replace(master, replace), function (err) {
if (err) {
throw err;
}
});
});
}
/* process file names from command line and process the identified files */
for (i = 2, length = process.argv.length; i < length; i++) {
glob(process.argv[i], function (err, matches) {
if (err) {
throw err;
}
matches.forEach(processFile);
});
}

14
test/gc/node_modules/nan/tools/README.md

@ -0,0 +1,14 @@
1to2 naively converts source code files from NAN 1 to NAN 2. There will be erroneous conversions,
false positives and missed opportunities. The input files are rewritten in place. Make sure that
you have backups. You will have to manually review the changes afterwards and do some touchups.
```sh
$ tools/1to2.js
Usage: 1to2 [options] <file ...>
Options:
-h, --help output usage information
-V, --version output the version number
```

19
test/gc/node_modules/nan/tools/package.json

@ -0,0 +1,19 @@
{
"name": "1to2",
"version": "1.0.0",
"description": "NAN 1 -> 2 Migration Script",
"main": "1to2.js",
"repository": {
"type": "git",
"url": "git://github.com/nodejs/nan.git"
},
"contributors": [
"Benjamin Byholm <bbyholm@abo.fi> (https://github.com/kkoopa/)",
"Mathias Küsel (https://github.com/mathiask88/)"
],
"dependencies": {
"glob": "~5.0.10",
"commander": "~2.8.1"
},
"license": "MIT"
}

1
test/gc/node_modules/weak/.gitignore

@ -1 +0,0 @@
/build

2
test/gc/node_modules/weak/LICENSE

@ -10,4 +10,4 @@ MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

91
test/gc/node_modules/weak/README.md

@ -1,7 +1,8 @@
node-weak
=========
### Make weak references to JavaScript Objects.
[![Build Status](https://secure.travis-ci.org/TooTallNate/node-weak.png)](http://travis-ci.org/TooTallNate/node-weak)
[![Build Status](https://travis-ci.org/TooTallNate/node-weak.svg?branch=master)](https://travis-ci.org/TooTallNate/node-weak)
[![Build Status](https://ci.appveyor.com/api/projects/status/09lf09d1a5hm24bq?svg=true)](https://ci.appveyor.com/project/TooTallNate/node-weak)
On certain rarer occasions, you run into the need to be notified when a JavaScript
object is going to be garbage collected. This feature is exposed to V8's C++ API,
@ -44,18 +45,10 @@ var obj = {
, foo: 'bar'
}
// The function to call before Garbage Collection.
// Note that by the time this is called, 'obj' has been set to `null`.
function cleanup (o) {
delete o.a
delete o.foo
}
// Here's where we set up the weak reference
var ref = weak(obj, function () {
// `this` inside the callback is the 'obj'. DO NOT store any new references
// to the object, and DO NOT use the object in any async functions.
cleanup(this)
// `this` inside the callback is the EventEmitter.
console.log('"obj" has been garbage collected!')
})
// While `obj` is alive, `ref` proxies everything to it, so:
@ -74,41 +67,97 @@ typeof ref.foo === 'undefined'
```
Weak Callback Function "Best Practices"
---------------------------------------
It's important to be careful when using the "callbacks" feature of `node-weak`,
otherwise you can end up in a situation where the watched object will never
be garbage collected.
You _should **not**_ define the callback function in the same scope as the
object that is being watched. It's often best to define the callback function
at the highest scope possible (top-level being the best). Named functions
work really well for this:
``` js
var http = require('http')
, weak = require('weak')
http.createServer(function (req, res) {
weak(req, gcReq)
weak(res, gcRes)
res.end('Hello World\n')
}).listen(3000)
function gcReq () {
console.log('GC\'d `req` object')
}
function gcRes () {
console.log('GC\'d `res` object')
}
```
API
---
### weakref weak(Object obj [, Function callback])
### Weakref weak(Object obj [, Function callback])
The main exports is the function that creates the weak reference.
The first argument is the Object that should be monitored.
The Object can be a regular Object, an Array, a Function, a RegExp, or any of
the primitive types or constructor function created with `new`.
Optionally, you can set a callback function to be invoked
before the object is garbage collected.
### Object weak.get(weakref ref)
### Object weak.get(Weakref ref)
`get()` returns the actual reference to the Object that this weak reference was
created with. If this is called with a dead reference, `undefined` is returned.
### Boolean weak.isDead(weakref ref)
### Boolean weak.isDead(Weakref ref)
Checks to see if `ref` is a dead reference. Returns `true` if the original Object
has already been GC'd, `false` otherwise.
### null weak.addCallback(weakref ref, Function callback)
### Boolean weak.isNearDeath(Weakref ref)
Checks to see if `ref` is "near death". This will be `true` exactly during the
weak reference callback function, and `false` any other time.
### Boolean weak.isWeakRef(Object obj)
Checks to see if `obj` is "weak reference" instance. Returns `true` if the
passed in object is a "weak reference", `false` otherwise.
### EventEmitter weak.addCallback(Weakref ref, Function callback)
Adds `callback` to the Array of callback functions that will be invoked before the
Objects gets garbage collected. The callbacks get executed in the order that they
Object gets garbage collected. The callbacks get executed in the order that they
are added.
### Array weak.callbacks(weakref ref)
### EventEmitter weak.removeCallback(Weakref ref, Function callback)
Removes `callback` from the Array of callback functions that will be invoked before
the Object gets garbage collected.
### EventEmitter weak.removeCallbacks(Weakref ref)
Empties the Array of callback functions that will be invoked before the Object gets
garbage collected.
### Array weak.callbacks(Weakref ref)
Returns the internal `Array` that `ref` iterates through to invoke the GC
callbacks. The array can be `push()`ed or `unshift()`ed onto, to have more control
over the execution order of the callbacks. This is similar in concept to node's
`EventEmitter#listeners()` function.
Returns an Array that `ref` iterates through to invoke the GC callbacks. This
utilizes node's `EventEmitter#listeners()` function and therefore returns a copy
in node 0.10 and newer.

49
test/gc/node_modules/weak/appveyor.yml

@ -0,0 +1,49 @@
# http://www.appveyor.com/docs/appveyor-yml
# Test against these versions of Node.js.
environment:
# Visual Studio Version
MSVS_VERSION: 2013
# Test against these versions of Node.js and io.js
matrix:
# node.js
- nodejs_version: "0.8"
- nodejs_version: "0.10"
- nodejs_version: "0.12"
# io.js
- nodejs_version: "2"
- nodejs_version: "3"
- nodejs_version: "4"
- nodejs_version: "5"
platform:
- x86
- x64
# Install scripts. (runs after repo cloning)
install:
# Get the latest stable version of Node 0.STABLE.latest
- ps: if($env:nodejs_version -eq "0.8") {Install-Product node $env:nodejs_version}
- ps: if($env:nodejs_version -ne "0.8") {Update-NodeJsInstallation (Get-NodeJsLatestBuild $env:nodejs_version)}
# Node 0.8 comes with a too obsolete npm
- IF %nodejs_version% == 0.8 (npm install -g npm@1.4.28)
# Install latest NPM only for node.js versions until built in node-gyp adds io.js support
# Update is required for node.js 0.8 because built in npm(node-gyp) does not know VS2013
- IF %nodejs_version% LSS 1 (npm install -g npm@2)
- IF %nodejs_version% LSS 1 set PATH=%APPDATA%\npm;%PATH%
# Typical npm stuff.
- npm install --msvs_version=%MSVS_VERSION%
# Post-install test scripts.
test_script:
# Output useful info for debugging.
- node --version
- npm --version
# run tests
- npm test
# Don't actually build.
build: off
# Set build version format here instead of in the admin panel.
version: "{build}"

13
test/gc/node_modules/weak/binding.gyp

@ -1,8 +1,9 @@
{
'targets': [
{
'target_name': 'weakref',
'sources': [ 'src/weakref.cc' ]
}
]
'targets': [{
'target_name': 'weakref',
'sources': [ 'src/weakref.cc' ],
'include_dirs': [
'<!(node -e "require(\'nan\')")'
]
}]
}

342
test/gc/node_modules/weak/build/Makefile

@ -0,0 +1,342 @@
# We borrow heavily from the kernel build setup, though we are simpler since
# we don't have Kconfig tweaking settings on us.
# The implicit make rules have it looking for RCS files, among other things.
# We instead explicitly write all the rules we care about.
# It's even quicker (saves ~200ms) to pass -r on the command line.
MAKEFLAGS=-r
# The source directory tree.
srcdir := ..
abs_srcdir := $(abspath $(srcdir))
# The name of the builddir.
builddir_name ?= .
# The V=1 flag on command line makes us verbosely print command lines.
ifdef V
quiet=
else
quiet=quiet_
endif
# Specify BUILDTYPE=Release on the command line for a release build.
BUILDTYPE ?= Release
# Directory all our build output goes into.
# Note that this must be two directories beneath src/ for unit tests to pass,
# as they reach into the src/ directory for data with relative paths.
builddir ?= $(builddir_name)/$(BUILDTYPE)
abs_builddir := $(abspath $(builddir))
depsdir := $(builddir)/.deps
# Object output directory.
obj := $(builddir)/obj
abs_obj := $(abspath $(obj))
# We build up a list of every single one of the targets so we can slurp in the
# generated dependency rule Makefiles in one pass.
all_deps :=
CC.target ?= $(CC)
CFLAGS.target ?= $(CPPFLAGS) $(CFLAGS)
CXX.target ?= $(CXX)
CXXFLAGS.target ?= $(CPPFLAGS) $(CXXFLAGS)
LINK.target ?= $(LINK)
LDFLAGS.target ?= $(LDFLAGS)
AR.target ?= $(AR)
# C++ apps need to be linked with g++.
LINK ?= $(CXX.target)
# TODO(evan): move all cross-compilation logic to gyp-time so we don't need
# to replicate this environment fallback in make as well.
CC.host ?= gcc
CFLAGS.host ?= $(CPPFLAGS_host) $(CFLAGS_host)
CXX.host ?= g++
CXXFLAGS.host ?= $(CPPFLAGS_host) $(CXXFLAGS_host)
LINK.host ?= $(CXX.host)
LDFLAGS.host ?=
AR.host ?= ar
# Define a dir function that can handle spaces.
# http://www.gnu.org/software/make/manual/make.html#Syntax-of-Functions
# "leading spaces cannot appear in the text of the first argument as written.
# These characters can be put into the argument value by variable substitution."
empty :=
space := $(empty) $(empty)
# http://stackoverflow.com/questions/1189781/using-make-dir-or-notdir-on-a-path-with-spaces
replace_spaces = $(subst $(space),?,$1)
unreplace_spaces = $(subst ?,$(space),$1)
dirx = $(call unreplace_spaces,$(dir $(call replace_spaces,$1)))
# Flags to make gcc output dependency info. Note that you need to be
# careful here to use the flags that ccache and distcc can understand.
# We write to a dep file on the side first and then rename at the end
# so we can't end up with a broken dep file.
depfile = $(depsdir)/$(call replace_spaces,$@).d
DEPFLAGS = -MMD -MF $(depfile).raw
# We have to fixup the deps output in a few ways.
# (1) the file output should mention the proper .o file.
# ccache or distcc lose the path to the target, so we convert a rule of
# the form:
# foobar.o: DEP1 DEP2
# into
# path/to/foobar.o: DEP1 DEP2
# (2) we want missing files not to cause us to fail to build.
# We want to rewrite
# foobar.o: DEP1 DEP2 \
# DEP3
# to
# DEP1:
# DEP2:
# DEP3:
# so if the files are missing, they're just considered phony rules.
# We have to do some pretty insane escaping to get those backslashes
# and dollar signs past make, the shell, and sed at the same time.
# Doesn't work with spaces, but that's fine: .d files have spaces in
# their names replaced with other characters.
define fixup_dep
# The depfile may not exist if the input file didn't have any #includes.
touch $(depfile).raw
# Fixup path as in (1).
sed -e "s|^$(notdir $@)|$@|" $(depfile).raw >> $(depfile)
# Add extra rules as in (2).
# We remove slashes and replace spaces with new lines;
# remove blank lines;
# delete the first line and append a colon to the remaining lines.
sed -e 's|\\||' -e 'y| |\n|' $(depfile).raw |\
grep -v '^$$' |\
sed -e 1d -e 's|$$|:|' \
>> $(depfile)
rm $(depfile).raw
endef
# Command definitions:
# - cmd_foo is the actual command to run;
# - quiet_cmd_foo is the brief-output summary of the command.
quiet_cmd_cc = CC($(TOOLSET)) $@
cmd_cc = $(CC.$(TOOLSET)) $(GYP_CFLAGS) $(DEPFLAGS) $(CFLAGS.$(TOOLSET)) -c -o $@ $<
quiet_cmd_cxx = CXX($(TOOLSET)) $@
cmd_cxx = $(CXX.$(TOOLSET)) $(GYP_CXXFLAGS) $(DEPFLAGS) $(CXXFLAGS.$(TOOLSET)) -c -o $@ $<
quiet_cmd_objc = CXX($(TOOLSET)) $@
cmd_objc = $(CC.$(TOOLSET)) $(GYP_OBJCFLAGS) $(DEPFLAGS) -c -o $@ $<
quiet_cmd_objcxx = CXX($(TOOLSET)) $@
cmd_objcxx = $(CXX.$(TOOLSET)) $(GYP_OBJCXXFLAGS) $(DEPFLAGS) -c -o $@ $<
# Commands for precompiled header files.
quiet_cmd_pch_c = CXX($(TOOLSET)) $@
cmd_pch_c = $(CC.$(TOOLSET)) $(GYP_PCH_CFLAGS) $(DEPFLAGS) $(CXXFLAGS.$(TOOLSET)) -c -o $@ $<
quiet_cmd_pch_cc = CXX($(TOOLSET)) $@
cmd_pch_cc = $(CC.$(TOOLSET)) $(GYP_PCH_CXXFLAGS) $(DEPFLAGS) $(CXXFLAGS.$(TOOLSET)) -c -o $@ $<
quiet_cmd_pch_m = CXX($(TOOLSET)) $@
cmd_pch_m = $(CC.$(TOOLSET)) $(GYP_PCH_OBJCFLAGS) $(DEPFLAGS) -c -o $@ $<
quiet_cmd_pch_mm = CXX($(TOOLSET)) $@
cmd_pch_mm = $(CC.$(TOOLSET)) $(GYP_PCH_OBJCXXFLAGS) $(DEPFLAGS) -c -o $@ $<
# gyp-mac-tool is written next to the root Makefile by gyp.
# Use $(4) for the command, since $(2) and $(3) are used as flag by do_cmd
# already.
quiet_cmd_mac_tool = MACTOOL $(4) $<
cmd_mac_tool = ./gyp-mac-tool $(4) $< "$@"
quiet_cmd_mac_package_framework = PACKAGE FRAMEWORK $@
cmd_mac_package_framework = ./gyp-mac-tool package-framework "$@" $(4)
quiet_cmd_infoplist = INFOPLIST $@
cmd_infoplist = $(CC.$(TOOLSET)) -E -P -Wno-trigraphs -x c $(INFOPLIST_DEFINES) "$<" -o "$@"
quiet_cmd_touch = TOUCH $@
cmd_touch = touch $@
quiet_cmd_copy = COPY $@
# send stderr to /dev/null to ignore messages when linking directories.
cmd_copy = rm -rf "$@" && cp -af "$<" "$@"
quiet_cmd_alink = LIBTOOL-STATIC $@
cmd_alink = rm -f $@ && ./gyp-mac-tool filter-libtool libtool $(GYP_LIBTOOLFLAGS) -static -o $@ $(filter %.o,$^)
quiet_cmd_link = LINK($(TOOLSET)) $@
cmd_link = $(LINK.$(TOOLSET)) $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o "$@" $(LD_INPUTS) $(LIBS)
quiet_cmd_solink = SOLINK($(TOOLSET)) $@
cmd_solink = $(LINK.$(TOOLSET)) -shared $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o "$@" $(LD_INPUTS) $(LIBS)
quiet_cmd_solink_module = SOLINK_MODULE($(TOOLSET)) $@
cmd_solink_module = $(LINK.$(TOOLSET)) -bundle $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o $@ $(filter-out FORCE_DO_CMD, $^) $(LIBS)
# Define an escape_quotes function to escape single quotes.
# This allows us to handle quotes properly as long as we always use
# use single quotes and escape_quotes.
escape_quotes = $(subst ','\'',$(1))
# This comment is here just to include a ' to unconfuse syntax highlighting.
# Define an escape_vars function to escape '$' variable syntax.
# This allows us to read/write command lines with shell variables (e.g.
# $LD_LIBRARY_PATH), without triggering make substitution.
escape_vars = $(subst $$,$$$$,$(1))
# Helper that expands to a shell command to echo a string exactly as it is in
# make. This uses printf instead of echo because printf's behaviour with respect
# to escape sequences is more portable than echo's across different shells
# (e.g., dash, bash).
exact_echo = printf '%s\n' '$(call escape_quotes,$(1))'
# Helper to compare the command we're about to run against the command
# we logged the last time we ran the command. Produces an empty
# string (false) when the commands match.
# Tricky point: Make has no string-equality test function.
# The kernel uses the following, but it seems like it would have false
# positives, where one string reordered its arguments.
# arg_check = $(strip $(filter-out $(cmd_$(1)), $(cmd_$@)) \
# $(filter-out $(cmd_$@), $(cmd_$(1))))
# We instead substitute each for the empty string into the other, and
# say they're equal if both substitutions produce the empty string.
# .d files contain ? instead of spaces, take that into account.
command_changed = $(or $(subst $(cmd_$(1)),,$(cmd_$(call replace_spaces,$@))),\
$(subst $(cmd_$(call replace_spaces,$@)),,$(cmd_$(1))))
# Helper that is non-empty when a prerequisite changes.
# Normally make does this implicitly, but we force rules to always run
# so we can check their command lines.
# $? -- new prerequisites
# $| -- order-only dependencies
prereq_changed = $(filter-out FORCE_DO_CMD,$(filter-out $|,$?))
# Helper that executes all postbuilds until one fails.
define do_postbuilds
@E=0;\
for p in $(POSTBUILDS); do\
eval $$p;\
E=$$?;\
if [ $$E -ne 0 ]; then\
break;\
fi;\
done;\
if [ $$E -ne 0 ]; then\
rm -rf "$@";\
exit $$E;\
fi
endef
# do_cmd: run a command via the above cmd_foo names, if necessary.
# Should always run for a given target to handle command-line changes.
# Second argument, if non-zero, makes it do asm/C/C++ dependency munging.
# Third argument, if non-zero, makes it do POSTBUILDS processing.
# Note: We intentionally do NOT call dirx for depfile, since it contains ? for
# spaces already and dirx strips the ? characters.
define do_cmd
$(if $(or $(command_changed),$(prereq_changed)),
@$(call exact_echo, $($(quiet)cmd_$(1)))
@mkdir -p "$(call dirx,$@)" "$(dir $(depfile))"
$(if $(findstring flock,$(word 2,$(cmd_$1))),
@$(cmd_$(1))
@echo " $(quiet_cmd_$(1)): Finished",
@$(cmd_$(1))
)
@$(call exact_echo,$(call escape_vars,cmd_$(call replace_spaces,$@) := $(cmd_$(1)))) > $(depfile)
@$(if $(2),$(fixup_dep))
$(if $(and $(3), $(POSTBUILDS)),
$(call do_postbuilds)
)
)
endef
# Declare the "all" target first so it is the default,
# even though we don't have the deps yet.
.PHONY: all
all:
# make looks for ways to re-generate included makefiles, but in our case, we
# don't have a direct way. Explicitly telling make that it has nothing to do
# for them makes it go faster.
%.d: ;
# Use FORCE_DO_CMD to force a target to run. Should be coupled with
# do_cmd.
.PHONY: FORCE_DO_CMD
FORCE_DO_CMD:
TOOLSET := target
# Suffix rules, putting all outputs into $(obj).
$(obj).$(TOOLSET)/%.o: $(srcdir)/%.c FORCE_DO_CMD
@$(call do_cmd,cc,1)
$(obj).$(TOOLSET)/%.o: $(srcdir)/%.cc FORCE_DO_CMD
@$(call do_cmd,cxx,1)
$(obj).$(TOOLSET)/%.o: $(srcdir)/%.cpp FORCE_DO_CMD
@$(call do_cmd,cxx,1)
$(obj).$(TOOLSET)/%.o: $(srcdir)/%.cxx FORCE_DO_CMD
@$(call do_cmd,cxx,1)
$(obj).$(TOOLSET)/%.o: $(srcdir)/%.m FORCE_DO_CMD
@$(call do_cmd,objc,1)
$(obj).$(TOOLSET)/%.o: $(srcdir)/%.mm FORCE_DO_CMD
@$(call do_cmd,objcxx,1)
$(obj).$(TOOLSET)/%.o: $(srcdir)/%.S FORCE_DO_CMD
@$(call do_cmd,cc,1)
$(obj).$(TOOLSET)/%.o: $(srcdir)/%.s FORCE_DO_CMD
@$(call do_cmd,cc,1)
# Try building from generated source, too.
$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.c FORCE_DO_CMD
@$(call do_cmd,cc,1)
$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.cc FORCE_DO_CMD
@$(call do_cmd,cxx,1)
$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.cpp FORCE_DO_CMD
@$(call do_cmd,cxx,1)
$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.cxx FORCE_DO_CMD
@$(call do_cmd,cxx,1)
$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.m FORCE_DO_CMD
@$(call do_cmd,objc,1)
$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.mm FORCE_DO_CMD
@$(call do_cmd,objcxx,1)
$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.S FORCE_DO_CMD
@$(call do_cmd,cc,1)
$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.s FORCE_DO_CMD
@$(call do_cmd,cc,1)
$(obj).$(TOOLSET)/%.o: $(obj)/%.c FORCE_DO_CMD
@$(call do_cmd,cc,1)
$(obj).$(TOOLSET)/%.o: $(obj)/%.cc FORCE_DO_CMD
@$(call do_cmd,cxx,1)
$(obj).$(TOOLSET)/%.o: $(obj)/%.cpp FORCE_DO_CMD
@$(call do_cmd,cxx,1)
$(obj).$(TOOLSET)/%.o: $(obj)/%.cxx FORCE_DO_CMD
@$(call do_cmd,cxx,1)
$(obj).$(TOOLSET)/%.o: $(obj)/%.m FORCE_DO_CMD
@$(call do_cmd,objc,1)
$(obj).$(TOOLSET)/%.o: $(obj)/%.mm FORCE_DO_CMD
@$(call do_cmd,objcxx,1)
$(obj).$(TOOLSET)/%.o: $(obj)/%.S FORCE_DO_CMD
@$(call do_cmd,cc,1)
$(obj).$(TOOLSET)/%.o: $(obj)/%.s FORCE_DO_CMD
@$(call do_cmd,cc,1)
ifeq ($(strip $(foreach prefix,$(NO_LOAD),\
$(findstring $(join ^,$(prefix)),\
$(join ^,weakref.target.mk)))),)
include weakref.target.mk
endif
quiet_cmd_regen_makefile = ACTION Regenerating $@
cmd_regen_makefile = cd $(srcdir); /Users/trott/io.js/deps/npm/node_modules/node-gyp/gyp/gyp_main.py -fmake --ignore-environment "--toplevel-dir=." -I/Users/trott/io.js/test/gc/node_modules/weak/build/config.gypi -I/Users/trott/io.js/deps/npm/node_modules/node-gyp/addon.gypi -I/Users/trott/io.js/common.gypi "--depth=." "-Goutput_dir=." "--generator-output=build" "-Dlibrary=shared_library" "-Dvisibility=default" "-Dnode_root_dir=/Users/trott/io.js" "-Dnode_gyp_dir=/Users/trott/io.js/deps/npm/node_modules/node-gyp" "-Dnode_lib_file=node.lib" "-Dmodule_root_dir=/Users/trott/io.js/test/gc/node_modules/weak" binding.gyp
Makefile: $(srcdir)/../../../../deps/npm/node_modules/node-gyp/addon.gypi $(srcdir)/build/config.gypi $(srcdir)/binding.gyp $(srcdir)/../../../../common.gypi
$(call do_cmd,regen_makefile)
# "all" is a concatenation of the "all" targets from all the included
# sub-makefiles. This is just here to clarify.
all:
# Add in dependency-tracking rules. $(all_deps) is the list of every single
# target in our tree. Only consider the ones with .d (dependency) info:
d_files := $(wildcard $(foreach f,$(all_deps),$(depsdir)/$(f).d))
ifneq ($(d_files),)
include $(d_files)
endif

6
test/gc/node_modules/weak/build/binding.Makefile

@ -0,0 +1,6 @@
# This file is generated by gyp; do not edit.
export builddir_name ?= ./build/.
.PHONY: all
all:
$(MAKE) weakref

56
test/gc/node_modules/weak/build/config.gypi

@ -0,0 +1,56 @@
# Do not edit. File was generated by node-gyp's "configure" step
{
"target_defaults": {
"cflags": [],
"default_configuration": "Release",
"defines": [],
"include_dirs": [],
"libraries": []
},
"variables": {
"asan": 0,
"host_arch": "x64",
"icu_data_file": "icudt57l.dat",
"icu_data_in": "../../deps/icu-small/source/data/in/icudt57l.dat",
"icu_endianness": "l",
"icu_gyp_path": "tools/icu/icu-generic.gyp",
"icu_locales": "en,root",
"icu_path": "deps/icu-small",
"icu_small": "true",
"icu_ver_major": "57",
"llvm_version": 0,
"node_byteorder": "little",
"node_enable_v8_vtunejit": "false",
"node_install_npm": "true",
"node_no_browser_globals": "false",
"node_prefix": "/usr/local",
"node_release_urlbase": "",
"node_shared_cares": "false",
"node_shared_http_parser": "false",
"node_shared_libuv": "false",
"node_shared_openssl": "false",
"node_shared_zlib": "false",
"node_tag": "",
"node_use_dtrace": "true",
"node_use_etw": "false",
"node_use_lttng": "false",
"node_use_openssl": "true",
"node_use_perfctr": "false",
"openssl_fips": "",
"openssl_no_asm": 0,
"target_arch": "x64",
"uv_parent_path": "/deps/uv/",
"uv_use_dtrace": "true",
"v8_enable_gdbjit": 0,
"v8_enable_i18n_support": 1,
"v8_no_strict_aliasing": 1,
"v8_optimized_debug": 0,
"v8_random_seed": 0,
"v8_use_snapshot": "true",
"want_separate_host_toolset": 0,
"xcode_version": "7.0",
"nodedir": "/Users/trott/io.js",
"copy_dev_lib": "false",
"standalone_static_library": 1
}
}

611
test/gc/node_modules/weak/build/gyp-mac-tool

@ -0,0 +1,611 @@
#!/usr/bin/env python
# Generated by gyp. Do not edit.
# Copyright (c) 2012 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Utility functions to perform Xcode-style build steps.
These functions are executed via gyp-mac-tool when using the Makefile generator.
"""
import fcntl
import fnmatch
import glob
import json
import os
import plistlib
import re
import shutil
import string
import subprocess
import sys
import tempfile
def main(args):
executor = MacTool()
exit_code = executor.Dispatch(args)
if exit_code is not None:
sys.exit(exit_code)
class MacTool(object):
"""This class performs all the Mac tooling steps. The methods can either be
executed directly, or dispatched from an argument list."""
def Dispatch(self, args):
"""Dispatches a string command to a method."""
if len(args) < 1:
raise Exception("Not enough arguments")
method = "Exec%s" % self._CommandifyName(args[0])
return getattr(self, method)(*args[1:])
def _CommandifyName(self, name_string):
"""Transforms a tool name like copy-info-plist to CopyInfoPlist"""
return name_string.title().replace('-', '')
def ExecCopyBundleResource(self, source, dest, convert_to_binary):
"""Copies a resource file to the bundle/Resources directory, performing any
necessary compilation on each resource."""
extension = os.path.splitext(source)[1].lower()
if os.path.isdir(source):
# Copy tree.
# TODO(thakis): This copies file attributes like mtime, while the
# single-file branch below doesn't. This should probably be changed to
# be consistent with the single-file branch.
if os.path.exists(dest):
shutil.rmtree(dest)
shutil.copytree(source, dest)
elif extension == '.xib':
return self._CopyXIBFile(source, dest)
elif extension == '.storyboard':
return self._CopyXIBFile(source, dest)
elif extension == '.strings':
self._CopyStringsFile(source, dest, convert_to_binary)
else:
shutil.copy(source, dest)
def _CopyXIBFile(self, source, dest):
"""Compiles a XIB file with ibtool into a binary plist in the bundle."""
# ibtool sometimes crashes with relative paths. See crbug.com/314728.
base = os.path.dirname(os.path.realpath(__file__))
if os.path.relpath(source):
source = os.path.join(base, source)
if os.path.relpath(dest):
dest = os.path.join(base, dest)
args = ['xcrun', 'ibtool', '--errors', '--warnings', '--notices',
'--output-format', 'human-readable-text', '--compile', dest, source]
ibtool_section_re = re.compile(r'/\*.*\*/')
ibtool_re = re.compile(r'.*note:.*is clipping its content')
ibtoolout = subprocess.Popen(args, stdout=subprocess.PIPE)
current_section_header = None
for line in ibtoolout.stdout:
if ibtool_section_re.match(line):
current_section_header = line
elif not ibtool_re.match(line):
if current_section_header:
sys.stdout.write(current_section_header)
current_section_header = None
sys.stdout.write(line)
return ibtoolout.returncode
def _ConvertToBinary(self, dest):
subprocess.check_call([
'xcrun', 'plutil', '-convert', 'binary1', '-o', dest, dest])
def _CopyStringsFile(self, source, dest, convert_to_binary):
"""Copies a .strings file using iconv to reconvert the input into UTF-16."""
input_code = self._DetectInputEncoding(source) or "UTF-8"
# Xcode's CpyCopyStringsFile / builtin-copyStrings seems to call
# CFPropertyListCreateFromXMLData() behind the scenes; at least it prints
# CFPropertyListCreateFromXMLData(): Old-style plist parser: missing
# semicolon in dictionary.
# on invalid files. Do the same kind of validation.
import CoreFoundation
s = open(source, 'rb').read()
d = CoreFoundation.CFDataCreate(None, s, len(s))
_, error = CoreFoundation.CFPropertyListCreateFromXMLData(None, d, 0, None)
if error:
return
fp = open(dest, 'wb')
fp.write(s.decode(input_code).encode('UTF-16'))
fp.close()
if convert_to_binary == 'True':
self._ConvertToBinary(dest)
def _DetectInputEncoding(self, file_name):
"""Reads the first few bytes from file_name and tries to guess the text
encoding. Returns None as a guess if it can't detect it."""
fp = open(file_name, 'rb')
try:
header = fp.read(3)
except e:
fp.close()
return None
fp.close()
if header.startswith("\xFE\xFF"):
return "UTF-16"
elif header.startswith("\xFF\xFE"):
return "UTF-16"
elif header.startswith("\xEF\xBB\xBF"):
return "UTF-8"
else:
return None
def ExecCopyInfoPlist(self, source, dest, convert_to_binary, *keys):
"""Copies the |source| Info.plist to the destination directory |dest|."""
# Read the source Info.plist into memory.
fd = open(source, 'r')
lines = fd.read()
fd.close()
# Insert synthesized key/value pairs (e.g. BuildMachineOSBuild).
plist = plistlib.readPlistFromString(lines)
if keys:
plist = dict(plist.items() + json.loads(keys[0]).items())
lines = plistlib.writePlistToString(plist)
# Go through all the environment variables and replace them as variables in
# the file.
IDENT_RE = re.compile(r'[/\s]')
for key in os.environ:
if key.startswith('_'):
continue
evar = '${%s}' % key
evalue = os.environ[key]
lines = string.replace(lines, evar, evalue)
# Xcode supports various suffices on environment variables, which are
# all undocumented. :rfc1034identifier is used in the standard project
# template these days, and :identifier was used earlier. They are used to
# convert non-url characters into things that look like valid urls --
# except that the replacement character for :identifier, '_' isn't valid
# in a URL either -- oops, hence :rfc1034identifier was born.
evar = '${%s:identifier}' % key
evalue = IDENT_RE.sub('_', os.environ[key])
lines = string.replace(lines, evar, evalue)
evar = '${%s:rfc1034identifier}' % key
evalue = IDENT_RE.sub('-', os.environ[key])
lines = string.replace(lines, evar, evalue)
# Remove any keys with values that haven't been replaced.
lines = lines.split('\n')
for i in range(len(lines)):
if lines[i].strip().startswith("<string>${"):
lines[i] = None
lines[i - 1] = None
lines = '\n'.join(filter(lambda x: x is not None, lines))
# Write out the file with variables replaced.
fd = open(dest, 'w')
fd.write(lines)
fd.close()
# Now write out PkgInfo file now that the Info.plist file has been
# "compiled".
self._WritePkgInfo(dest)
if convert_to_binary == 'True':
self._ConvertToBinary(dest)
def _WritePkgInfo(self, info_plist):
"""This writes the PkgInfo file from the data stored in Info.plist."""
plist = plistlib.readPlist(info_plist)
if not plist:
return
# Only create PkgInfo for executable types.
package_type = plist['CFBundlePackageType']
if package_type != 'APPL':
return
# The format of PkgInfo is eight characters, representing the bundle type
# and bundle signature, each four characters. If that is missing, four
# '?' characters are used instead.
signature_code = plist.get('CFBundleSignature', '????')
if len(signature_code) != 4: # Wrong length resets everything, too.
signature_code = '?' * 4
dest = os.path.join(os.path.dirname(info_plist), 'PkgInfo')
fp = open(dest, 'w')
fp.write('%s%s' % (package_type, signature_code))
fp.close()
def ExecFlock(self, lockfile, *cmd_list):
"""Emulates the most basic behavior of Linux's flock(1)."""
# Rely on exception handling to report errors.
fd = os.open(lockfile, os.O_RDONLY|os.O_NOCTTY|os.O_CREAT, 0o666)
fcntl.flock(fd, fcntl.LOCK_EX)
return subprocess.call(cmd_list)
def ExecFilterLibtool(self, *cmd_list):
"""Calls libtool and filters out '/path/to/libtool: file: foo.o has no
symbols'."""
libtool_re = re.compile(r'^.*libtool: file: .* has no symbols$')
libtool_re5 = re.compile(
r'^.*libtool: warning for library: ' +
r'.* the table of contents is empty ' +
r'\(no object file members in the library define global symbols\)$')
env = os.environ.copy()
# Ref:
# http://www.opensource.apple.com/source/cctools/cctools-809/misc/libtool.c
# The problem with this flag is that it resets the file mtime on the file to
# epoch=0, e.g. 1970-1-1 or 1969-12-31 depending on timezone.
env['ZERO_AR_DATE'] = '1'
libtoolout = subprocess.Popen(cmd_list, stderr=subprocess.PIPE, env=env)
_, err = libtoolout.communicate()
for line in err.splitlines():
if not libtool_re.match(line) and not libtool_re5.match(line):
print >>sys.stderr, line
# Unconditionally touch the output .a file on the command line if present
# and the command succeeded. A bit hacky.
if not libtoolout.returncode:
for i in range(len(cmd_list) - 1):
if cmd_list[i] == "-o" and cmd_list[i+1].endswith('.a'):
os.utime(cmd_list[i+1], None)
break
return libtoolout.returncode
def ExecPackageFramework(self, framework, version):
"""Takes a path to Something.framework and the Current version of that and
sets up all the symlinks."""
# Find the name of the binary based on the part before the ".framework".
binary = os.path.basename(framework).split('.')[0]
CURRENT = 'Current'
RESOURCES = 'Resources'
VERSIONS = 'Versions'
if not os.path.exists(os.path.join(framework, VERSIONS, version, binary)):
# Binary-less frameworks don't seem to contain symlinks (see e.g.
# chromium's out/Debug/org.chromium.Chromium.manifest/ bundle).
return
# Move into the framework directory to set the symlinks correctly.
pwd = os.getcwd()
os.chdir(framework)
# Set up the Current version.
self._Relink(version, os.path.join(VERSIONS, CURRENT))
# Set up the root symlinks.
self._Relink(os.path.join(VERSIONS, CURRENT, binary), binary)
self._Relink(os.path.join(VERSIONS, CURRENT, RESOURCES), RESOURCES)
# Back to where we were before!
os.chdir(pwd)
def _Relink(self, dest, link):
"""Creates a symlink to |dest| named |link|. If |link| already exists,
it is overwritten."""
if os.path.lexists(link):
os.remove(link)
os.symlink(dest, link)
def ExecCompileXcassets(self, keys, *inputs):
"""Compiles multiple .xcassets files into a single .car file.
This invokes 'actool' to compile all the inputs .xcassets files. The
|keys| arguments is a json-encoded dictionary of extra arguments to
pass to 'actool' when the asset catalogs contains an application icon
or a launch image.
Note that 'actool' does not create the Assets.car file if the asset
catalogs does not contains imageset.
"""
command_line = [
'xcrun', 'actool', '--output-format', 'human-readable-text',
'--compress-pngs', '--notices', '--warnings', '--errors',
]
is_iphone_target = 'IPHONEOS_DEPLOYMENT_TARGET' in os.environ
if is_iphone_target:
platform = os.environ['CONFIGURATION'].split('-')[-1]
if platform not in ('iphoneos', 'iphonesimulator'):
platform = 'iphonesimulator'
command_line.extend([
'--platform', platform, '--target-device', 'iphone',
'--target-device', 'ipad', '--minimum-deployment-target',
os.environ['IPHONEOS_DEPLOYMENT_TARGET'], '--compile',
os.path.abspath(os.environ['CONTENTS_FOLDER_PATH']),
])
else:
command_line.extend([
'--platform', 'macosx', '--target-device', 'mac',
'--minimum-deployment-target', os.environ['MACOSX_DEPLOYMENT_TARGET'],
'--compile',
os.path.abspath(os.environ['UNLOCALIZED_RESOURCES_FOLDER_PATH']),
])
if keys:
keys = json.loads(keys)
for key, value in keys.iteritems():
arg_name = '--' + key
if isinstance(value, bool):
if value:
command_line.append(arg_name)
elif isinstance(value, list):
for v in value:
command_line.append(arg_name)
command_line.append(str(v))
else:
command_line.append(arg_name)
command_line.append(str(value))
# Note: actool crashes if inputs path are relative, so use os.path.abspath
# to get absolute path name for inputs.
command_line.extend(map(os.path.abspath, inputs))
subprocess.check_call(command_line)
def ExecMergeInfoPlist(self, output, *inputs):
"""Merge multiple .plist files into a single .plist file."""
merged_plist = {}
for path in inputs:
plist = self._LoadPlistMaybeBinary(path)
self._MergePlist(merged_plist, plist)
plistlib.writePlist(merged_plist, output)
def ExecCodeSignBundle(self, key, resource_rules, entitlements, provisioning):
"""Code sign a bundle.
This function tries to code sign an iOS bundle, following the same
algorithm as Xcode:
1. copy ResourceRules.plist from the user or the SDK into the bundle,
2. pick the provisioning profile that best match the bundle identifier,
and copy it into the bundle as embedded.mobileprovision,
3. copy Entitlements.plist from user or SDK next to the bundle,
4. code sign the bundle.
"""
resource_rules_path = self._InstallResourceRules(resource_rules)
substitutions, overrides = self._InstallProvisioningProfile(
provisioning, self._GetCFBundleIdentifier())
entitlements_path = self._InstallEntitlements(
entitlements, substitutions, overrides)
subprocess.check_call([
'codesign', '--force', '--sign', key, '--resource-rules',
resource_rules_path, '--entitlements', entitlements_path,
os.path.join(
os.environ['TARGET_BUILD_DIR'],
os.environ['FULL_PRODUCT_NAME'])])
def _InstallResourceRules(self, resource_rules):
"""Installs ResourceRules.plist from user or SDK into the bundle.
Args:
resource_rules: string, optional, path to the ResourceRules.plist file
to use, default to "${SDKROOT}/ResourceRules.plist"
Returns:
Path to the copy of ResourceRules.plist into the bundle.
"""
source_path = resource_rules
target_path = os.path.join(
os.environ['BUILT_PRODUCTS_DIR'],
os.environ['CONTENTS_FOLDER_PATH'],
'ResourceRules.plist')
if not source_path:
source_path = os.path.join(
os.environ['SDKROOT'], 'ResourceRules.plist')
shutil.copy2(source_path, target_path)
return target_path
def _InstallProvisioningProfile(self, profile, bundle_identifier):
"""Installs embedded.mobileprovision into the bundle.
Args:
profile: string, optional, short name of the .mobileprovision file
to use, if empty or the file is missing, the best file installed
will be used
bundle_identifier: string, value of CFBundleIdentifier from Info.plist
Returns:
A tuple containing two dictionary: variables substitutions and values
to overrides when generating the entitlements file.
"""
source_path, provisioning_data, team_id = self._FindProvisioningProfile(
profile, bundle_identifier)
target_path = os.path.join(
os.environ['BUILT_PRODUCTS_DIR'],
os.environ['CONTENTS_FOLDER_PATH'],
'embedded.mobileprovision')
shutil.copy2(source_path, target_path)
substitutions = self._GetSubstitutions(bundle_identifier, team_id + '.')
return substitutions, provisioning_data['Entitlements']
def _FindProvisioningProfile(self, profile, bundle_identifier):
"""Finds the .mobileprovision file to use for signing the bundle.
Checks all the installed provisioning profiles (or if the user specified
the PROVISIONING_PROFILE variable, only consult it) and select the most
specific that correspond to the bundle identifier.
Args:
profile: string, optional, short name of the .mobileprovision file
to use, if empty or the file is missing, the best file installed
will be used
bundle_identifier: string, value of CFBundleIdentifier from Info.plist
Returns:
A tuple of the path to the selected provisioning profile, the data of
the embedded plist in the provisioning profile and the team identifier
to use for code signing.
Raises:
SystemExit: if no .mobileprovision can be used to sign the bundle.
"""
profiles_dir = os.path.join(
os.environ['HOME'], 'Library', 'MobileDevice', 'Provisioning Profiles')
if not os.path.isdir(profiles_dir):
print >>sys.stderr, (
'cannot find mobile provisioning for %s' % bundle_identifier)
sys.exit(1)
provisioning_profiles = None
if profile:
profile_path = os.path.join(profiles_dir, profile + '.mobileprovision')
if os.path.exists(profile_path):
provisioning_profiles = [profile_path]
if not provisioning_profiles:
provisioning_profiles = glob.glob(
os.path.join(profiles_dir, '*.mobileprovision'))
valid_provisioning_profiles = {}
for profile_path in provisioning_profiles:
profile_data = self._LoadProvisioningProfile(profile_path)
app_id_pattern = profile_data.get(
'Entitlements', {}).get('application-identifier', '')
for team_identifier in profile_data.get('TeamIdentifier', []):
app_id = '%s.%s' % (team_identifier, bundle_identifier)
if fnmatch.fnmatch(app_id, app_id_pattern):
valid_provisioning_profiles[app_id_pattern] = (
profile_path, profile_data, team_identifier)
if not valid_provisioning_profiles:
print >>sys.stderr, (
'cannot find mobile provisioning for %s' % bundle_identifier)
sys.exit(1)
# If the user has multiple provisioning profiles installed that can be
# used for ${bundle_identifier}, pick the most specific one (ie. the
# provisioning profile whose pattern is the longest).
selected_key = max(valid_provisioning_profiles, key=lambda v: len(v))
return valid_provisioning_profiles[selected_key]
def _LoadProvisioningProfile(self, profile_path):
"""Extracts the plist embedded in a provisioning profile.
Args:
profile_path: string, path to the .mobileprovision file
Returns:
Content of the plist embedded in the provisioning profile as a dictionary.
"""
with tempfile.NamedTemporaryFile() as temp:
subprocess.check_call([
'security', 'cms', '-D', '-i', profile_path, '-o', temp.name])
return self._LoadPlistMaybeBinary(temp.name)
def _MergePlist(self, merged_plist, plist):
"""Merge |plist| into |merged_plist|."""
for key, value in plist.iteritems():
if isinstance(value, dict):
merged_value = merged_plist.get(key, {})
if isinstance(merged_value, dict):
self._MergePlist(merged_value, value)
merged_plist[key] = merged_value
else:
merged_plist[key] = value
else:
merged_plist[key] = value
def _LoadPlistMaybeBinary(self, plist_path):
"""Loads into a memory a plist possibly encoded in binary format.
This is a wrapper around plistlib.readPlist that tries to convert the
plist to the XML format if it can't be parsed (assuming that it is in
the binary format).
Args:
plist_path: string, path to a plist file, in XML or binary format
Returns:
Content of the plist as a dictionary.
"""
try:
# First, try to read the file using plistlib that only supports XML,
# and if an exception is raised, convert a temporary copy to XML and
# load that copy.
return plistlib.readPlist(plist_path)
except:
pass
with tempfile.NamedTemporaryFile() as temp:
shutil.copy2(plist_path, temp.name)
subprocess.check_call(['plutil', '-convert', 'xml1', temp.name])
return plistlib.readPlist(temp.name)
def _GetSubstitutions(self, bundle_identifier, app_identifier_prefix):
"""Constructs a dictionary of variable substitutions for Entitlements.plist.
Args:
bundle_identifier: string, value of CFBundleIdentifier from Info.plist
app_identifier_prefix: string, value for AppIdentifierPrefix
Returns:
Dictionary of substitutions to apply when generating Entitlements.plist.
"""
return {
'CFBundleIdentifier': bundle_identifier,
'AppIdentifierPrefix': app_identifier_prefix,
}
def _GetCFBundleIdentifier(self):
"""Extracts CFBundleIdentifier value from Info.plist in the bundle.
Returns:
Value of CFBundleIdentifier in the Info.plist located in the bundle.
"""
info_plist_path = os.path.join(
os.environ['TARGET_BUILD_DIR'],
os.environ['INFOPLIST_PATH'])
info_plist_data = self._LoadPlistMaybeBinary(info_plist_path)
return info_plist_data['CFBundleIdentifier']
def _InstallEntitlements(self, entitlements, substitutions, overrides):
"""Generates and install the ${BundleName}.xcent entitlements file.
Expands variables "$(variable)" pattern in the source entitlements file,
add extra entitlements defined in the .mobileprovision file and the copy
the generated plist to "${BundlePath}.xcent".
Args:
entitlements: string, optional, path to the Entitlements.plist template
to use, defaults to "${SDKROOT}/Entitlements.plist"
substitutions: dictionary, variable substitutions
overrides: dictionary, values to add to the entitlements
Returns:
Path to the generated entitlements file.
"""
source_path = entitlements
target_path = os.path.join(
os.environ['BUILT_PRODUCTS_DIR'],
os.environ['PRODUCT_NAME'] + '.xcent')
if not source_path:
source_path = os.path.join(
os.environ['SDKROOT'],
'Entitlements.plist')
shutil.copy2(source_path, target_path)
data = self._LoadPlistMaybeBinary(target_path)
data = self._ExpandVariables(data, substitutions)
if overrides:
for key in overrides:
if key not in data:
data[key] = overrides[key]
plistlib.writePlist(data, target_path)
return target_path
def _ExpandVariables(self, data, substitutions):
"""Expands variables "$(variable)" in data.
Args:
data: object, can be either string, list or dictionary
substitutions: dictionary, variable substitutions to perform
Returns:
Copy of data where each references to "$(variable)" has been replaced
by the corresponding value found in substitutions, or left intact if
the key was not found.
"""
if isinstance(data, str):
for key, value in substitutions.iteritems():
data = data.replace('$(%s)' % key, value)
return data
if isinstance(data, list):
return [self._ExpandVariables(v, substitutions) for v in data]
if isinstance(data, dict):
return {k: self._ExpandVariables(data[k], substitutions) for k in data}
return data
if __name__ == '__main__':
sys.exit(main(sys.argv[1:]))

169
test/gc/node_modules/weak/build/weakref.target.mk

@ -0,0 +1,169 @@
# This file is generated by gyp; do not edit.
TOOLSET := target
TARGET := weakref
DEFS_Debug := \
'-DNODE_GYP_MODULE_NAME=weakref' \
'-D_DARWIN_USE_64_BIT_INODE=1' \
'-D_LARGEFILE_SOURCE' \
'-D_FILE_OFFSET_BITS=64' \
'-DBUILDING_NODE_EXTENSION' \
'-DDEBUG' \
'-D_DEBUG'
# Flags passed to all source files.
CFLAGS_Debug := \
-O0 \
-gdwarf-2 \
-mmacosx-version-min=10.7 \
-arch x86_64 \
-Wall \
-Wendif-labels \
-W \
-Wno-unused-parameter
# Flags passed to only C files.
CFLAGS_C_Debug := \
-fno-strict-aliasing
# Flags passed to only C++ files.
CFLAGS_CC_Debug := \
-std=gnu++0x \
-fno-rtti \
-fno-exceptions \
-fno-threadsafe-statics \
-fno-strict-aliasing
# Flags passed to only ObjC files.
CFLAGS_OBJC_Debug :=
# Flags passed to only ObjC++ files.
CFLAGS_OBJCC_Debug :=
INCS_Debug := \
-I/Users/trott/io.js/include/node \
-I/Users/trott/io.js/src \
-I/Users/trott/io.js/deps/uv/include \
-I/Users/trott/io.js/deps/v8/include \
-I$(srcdir)/../nan
DEFS_Release := \
'-DNODE_GYP_MODULE_NAME=weakref' \
'-D_DARWIN_USE_64_BIT_INODE=1' \
'-D_LARGEFILE_SOURCE' \
'-D_FILE_OFFSET_BITS=64' \
'-DBUILDING_NODE_EXTENSION'
# Flags passed to all source files.
CFLAGS_Release := \
-Os \
-gdwarf-2 \
-mmacosx-version-min=10.7 \
-arch x86_64 \
-Wall \
-Wendif-labels \
-W \
-Wno-unused-parameter
# Flags passed to only C files.
CFLAGS_C_Release := \
-fno-strict-aliasing
# Flags passed to only C++ files.
CFLAGS_CC_Release := \
-std=gnu++0x \
-fno-rtti \
-fno-exceptions \
-fno-threadsafe-statics \
-fno-strict-aliasing
# Flags passed to only ObjC files.
CFLAGS_OBJC_Release :=
# Flags passed to only ObjC++ files.
CFLAGS_OBJCC_Release :=
INCS_Release := \
-I/Users/trott/io.js/include/node \
-I/Users/trott/io.js/src \
-I/Users/trott/io.js/deps/uv/include \
-I/Users/trott/io.js/deps/v8/include \
-I$(srcdir)/../nan
OBJS := \
$(obj).target/$(TARGET)/src/weakref.o
# Add to the list of files we specially track dependencies for.
all_deps += $(OBJS)
# CFLAGS et al overrides must be target-local.
# See "Target-specific Variable Values" in the GNU Make manual.
$(OBJS): TOOLSET := $(TOOLSET)
$(OBJS): GYP_CFLAGS := $(DEFS_$(BUILDTYPE)) $(INCS_$(BUILDTYPE)) $(CFLAGS_$(BUILDTYPE)) $(CFLAGS_C_$(BUILDTYPE))
$(OBJS): GYP_CXXFLAGS := $(DEFS_$(BUILDTYPE)) $(INCS_$(BUILDTYPE)) $(CFLAGS_$(BUILDTYPE)) $(CFLAGS_CC_$(BUILDTYPE))
$(OBJS): GYP_OBJCFLAGS := $(DEFS_$(BUILDTYPE)) $(INCS_$(BUILDTYPE)) $(CFLAGS_$(BUILDTYPE)) $(CFLAGS_C_$(BUILDTYPE)) $(CFLAGS_OBJC_$(BUILDTYPE))
$(OBJS): GYP_OBJCXXFLAGS := $(DEFS_$(BUILDTYPE)) $(INCS_$(BUILDTYPE)) $(CFLAGS_$(BUILDTYPE)) $(CFLAGS_CC_$(BUILDTYPE)) $(CFLAGS_OBJCC_$(BUILDTYPE))
# Suffix rules, putting all outputs into $(obj).
$(obj).$(TOOLSET)/$(TARGET)/%.o: $(srcdir)/%.cc FORCE_DO_CMD
@$(call do_cmd,cxx,1)
# Try building from generated source, too.
$(obj).$(TOOLSET)/$(TARGET)/%.o: $(obj).$(TOOLSET)/%.cc FORCE_DO_CMD
@$(call do_cmd,cxx,1)
$(obj).$(TOOLSET)/$(TARGET)/%.o: $(obj)/%.cc FORCE_DO_CMD
@$(call do_cmd,cxx,1)
# End of this set of suffix rules
### Rules for final target.
LDFLAGS_Debug := \
-undefined dynamic_lookup \
-Wl,-no_pie \
-Wl,-search_paths_first \
-mmacosx-version-min=10.7 \
-arch x86_64 \
-L$(builddir)
LIBTOOLFLAGS_Debug := \
-undefined dynamic_lookup \
-Wl,-no_pie \
-Wl,-search_paths_first
LDFLAGS_Release := \
-undefined dynamic_lookup \
-Wl,-no_pie \
-Wl,-search_paths_first \
-mmacosx-version-min=10.7 \
-arch x86_64 \
-L$(builddir)
LIBTOOLFLAGS_Release := \
-undefined dynamic_lookup \
-Wl,-no_pie \
-Wl,-search_paths_first
LIBS :=
$(builddir)/weakref.node: GYP_LDFLAGS := $(LDFLAGS_$(BUILDTYPE))
$(builddir)/weakref.node: LIBS := $(LIBS)
$(builddir)/weakref.node: GYP_LIBTOOLFLAGS := $(LIBTOOLFLAGS_$(BUILDTYPE))
$(builddir)/weakref.node: TOOLSET := $(TOOLSET)
$(builddir)/weakref.node: $(OBJS) FORCE_DO_CMD
$(call do_cmd,solink_module)
all_deps += $(builddir)/weakref.node
# Add target alias
.PHONY: weakref
weakref: $(builddir)/weakref.node
# Short alias for building this executable.
.PHONY: weakref.node
weakref.node: $(builddir)/weakref.node
# Add executable to "all" target.
.PHONY: all
all: $(builddir)/weakref.node

121
test/gc/node_modules/weak/lib/weak.js

@ -1,19 +1,110 @@
'use strict';
var bindings
try {
bindings = require('../build/Release/weakref.node')
} catch (e) {
if (e.code === 'MODULE_NOT_FOUND') {
bindings = require('../build/Debug/weakref.node')
} else {
throw e
/**
* Module dependencies.
*/
var Emitter = require('events').EventEmitter;
var bindings = require('bindings')('weakref.node');
/**
* Set global weak callback function.
*/
bindings._setCallback(callback);
/**
* Module exports.
*/
exports = module.exports = create;
exports.addCallback = exports.addListener = addCallback;
exports.removeCallback = exports.removeListener = removeCallback;
exports.removeCallbacks = exports.removeListeners = removeCallbacks;
exports.callbacks = exports.listeners = callbacks;
// backwards-compat with node-weakref
exports.weaken = exports.create = exports;
// re-export all the binding functions onto the exports
Object.keys(bindings).forEach(function (name) {
exports[name] = bindings[name];
});
/**
* Internal emitter event name.
* This is completely arbitrary...
* Could be any value....
*/
var CB = '_CB';
/**
* Creates and returns a new Weakref instance. Optionally attaches
* a weak callback to invoke when the Object gets garbage collected.
*
* @api public
*/
function create (obj, fn) {
var weakref = bindings._create(obj, new Emitter());
if ('function' == typeof fn) {
exports.addCallback(weakref, fn);
}
return weakref;
}
module.exports = bindings.create
// backwards-compat with node-weakref
bindings.weaken = bindings.create
/**
* Adds a weak callback function to the Weakref instance.
*
* @api public
*/
Object.keys(bindings).forEach(function(name) {
module.exports[name] = bindings[name]
})
function addCallback (weakref, fn) {
var emitter = bindings._getEmitter(weakref);
return emitter.on(CB, fn);
}
/**
* Removes a weak callback function from the Weakref instance.
*
* @api public
*/
function removeCallback (weakref, fn) {
var emitter = bindings._getEmitter(weakref);
return emitter.removeListener(CB, fn);
}
/**
* Returns a copy of the listeners on the Weakref instance.
*
* @api public
*/
function callbacks (weakref) {
var emitter = bindings._getEmitter(weakref);
return emitter.listeners(CB);
}
/**
* Removes all callbacks on the Weakref instance.
*
* @api public
*/
function removeCallbacks (weakref) {
var emitter = bindings._getEmitter(weakref);
return emitter.removeAllListeners(CB);
}
/**
* Common weak callback function.
*
* @api private
*/
function callback (emitter) {
emitter.emit(CB);
emitter = null;
}

102
test/gc/node_modules/weak/package.json

@ -1,17 +1,68 @@
{
"_args": [
[
"weak",
"/Users/trott/io.js/test/gc"
]
],
"_from": "weak@latest",
"_id": "weak@1.0.1",
"_inCache": true,
"_installable": true,
"_location": "/weak",
"_nodeVersion": "5.3.0",
"_npmUser": {
"email": "nathan@tootallnate.net",
"name": "tootallnate"
},
"_npmVersion": "3.3.12",
"_phantomChildren": {},
"_requested": {
"name": "weak",
"raw": "weak",
"rawSpec": "",
"scope": null,
"spec": "latest",
"type": "tag"
},
"_requiredBy": [
"#USER"
],
"_resolved": "https://registry.npmjs.org/weak/-/weak-1.0.1.tgz",
"_shasum": "ab99aab30706959aa0200cb8cf545bb9cb33b99e",
"_shrinkwrap": null,
"_spec": "weak",
"_where": "/Users/trott/io.js/test/gc",
"author": {
"name": "Ben Noordhuis",
"email": "info@bnoordhuis.nl"
"email": "info@bnoordhuis.nl",
"name": "Ben Noordhuis"
},
"bugs": {
"url": "https://github.com/TooTallNate/node-weak/issues"
},
"contributors": [
{
"name": "Nathan Rajlich",
"email": "nathan@tootallnate.net",
"name": "Nathan Rajlich",
"url": "http://tootallnate.net"
}
],
"name": "weak",
"dependencies": {
"bindings": "^1.2.1",
"nan": "^2.0.5"
},
"description": "Make weak references to JavaScript Objects.",
"devDependencies": {
"mocha": "~2.1.0"
},
"directories": {},
"dist": {
"shasum": "ab99aab30706959aa0200cb8cf545bb9cb33b99e",
"tarball": "http://registry.npmjs.org/weak/-/weak-1.0.1.tgz"
},
"gitHead": "1c3b0376dab966782e5d1fcf06f9fcb1309cb2c0",
"gypfile": true,
"homepage": "https://github.com/TooTallNate/node-weak#readme",
"keywords": [
"weak",
"reference",
@ -21,35 +72,28 @@
"function",
"callback"
],
"version": "0.2.1",
"license": "MIT",
"main": "lib/weak.js",
"maintainers": [
{
"email": "nathan@tootallnate.net",
"name": "TooTallNate"
},
{
"email": "nathan@tootallnate.net",
"name": "tootallnate"
}
],
"name": "weak",
"optionalDependencies": {},
"readme": "ERROR: No README data found!",
"repository": {
"type": "git",
"url": "git://github.com/TooTallNate/node-weak.git"
},
"main": "./lib/weak.js",
"scripts": {
"test": "mocha -gc --reporter spec",
"install": "node-gyp rebuild"
},
"engines": {
"node": "*"
"install": "node-gyp rebuild",
"test": "mocha -gc --reporter spec"
},
"dependencies": {
"bindings": "*"
},
"devDependencies": {
"mocha": "> 0.7.0",
"should": "*"
},
"_npmUser": {
"name": "tootallnate",
"email": "nathan@tootallnate.net"
},
"_id": "weak@0.2.1",
"optionalDependencies": {},
"_engineSupported": true,
"_npmVersion": "1.1.25",
"_nodeVersion": "v0.7.10",
"_defaultsLoaded": true,
"_from": "weak"
"version": "1.0.1"
}

371
test/gc/node_modules/weak/src/weakref.cc

@ -15,45 +15,31 @@
*/
#include <stdlib.h>
#include "v8.h"
#include "node.h"
#include <nan.h>
using namespace v8;
namespace {
using node::FatalException;
using v8::Array;
using v8::Boolean;
using v8::Exception;
using v8::Function;
using v8::FunctionTemplate;
using v8::FunctionCallbackInfo;
using v8::HandleScope;
using v8::Integer;
using v8::Isolate;
using v8::Local;
using v8::None;
using v8::Object;
using v8::ObjectTemplate;
using v8::Persistent;
using v8::PropertyCallbackInfo;
using v8::Value;
using v8::String;
using v8::TryCatch;
typedef struct proxy_container {
Persistent<Object> proxy;
Persistent<Object> target;
Persistent<Array> callbacks;
} proxy_container;
Persistent<ObjectTemplate> proxyClass;
class proxy_container {
public:
Nan::Persistent<Object> proxy;
Nan::Persistent<Object> emitter;
Nan::Persistent<Object> target;
};
Nan::Persistent<ObjectTemplate> proxyClass;
Nan::Callback *globalCallback;
bool IsDead(Local<Object> proxy) {
assert(proxy->InternalFieldCount() == 1);
proxy_container *cont = reinterpret_cast<proxy_container*>(
proxy->GetAlignedPointerFromInternalField(0));
Nan::GetInternalFieldPointer(proxy, 0)
);
return cont == NULL || cont->target.IsEmpty();
}
@ -61,160 +47,133 @@ bool IsDead(Local<Object> proxy) {
Local<Object> Unwrap(Local<Object> proxy) {
assert(!IsDead(proxy));
proxy_container *cont = reinterpret_cast<proxy_container*>(
proxy->GetAlignedPointerFromInternalField(0));
Isolate* isolate = Isolate::GetCurrent();
return Local<Object>::New(isolate, cont->target);
Nan::GetInternalFieldPointer(proxy, 0)
);
Local<Object> _target = Nan::New<Object>(cont->target);
return _target;
}
Local<Array> GetCallbacks(Local<Object> proxy) {
Local<Object> GetEmitter(Local<Object> proxy) {
proxy_container *cont = reinterpret_cast<proxy_container*>(
proxy->GetAlignedPointerFromInternalField(0));
Nan::GetInternalFieldPointer(proxy, 0)
);
assert(cont != NULL);
Isolate* isolate = Isolate::GetCurrent();
return Local<Array>::New(isolate, cont->callbacks);
Local<Object> _emitter = Nan::New<Object>(cont->emitter);
return _emitter;
}
#define UNWRAP \
HandleScope scope(info.GetIsolate()); \
Local<Object> obj; \
Local<Object> obj; \
const bool dead = IsDead(info.This()); \
if (!dead) obj = Unwrap(info.This()); \
void ThrowTypeError(Isolate* isolate, const char* message) {
HandleScope scope(isolate);
Local<String> emessage = String::NewFromUtf8(isolate, message);
isolate->ThrowException(v8::Exception::TypeError(emessage));
}
void WeakNamedPropertyGetter(Local<String> property,
const PropertyCallbackInfo<Value>& info) {
NAN_PROPERTY_GETTER(WeakNamedPropertyGetter) {
UNWRAP
if (!dead) info.GetReturnValue().Set(obj->Get(property));
info.GetReturnValue().Set(dead ? Local<Value>() : Nan::Get(obj, property).ToLocalChecked());
}
void WeakNamedPropertySetter(Local<String> property,
Local<Value> value,
const PropertyCallbackInfo<Value>& info) {
NAN_PROPERTY_SETTER(WeakNamedPropertySetter) {
UNWRAP
if (!dead) obj->Set(property, value);
if (!dead) Nan::Set(obj, property, value);
info.GetReturnValue().Set(value);
}
void WeakNamedPropertyQuery(Local<String> property,
const PropertyCallbackInfo<Integer>& info) {
NAN_PROPERTY_QUERY(WeakNamedPropertyQuery) {
info.GetReturnValue().Set(None);
}
void WeakNamedPropertyDeleter(Local<String> property,
const PropertyCallbackInfo<Boolean>& info) {
NAN_PROPERTY_DELETER(WeakNamedPropertyDeleter) {
UNWRAP
info.GetReturnValue().Set(!dead && obj->Delete(property));
info.GetReturnValue().Set(!dead && Nan::Delete(obj, property).FromJust());
}
void WeakIndexedPropertyGetter(uint32_t index,
const PropertyCallbackInfo<Value>& info) {
NAN_INDEX_GETTER(WeakIndexedPropertyGetter) {
UNWRAP
if (!dead) info.GetReturnValue().Set(obj->Get(index));
info.GetReturnValue().Set(dead ? Local<Value>() : Nan::Get(obj, index).ToLocalChecked());
}
void WeakIndexedPropertySetter(uint32_t index,
Local<Value> value,
const PropertyCallbackInfo<Value>& info) {
NAN_INDEX_SETTER(WeakIndexedPropertySetter) {
UNWRAP
if (!dead) obj->Set(index, value);
if (!dead) Nan::Set(obj, index, value);
info.GetReturnValue().Set(value);
}
void WeakIndexedPropertyQuery(uint32_t index,
const PropertyCallbackInfo<Integer>& info) {
NAN_INDEX_QUERY(WeakIndexedPropertyQuery) {
info.GetReturnValue().Set(None);
}
void WeakIndexedPropertyDeleter(uint32_t index,
const PropertyCallbackInfo<Boolean>& info) {
NAN_INDEX_DELETER(WeakIndexedPropertyDeleter) {
UNWRAP
info.GetReturnValue().Set(!dead && obj->Delete(index));
info.GetReturnValue().Set(!dead && Nan::Delete(obj, index).FromJust());
}
void WeakPropertyEnumerator(const PropertyCallbackInfo<Array>& info) {
UNWRAP
info.GetReturnValue().Set(dead ? Array::New(0) : obj->GetPropertyNames());
}
/**
* Only one "enumerator" function needs to be defined. This function is used for
* both the property and indexed enumerator functions.
*/
void AddCallback(Isolate* isolate, Local<Object> proxy, Local<Function> callback) {
Local<Array> callbacks = GetCallbacks(proxy);
callbacks->Set(Integer::New(isolate, callbacks->Length()), callback);
NAN_PROPERTY_ENUMERATOR(WeakPropertyEnumerator) {
UNWRAP
info.GetReturnValue().Set(dead ? Nan::New<Array>(0) : Nan::GetPropertyNames(obj).ToLocalChecked());
}
/**
* Weakref callback function. Invokes the "global" callback function,
* which emits the _CB event on the per-object EventEmitter.
*/
static void TargetCallback(const v8::WeakCallbackData<v8::Object, proxy_container>& data) {
Isolate* isolate = data.GetIsolate();
HandleScope scope(isolate);
Local<Object> target = data.GetValue();
proxy_container* cont = data.GetParameter();
// invoke any listening callbacks
Local<Array> callbacks = Local<Array>::New(isolate, cont->callbacks);
uint32_t len = callbacks->Length();
Local<Value> argv[1];
argv[0] = target;
for (uint32_t i=0; i<len; i++) {
Local<Function> cb = Local<Function>::Cast(
callbacks->Get(Integer::New(isolate, i)));
TryCatch try_catch;
cb->Call(target, 1, argv);
if (try_catch.HasCaught()) {
FatalException(try_catch);
}
}
static void TargetCallback(const Nan::WeakCallbackInfo<proxy_container> &info) {
Nan::HandleScope scope;
proxy_container *cont = info.GetParameter();
// invoke global callback function
Local<Value> argv[] = {
Nan::New<Object>(cont->emitter)
};
// Invoke callback directly, not via Nan::Callback->Call() which uses
// node::MakeCallback() which calls into process._tickCallback()
// too. Those other callbacks are not safe to run from here.
v8::Local<v8::Function> globalCallbackDirect = globalCallback->GetFunction();
globalCallbackDirect->Call(Nan::GetCurrentContext()->Global(), 1, argv);
// clean everything up
Local<Object> proxy = Nan::New<Object>(cont->proxy);
Nan::SetInternalFieldPointer(proxy, 0, NULL);
cont->proxy.Reset();
cont->target.Reset();
cont->callbacks.Reset();
cont->emitter.Reset();
delete cont;
}
/**
* `_create(obj, emitter)` JS function.
*/
void Create(const FunctionCallbackInfo<Value>& args) {
HandleScope scope(args.GetIsolate());
if (!args[0]->IsObject()) {
ThrowTypeError(args.GetIsolate(), "Object expected");
return;
}
proxy_container *cont = new proxy_container;
NAN_METHOD(Create) {
if (!info[0]->IsObject()) return Nan::ThrowTypeError("Object expected");
Isolate* isolate = args.GetIsolate();
Local<ObjectTemplate> tmpl = Local<ObjectTemplate>::New(isolate, proxyClass);
Local<Object> proxy = tmpl->NewInstance();
proxy->SetAlignedPointerInInternalField(0, cont);
proxy_container *cont = new proxy_container();
cont->proxy.Reset(Isolate::GetCurrent(), proxy);
cont->target.Reset(isolate, args[0].As<Object>());
cont->callbacks.Reset(isolate, Array::New(args.GetIsolate()));
cont->target.SetWeak(cont, TargetCallback);
Local<Object> _target = info[0].As<Object>();
Local<Object> _emitter = info[1].As<Object>();
Local<Object> proxy = Nan::New<ObjectTemplate>(proxyClass)->NewInstance();
cont->proxy.Reset(proxy);
cont->emitter.Reset(_emitter);
cont->target.Reset(_target);
Nan::SetInternalFieldPointer(proxy, 0, cont);
if (args.Length() >= 2) {
AddCallback(args.GetIsolate(), proxy, Local<Function>::Cast(args[1]));
}
cont->target.SetWeak(cont, TargetCallback, Nan::WeakCallbackType::kParameter);
args.GetReturnValue().Set(proxy);
info.GetReturnValue().Set(proxy);
}
/**
@ -222,109 +181,109 @@ void Create(const FunctionCallbackInfo<Value>& args) {
*/
bool isWeakRef (Local<Value> val) {
return val->IsObject() && val->ToObject()->InternalFieldCount() == 1;
return val->IsObject() && val.As<Object>()->InternalFieldCount() == 1;
}
void IsWeakRef (const FunctionCallbackInfo<Value>& args) {
args.GetReturnValue().Set(isWeakRef(args[0]));
}
/**
* `isWeakRef()` JS function.
*/
void Get(const FunctionCallbackInfo<Value>& args) {
HandleScope scope(args.GetIsolate());
NAN_METHOD(IsWeakRef) {
info.GetReturnValue().Set(isWeakRef(info[0]));
}
if (!isWeakRef(args[0])) {
ThrowTypeError(args.GetIsolate(), "Weakref instance expected");
return;
}
#define WEAKREF_FIRST_ARG \
if (!isWeakRef(info[0])) { \
return Nan::ThrowTypeError("Weakref instance expected"); \
} \
Local<Object> proxy = info[0].As<Object>();
Local<Object> proxy = args[0]->ToObject();
if (IsDead(proxy)) return;
/**
* `get(weakref)` JS function.
*/
Local<Object> obj = Unwrap(proxy);
args.GetReturnValue().Set(obj);
NAN_METHOD(Get) {
WEAKREF_FIRST_ARG
if (!IsDead(proxy))
info.GetReturnValue().Set(Unwrap(proxy));
}
void IsNearDeath(const FunctionCallbackInfo<Value>& args) {
HandleScope scope(args.GetIsolate());
/**
* `isNearDeath(weakref)` JS function.
*/
if (!isWeakRef(args[0])) {
ThrowTypeError(args.GetIsolate(), "Weakref instance expected");
return;
}
NAN_METHOD(IsNearDeath) {
WEAKREF_FIRST_ARG
Local<Object> proxy = args[0]->ToObject();
proxy_container *cont = static_cast<proxy_container*>(
proxy->GetAlignedPointerFromInternalField(0));
proxy_container *cont = reinterpret_cast<proxy_container*>(
Nan::GetInternalFieldPointer(proxy, 0)
);
assert(cont != NULL);
args.GetReturnValue().Set(cont->target.IsNearDeath());
}
void IsDead(const FunctionCallbackInfo<Value>& args) {
HandleScope scope(args.GetIsolate());
Local<Boolean> rtn = Nan::New<Boolean>(cont->target.IsNearDeath());
if (!isWeakRef(args[0])) {
ThrowTypeError(args.GetIsolate(), "Weakref instance expected");
return;
}
Local<Object> proxy = args[0]->ToObject();
args.GetReturnValue().Set(IsDead(proxy));
info.GetReturnValue().Set(rtn);
}
/**
* `isDead(weakref)` JS function.
*/
void AddCallback(const FunctionCallbackInfo<Value>& args) {
HandleScope scope(args.GetIsolate());
NAN_METHOD(IsDead) {
WEAKREF_FIRST_ARG
info.GetReturnValue().Set(IsDead(proxy));
}
if (!isWeakRef(args[0])) {
ThrowTypeError(args.GetIsolate(), "Weakref instance expected");
return;
}
/**
* `_getEmitter(weakref)` JS function.
*/
Local<Object> proxy = args[0]->ToObject();
AddCallback(args.GetIsolate(), proxy, Local<Function>::Cast(args[1]));
NAN_METHOD(GetEmitter) {
WEAKREF_FIRST_ARG
info.GetReturnValue().Set(GetEmitter(proxy));
}
void Callbacks(const FunctionCallbackInfo<Value>& args) {
HandleScope scope(args.GetIsolate());
if (!isWeakRef(args[0])) {
ThrowTypeError(args.GetIsolate(), "Weakref instance expected");
return;
}
/**
* Sets the global weak callback function.
*/
Local<Object> proxy = args[0]->ToObject();
args.GetReturnValue().Set(GetCallbacks(proxy));
NAN_METHOD(SetCallback) {
Local<Function> callbackHandle = info[0].As<Function>();
globalCallback = new Nan::Callback(callbackHandle);
}
/**
* Init function.
*/
void Initialize(Local<Object> target) {
HandleScope scope(target->CreationContext()->GetIsolate());
Local<ObjectTemplate> tmpl = ObjectTemplate::New();
tmpl->SetNamedPropertyHandler(WeakNamedPropertyGetter,
WeakNamedPropertySetter,
WeakNamedPropertyQuery,
WeakNamedPropertyDeleter,
WeakPropertyEnumerator);
tmpl->SetIndexedPropertyHandler(WeakIndexedPropertyGetter,
WeakIndexedPropertySetter,
WeakIndexedPropertyQuery,
WeakIndexedPropertyDeleter,
WeakPropertyEnumerator);
tmpl->SetInternalFieldCount(1);
proxyClass.Reset(Isolate::GetCurrent(), tmpl);
NODE_SET_METHOD(target, "get", Get);
NODE_SET_METHOD(target, "create", Create);
NODE_SET_METHOD(target, "isWeakRef", IsWeakRef);
NODE_SET_METHOD(target, "isNearDeath", IsNearDeath);
NODE_SET_METHOD(target, "isDead", IsDead);
NODE_SET_METHOD(target, "callbacks", Callbacks);
NODE_SET_METHOD(target, "addCallback", AddCallback);
NAN_MODULE_INIT(Initialize) {
Nan::HandleScope scope;
Local<ObjectTemplate> p = Nan::New<ObjectTemplate>();
proxyClass.Reset(p);
Nan::SetNamedPropertyHandler(p,
WeakNamedPropertyGetter,
WeakNamedPropertySetter,
WeakNamedPropertyQuery,
WeakNamedPropertyDeleter,
WeakPropertyEnumerator);
Nan::SetIndexedPropertyHandler(p,
WeakIndexedPropertyGetter,
WeakIndexedPropertySetter,
WeakIndexedPropertyQuery,
WeakIndexedPropertyDeleter,
WeakPropertyEnumerator);
p->SetInternalFieldCount(1);
Nan::SetMethod(target, "get", Get);
Nan::SetMethod(target, "isWeakRef", IsWeakRef);
Nan::SetMethod(target, "isNearDeath", IsNearDeath);
Nan::SetMethod(target, "isDead", IsDead);
Nan::SetMethod(target, "_create", Create);
Nan::SetMethod(target, "_getEmitter", GetEmitter);
Nan::SetMethod(target, "_setCallback", SetCallback);
}
} // anonymous namespace
NODE_MODULE(weakref, Initialize);
NODE_MODULE(weakref, Initialize)

Loading…
Cancel
Save