[Pkg-javascript-commits] [node-amdefine] 01/02: Imported Upstream version 0.1.0

Leo Iannacone l3on-guest at moszumanska.debian.org
Wed Apr 30 09:49:34 UTC 2014


This is an automated email from the git hooks/post-receive script.

l3on-guest pushed a commit to branch master
in repository node-amdefine.

commit 51527c519bf2577729558b1a3f306e303bc75c04
Author: Leo Iannacone <l3on at ubuntu.com>
Date:   Sun Apr 27 15:48:08 2014 +0200

    Imported Upstream version 0.1.0
---
 .npmignore                                       |    2 +
 LICENSE                                          |   58 +
 README.md                                        |  169 +
 amdefine.js                                      |  299 ++
 intercept.js                                     |   36 +
 package.json                                     |   25 +
 tests/all-intercept.js                           |   33 +
 tests/all.js                                     |   39 +
 tests/basic-intercept/a.js                       |    7 +
 tests/basic-intercept/b.js                       |    3 +
 tests/basic-intercept/basic-tests.js             |   16 +
 tests/basic-intercept/sub/c.js                   |   10 +
 tests/basic-intercept/sub/nested/d.js            |   10 +
 tests/basic-intercept/sub/nested/e.js            |    4 +
 tests/basic/a.js                                 |    9 +
 tests/basic/b.js                                 |    5 +
 tests/basic/basic-tests.js                       |   16 +
 tests/basic/sub/c.js                             |   12 +
 tests/basic/sub/nested/d.js                      |   12 +
 tests/basic/sub/nested/e.js                      |    6 +
 tests/doh/LICENSE                                |  195 +
 tests/doh/README                                 |   12 +
 tests/doh/_browserRunner.js                      |  855 ++++
 tests/doh/_nodeRunner.js                         |   20 +
 tests/doh/_rhinoRunner.js                        |   17 +
 tests/doh/runner.html                            |  316 ++
 tests/doh/runner.js                              | 1499 +++++++
 tests/doh/runner.sh                              |    3 +
 tests/doh/small_logo.png                         |  Bin 0 -> 1893 bytes
 tests/named/lib.js                               |   46 +
 tests/named/named-tests.js                       |   16 +
 tests/named/other.js                             |    9 +
 tests/node_modules/amdefine.js                   |  299 ++
 tests/plugins/coffeescript/coffeescript-tests.js |   14 +
 tests/plugins/coffeescript/controller.coffee     |    6 +
 tests/plugins/coffeescript/cs.js                 | 4517 ++++++++++++++++++++++
 tests/plugins/coffeescript/csmain.coffee         |   13 +
 tests/plugins/coffeescript/main.js               |    6 +
 tests/plugins/coffeescript/views/regular.js      |    6 +
 tests/plugins/coffeescript/views/view.coffee     |    6 +
 tests/plugins/relative/multicall.js              |    0
 tests/plugins/relative/relative-tests.js         |   20 +
 tests/plugins/relative/sub/another/leaf.js       |    8 +
 tests/plugins/relative/sub/branch.js             |   14 +
 tests/plugins/relative/sub/templates/one.txt     |    1 +
 tests/plugins/relative/sub/templates/two.txt     |    3 +
 tests/plugins/relative/text.js                   |  285 ++
 tests/require/addTwo.js                          |    3 +
 tests/require/require-tests.js                   |   14 +
 tests/require/sub/dynamic.js                     |   20 +
 50 files changed, 8994 insertions(+)

diff --git a/.npmignore b/.npmignore
new file mode 100644
index 0000000..888a983
--- /dev/null
+++ b/.npmignore
@@ -0,0 +1,2 @@
+tests/
+.npmignore
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000..f33d665
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,58 @@
+amdefine is released under two licenses: new BSD, and MIT. You may pick the
+license that best suits your development needs. The text of both licenses are
+provided below.
+
+
+The "New" BSD License:
+----------------------
+
+Copyright (c) 2011, The Dojo Foundation
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are met:
+
+  * Redistributions of source code must retain the above copyright notice, this
+    list of conditions and the following disclaimer.
+  * Redistributions in binary form must reproduce the above copyright notice,
+    this list of conditions and the following disclaimer in the documentation
+    and/or other materials provided with the distribution.
+  * Neither the name of the Dojo Foundation nor the names of its contributors
+    may be used to endorse or promote products derived from this software
+    without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
+FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+
+
+MIT License
+-----------
+
+Copyright (c) 2011, The Dojo Foundation
+
+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.
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..a01a9e7
--- /dev/null
+++ b/README.md
@@ -0,0 +1,169 @@
+# amdefine
+
+A module that can be used to implement AMD's define() in Node. This allows you
+to code to the AMD API and have the module work in node programs without
+requiring those other programs to use AMD.
+
+## Usage
+
+**1)** Update your package.json to indicate amdefine as a dependency:
+
+```javascript
+    "dependencies": {
+        "amdefine": ">=0.1.0"
+    }
+```
+
+Then run `npm install` to get amdefine into your project.
+
+**2)** At the top of each module that uses define(), place this code:
+
+```javascript
+if (typeof define !== 'function') { var define = require('amdefine')(module) }
+```
+
+**Only use these snippets** when loading amdefine. If you preserve the basic structure,
+with the braces, it will be stripped out when using the [RequireJS optimizer](#optimizer).
+
+You can add spaces, line breaks and even require amdefine with a local path, but
+keep the rest of the structure to get the stripping behavior.
+
+As you may know, because `if` statements in JavaScript don't have their own scope, the var
+declaration in the above snippet is made whether the `if` expression is truthy or not. If
+RequireJS is loaded then the declaration is superfluous because `define` is already already
+declared in the same scope in RequireJS. Fortunately JavaScript handles multiple `var`
+declarations of the same variable in the same scope gracefully.
+
+If you want to deliver amdefine.js with your code rather than specifying it as a dependency
+with npm, then just download the latest release and refer to it using a relative path:
+
+[Latest Version](https://github.com/jrburke/amdefine/raw/latest/amdefine.js)
+
+### amdefine/intercept
+
+Instead of pasting the piece of text for the amdefine setup of a `define`
+variable in each module you create or cosunme, you can use `amdefine/intercept`
+instead. It will automatically insert the above snippet in each .js file loaded
+by Node.
+
+**Warning**: you should only use this if you are creating an application that
+is consuming AMD style defined()'d modules that are distributed via npm and want
+to run that code in Node.
+
+For library code where you are not sure if it will be used by others in Node or
+in the browser, then explicitly depending on amdefine and placing the code
+snippet above is suggested path, instead of using `amdefine/intercept`. The
+intercept module affects all .js files loaded in the Node app, and it is
+inconsiderate to modify global state like that unless you are also controlling
+the top level app.
+
+#### Why distribute AMD-style nodes via npm?
+
+npm has a lot of weaknesses for front-end use (installed layout is not great,
+should have better support for the `baseUrl + moduleID + '.js' style of loading,
+single file JS installs), but some people want a JS package manager and are
+willing to live with those constraints. If that is you, but still want to author
+in AMD style modules to get dynamic require([]), better direct source usage and
+powerful loader plugin support in the browser, then this tool can help.
+
+#### amdefine/intercept usage
+
+Just require it in your top level app module (for example index.js, server.js):
+
+```javascript
+require('amdefine/intercept');
+```
+
+The module does not return a value, so no need to assign the result to a local
+variable.
+
+Then just require() code as you normally would with Node's require(). Any .js
+loaded after the intercept require will have the amdefine check injected in
+the .js source as it is loaded. It does not modify the source on disk, just
+prepends some content to the text of the module as it is loaded by Node.
+
+#### How amdefine/intercept works
+
+It overrides the `Module._extensions['.js']` in Node to automatically prepend
+the amdefine snippet above. So, it will affect any .js file loaded by your
+app.
+
+## define() usage
+
+It is best if you use the anonymous forms of define() in your module:
+
+```javascript
+define(function (require) {
+    var dependency = require('dependency');
+});
+```
+
+or
+
+```javascript
+define(['dependency'], function (dependency) {
+
+});
+```
+
+## RequireJS optimizer integration. <a name="optimizer"></name>
+
+Version 1.0.3 of the [RequireJS optimizer](http://requirejs.org/docs/optimization.html)
+will have support for stripping the `if (typeof define !== 'function')` check
+mentioned above, so you can include this snippet for code that runs in the
+browser, but avoid taking the cost of the if() statement once the code is
+optimized for deployment.
+
+## Node 0.4 Support
+
+If you want to support Node 0.4, then add `require` as the second parameter to amdefine:
+
+```javascript
+//Only if you want Node 0.4. If using 0.5 or later, use the above snippet.
+if (typeof define !== 'function') { var define = require('amdefine')(module, require) }
+```
+
+## Limitations
+
+### Synchronous vs Asynchronous
+
+amdefine creates a define() function that is callable by your code. It will
+execute and trace dependencies and call the factory function *synchronously*,
+to keep the behavior in line with Node's synchronous dependency tracing.
+
+The exception: calling AMD's callback-style require() from inside a factory
+function. The require callback is called on process.nextTick():
+
+```javascript
+define(function (require) {
+    require(['a'], function(a) {
+        //'a' is loaded synchronously, but
+        //this callback is called on process.nextTick().
+    });
+});
+```
+
+### Loader Plugins
+
+Loader plugins are supported as long as they call their load() callbacks
+synchronously. So ones that do network requests will not work. However plugins
+like [text](http://requirejs.org/docs/api.html#text) can load text files locally.
+
+The plugin API's `load.fromText()` is **not supported** in amdefine, so this means
+transpiler plugins like the [CoffeeScript loader plugin](https://github.com/jrburke/require-cs)
+will not work. This may be fixable, but it is a bit complex, and I do not have
+enough node-fu to figure it out yet. See the source for amdefine.js if you want
+to get an idea of the issues involved.
+
+## Tests
+
+To run the tests, cd to **tests** and run:
+
+```
+node all.js
+node all-intercept.js
+```
+
+## License
+
+New BSD and MIT. Check the LICENSE file for all the details.
diff --git a/amdefine.js b/amdefine.js
new file mode 100644
index 0000000..53bf5a6
--- /dev/null
+++ b/amdefine.js
@@ -0,0 +1,299 @@
+/** vim: et:ts=4:sw=4:sts=4
+ * @license amdefine 0.1.0 Copyright (c) 2011, The Dojo Foundation All Rights Reserved.
+ * Available via the MIT or new BSD license.
+ * see: http://github.com/jrburke/amdefine for details
+ */
+
+/*jslint node: true */
+/*global module, process */
+'use strict';
+
+/**
+ * Creates a define for node.
+ * @param {Object} module the "module" object that is defined by Node for the
+ * current module.
+ * @param {Function} [requireFn]. Node's require function for the current module.
+ * It only needs to be passed in Node versions before 0.5, when module.require
+ * did not exist.
+ * @returns {Function} a define function that is usable for the current node
+ * module.
+ */
+function amdefine(module, requireFn) {
+    'use strict';
+    var defineCache = {},
+        loaderCache = {},
+        alreadyCalled = false,
+        path = require('path'),
+        makeRequire, stringRequire;
+
+    /**
+     * Trims the . and .. from an array of path segments.
+     * It will keep a leading path segment if a .. will become
+     * the first path segment, to help with module name lookups,
+     * which act like paths, but can be remapped. But the end result,
+     * all paths that use this function should look normalized.
+     * NOTE: this method MODIFIES the input array.
+     * @param {Array} ary the array of path segments.
+     */
+    function trimDots(ary) {
+        var i, part;
+        for (i = 0; ary[i]; i+= 1) {
+            part = ary[i];
+            if (part === '.') {
+                ary.splice(i, 1);
+                i -= 1;
+            } else if (part === '..') {
+                if (i === 1 && (ary[2] === '..' || ary[0] === '..')) {
+                    //End of the line. Keep at least one non-dot
+                    //path segment at the front so it can be mapped
+                    //correctly to disk. Otherwise, there is likely
+                    //no path mapping for a path starting with '..'.
+                    //This can still fail, but catches the most reasonable
+                    //uses of ..
+                    break;
+                } else if (i > 0) {
+                    ary.splice(i - 1, 2);
+                    i -= 2;
+                }
+            }
+        }
+    }
+
+    function normalize(name, baseName) {
+        var baseParts;
+
+        //Adjust any relative paths.
+        if (name && name.charAt(0) === '.') {
+            //If have a base name, try to normalize against it,
+            //otherwise, assume it is a top-level require that will
+            //be relative to baseUrl in the end.
+            if (baseName) {
+                baseParts = baseName.split('/');
+                baseParts = baseParts.slice(0, baseParts.length - 1);
+                baseParts = baseParts.concat(name.split('/'));
+                trimDots(baseParts);
+                name = baseParts.join('/');
+            }
+        }
+
+        return name;
+    }
+
+    /**
+     * Create the normalize() function passed to a loader plugin's
+     * normalize method.
+     */
+    function makeNormalize(relName) {
+        return function (name) {
+            return normalize(name, relName);
+        };
+    }
+
+    function makeLoad(id) {
+        function load(value) {
+            loaderCache[id] = value;
+        }
+
+        load.fromText = function (id, text) {
+            //This one is difficult because the text can/probably uses
+            //define, and any relative paths and requires should be relative
+            //to that id was it would be found on disk. But this would require
+            //bootstrapping a module/require fairly deeply from node core.
+            //Not sure how best to go about that yet.
+            throw new Error('amdefine does not implement load.fromText');
+        };
+
+        return load;
+    }
+
+    makeRequire = function (systemRequire, exports, module, relId) {
+        function amdRequire(deps, callback) {
+            if (typeof deps === 'string') {
+                //Synchronous, single module require('')
+                return stringRequire(systemRequire, exports, module, deps, relId);
+            } else {
+                //Array of dependencies with a callback.
+
+                //Convert the dependencies to modules.
+                deps = deps.map(function (depName) {
+                    return stringRequire(systemRequire, exports, module, depName, relId);
+                });
+
+                //Wait for next tick to call back the require call.
+                process.nextTick(function () {
+                    callback.apply(null, deps);
+                });
+            }
+        }
+
+        amdRequire.toUrl = function (filePath) {
+            if (filePath.indexOf('.') === 0) {
+                return normalize(filePath, path.dirname(module.filename));
+            } else {
+                return filePath;
+            }
+        };
+
+        return amdRequire;
+    };
+
+    //Favor explicit value, passed in if the module wants to support Node 0.4.
+    requireFn = requireFn || function req() {
+        return module.require.apply(module, arguments);
+    };
+
+    function runFactory(id, deps, factory) {
+        var r, e, m, result;
+
+        if (id) {
+            e = loaderCache[id] = {};
+            m = {
+                id: id,
+                uri: __filename,
+                exports: e
+            };
+            r = makeRequire(requireFn, e, m, id);
+        } else {
+            //Only support one define call per file
+            if (alreadyCalled) {
+                throw new Error('amdefine with no module ID cannot be called more than once per file.');
+            }
+            alreadyCalled = true;
+
+            //Use the real variables from node
+            //Use module.exports for exports, since
+            //the exports in here is amdefine exports.
+            e = module.exports;
+            m = module;
+            r = makeRequire(requireFn, e, m, module.id);
+        }
+
+        //If there are dependencies, they are strings, so need
+        //to convert them to dependency values.
+        if (deps) {
+            deps = deps.map(function (depName) {
+                return r(depName);
+            });
+        }
+
+        //Call the factory with the right dependencies.
+        if (typeof factory === 'function') {
+            result = factory.apply(m.exports, deps);
+        } else {
+            result = factory;
+        }
+
+        if (result !== undefined) {
+            m.exports = result;
+            if (id) {
+                loaderCache[id] = m.exports;
+            }
+        }
+    }
+
+    stringRequire = function (systemRequire, exports, module, id, relId) {
+        //Split the ID by a ! so that
+        var index = id.indexOf('!'),
+            originalId = id,
+            prefix, plugin;
+
+        if (index === -1) {
+            id = normalize(id, relId);
+
+            //Straight module lookup. If it is one of the special dependencies,
+            //deal with it, otherwise, delegate to node.
+            if (id === 'require') {
+                return makeRequire(systemRequire, exports, module, relId);
+            } else if (id === 'exports') {
+                return exports;
+            } else if (id === 'module') {
+                return module;
+            } else if (loaderCache.hasOwnProperty(id)) {
+                return loaderCache[id];
+            } else if (defineCache[id]) {
+                runFactory.apply(null, defineCache[id]);
+                return loaderCache[id];
+            } else {
+                if(systemRequire) {
+                    return systemRequire(originalId);
+                } else {
+                    throw new Error('No module with ID: ' + id);
+                }
+            }
+        } else {
+            //There is a plugin in play.
+            prefix = id.substring(0, index);
+            id = id.substring(index + 1, id.length);
+
+            plugin = stringRequire(systemRequire, exports, module, prefix, relId);
+
+            if (plugin.normalize) {
+                id = plugin.normalize(id, makeNormalize(relId));
+            } else {
+                //Normalize the ID normally.
+                id = normalize(id, relId);
+            }
+
+            if (loaderCache[id]) {
+                return loaderCache[id];
+            } else {
+                plugin.load(id, makeRequire(systemRequire, exports, module, relId), makeLoad(id), {});
+
+                return loaderCache[id];
+            }
+        }
+    };
+
+    //Create a define function specific to the module asking for amdefine.
+    function define(id, deps, factory) {
+        if (Array.isArray(id)) {
+            factory = deps;
+            deps = id;
+            id = undefined;
+        } else if (typeof id !== 'string') {
+            factory = id;
+            id = deps = undefined;
+        }
+
+        if (deps && !Array.isArray(deps)) {
+            factory = deps;
+            deps = undefined;
+        }
+
+        if (!deps) {
+            deps = ['require', 'exports', 'module'];
+        }
+
+        //Set up properties for this module. If an ID, then use
+        //internal cache. If no ID, then use the external variables
+        //for this node module.
+        if (id) {
+            //Put the module in deep freeze until there is a
+            //require call for it.
+            defineCache[id] = [id, deps, factory];
+        } else {
+            runFactory(id, deps, factory);
+        }
+    }
+
+    //define.require, which has access to all the values in the
+    //cache. Useful for AMD modules that all have IDs in the file,
+    //but need to finally export a value to node based on one of those
+    //IDs.
+    define.require = function (id) {
+        if (loaderCache[id]) {
+            return loaderCache[id];
+        }
+
+        if (defineCache[id]) {
+            runFactory.apply(null, defineCache[id]);
+            return loaderCache[id];
+        }
+    };
+
+    define.amd = {};
+
+    return define;
+}
+
+module.exports = amdefine;
diff --git a/intercept.js b/intercept.js
new file mode 100644
index 0000000..771a983
--- /dev/null
+++ b/intercept.js
@@ -0,0 +1,36 @@
+/*jshint node: true */
+var inserted,
+    Module = require('module'),
+    fs = require('fs'),
+    existingExtFn = Module._extensions['.js'],
+    amdefineRegExp = /amdefine\.js/;
+
+inserted  = "if (typeof define !== 'function') {var define = require('amdefine')(module)}";
+
+//From the node/lib/module.js source:
+function stripBOM(content) {
+    // Remove byte order marker. This catches EF BB BF (the UTF-8 BOM)
+    // because the buffer-to-string conversion in `fs.readFileSync()`
+    // translates it to FEFF, the UTF-16 BOM.
+    if (content.charCodeAt(0) === 0xFEFF) {
+        content = content.slice(1);
+    }
+    return content;
+}
+
+//Also adapted from the node/lib/module.js source:
+function intercept(module, filename) {
+    var content = stripBOM(fs.readFileSync(filename, 'utf8'));
+
+    if (!amdefineRegExp.test(module.id)) {
+        content = inserted + content;
+    }
+
+    module._compile(content, filename);
+}
+
+intercept._id = 'amdefine/intercept';
+
+if (!existingExtFn._id || existingExtFn._id !== intercept._id) {
+    Module._extensions['.js'] = intercept;
+}
diff --git a/package.json b/package.json
new file mode 100644
index 0000000..51cdfa6
--- /dev/null
+++ b/package.json
@@ -0,0 +1,25 @@
+{
+    "name": "amdefine",
+    "description": "Provide AMD's define() API for declaring modules in the AMD format",
+    "version": "0.1.0",
+    "homepage": "http://github.com/jrburke/amdefine",
+    "author": "James Burke <jrburke at gmail.com> (http://github.com/jrburke)",
+    "licenses": [
+        {
+            "type": "BSD",
+            "url": "https://github.com/jrburke/amdefine/blob/master/LICENSE"
+        },
+        {
+            "type": "MIT",
+            "url": "https://github.com/jrburke/amdefine/blob/master/LICENSE"
+        }
+    ],
+    "repository": {
+        "type": "git",
+        "url": "https://github.com/jrburke/amdefine.git"
+    },
+    "main": "./amdefine.js",
+    "engines": {
+        "node": ">=0.4.2"
+    }
+}
diff --git a/tests/all-intercept.js b/tests/all-intercept.js
new file mode 100644
index 0000000..b6a49d8
--- /dev/null
+++ b/tests/all-intercept.js
@@ -0,0 +1,33 @@
+/*jslint strict: false, evil: true */
+/*global Packages: false, process: false, require: true, define: true, doh: false */
+
+//A hack to doh to avoid dojo setup stuff in doh/runner.js
+var skipDohSetup = true,
+    fs, vm, load, env;
+
+require('../intercept');
+
+(function () {
+    if (typeof Packages !== 'undefined') {
+        env = 'rhino';
+    } else if (typeof process !== 'undefined') {
+        env = 'node';
+
+        fs = require('fs');
+        vm = require('vm');
+
+        load = function (path) {
+            return vm.runInThisContext(fs.readFileSync(path, 'utf8'), path);
+        };
+    }
+
+}());
+
+//Load the tests.
+load("doh/runner.js");
+load('doh/_' + env + 'Runner.js');
+
+require("./basic-intercept/basic-tests");
+
+//Print out the final report
+doh.run();
diff --git a/tests/all.js b/tests/all.js
new file mode 100644
index 0000000..05d4910
--- /dev/null
+++ b/tests/all.js
@@ -0,0 +1,39 @@
+/*jslint strict: false, evil: true */
+/*global Packages: false, process: false, require: true, define: true, doh: false */
+
+//A hack to doh to avoid dojo setup stuff in doh/runner.js
+var skipDohSetup = true,
+    fs, vm, load, env;
+
+(function () {
+    if (typeof Packages !== 'undefined') {
+        env = 'rhino';
+    } else if (typeof process !== 'undefined') {
+        env = 'node';
+
+        fs = require('fs');
+        vm = require('vm');
+
+        load = function (path) {
+            return vm.runInThisContext(fs.readFileSync(path, 'utf8'), path);
+        };
+    }
+
+}());
+
+//Load the tests.
+load("doh/runner.js");
+load('doh/_' + env + 'Runner.js');
+
+require("./basic/basic-tests");
+require("./named/named-tests");
+
+require("./plugins/relative/relative-tests");
+
+//Cannot handle load.fromText for plugins yet, so commented out.
+//require("./plugins/coffeescript/coffeescript-tests");
+
+require("./require/require-tests");
+
+//Print out the final report
+doh.run();
diff --git a/tests/basic-intercept/a.js b/tests/basic-intercept/a.js
new file mode 100644
index 0000000..8ba1540
--- /dev/null
+++ b/tests/basic-intercept/a.js
@@ -0,0 +1,7 @@
+define(['./b', './sub/nested/d'], function (b, d) {
+    return {
+        name: 'a',
+        b: b,
+        d: d
+    };
+});
diff --git a/tests/basic-intercept/b.js b/tests/basic-intercept/b.js
new file mode 100644
index 0000000..7688214
--- /dev/null
+++ b/tests/basic-intercept/b.js
@@ -0,0 +1,3 @@
+define({
+    name: 'b'
+});
\ No newline at end of file
diff --git a/tests/basic-intercept/basic-tests.js b/tests/basic-intercept/basic-tests.js
new file mode 100644
index 0000000..a1ed4de
--- /dev/null
+++ b/tests/basic-intercept/basic-tests.js
@@ -0,0 +1,16 @@
+doh.register(
+    "basicIntercept",
+    [
+        function basicIntercept(t){
+            var a = require('./a');
+
+            t.is('a', a.name);
+            t.is('b', a.b.name);
+            t.is('d', a.d.name);
+            t.is('c', a.d.cName);
+            t.is('e', a.d.e.name);
+        }
+    ]
+);
+
+doh.run();
diff --git a/tests/basic-intercept/sub/c.js b/tests/basic-intercept/sub/c.js
new file mode 100644
index 0000000..04677fe
--- /dev/null
+++ b/tests/basic-intercept/sub/c.js
@@ -0,0 +1,10 @@
+define(function (require, exports, module) {
+
+    //A fake out, modify the exports, but still prefer the
+    //return value as the module value.
+    exports.name = 'badc';
+
+    return {
+        name: 'c'
+    };
+});
diff --git a/tests/basic-intercept/sub/nested/d.js b/tests/basic-intercept/sub/nested/d.js
new file mode 100644
index 0000000..5432f68
--- /dev/null
+++ b/tests/basic-intercept/sub/nested/d.js
@@ -0,0 +1,10 @@
+define(function (require, exports, module) {
+    var c = require('../c'),
+        e = require('./e');
+
+    return {
+        name: 'd',
+        e: e,
+        cName: c.name
+    };
+});
diff --git a/tests/basic-intercept/sub/nested/e.js b/tests/basic-intercept/sub/nested/e.js
new file mode 100644
index 0000000..fe6995e
--- /dev/null
+++ b/tests/basic-intercept/sub/nested/e.js
@@ -0,0 +1,4 @@
+//Just testing a plain exports case.
+define(function (require, exports) {
+    exports.name = 'e';
+});
diff --git a/tests/basic/a.js b/tests/basic/a.js
new file mode 100644
index 0000000..d471cea
--- /dev/null
+++ b/tests/basic/a.js
@@ -0,0 +1,9 @@
+if (typeof define !== 'function') { var define = require('../../amdefine')(module) }
+
+define(['./b', './sub/nested/d'], function (b, d) {
+    return {
+        name: 'a',
+        b: b,
+        d: d
+    };
+});
diff --git a/tests/basic/b.js b/tests/basic/b.js
new file mode 100644
index 0000000..959569c
--- /dev/null
+++ b/tests/basic/b.js
@@ -0,0 +1,5 @@
+if (typeof define !== 'function') { var define = (require('../../amdefine'))(module); }
+
+define({
+    name: 'b'
+});
\ No newline at end of file
diff --git a/tests/basic/basic-tests.js b/tests/basic/basic-tests.js
new file mode 100644
index 0000000..605ab52
--- /dev/null
+++ b/tests/basic/basic-tests.js
@@ -0,0 +1,16 @@
+doh.register(
+    "simple",
+    [
+        function simple(t){
+            var a = require('./a');
+
+            t.is('a', a.name);
+            t.is('b', a.b.name);
+            t.is('d', a.d.name);
+            t.is('c', a.d.cName);
+            t.is('e', a.d.e.name);
+        }
+    ]
+);
+
+doh.run();
diff --git a/tests/basic/sub/c.js b/tests/basic/sub/c.js
new file mode 100644
index 0000000..5dfe33a
--- /dev/null
+++ b/tests/basic/sub/c.js
@@ -0,0 +1,12 @@
+if (typeof define !== 'function') { var define = (require('../../../amdefine'))(module); }
+
+define(function (require, exports, module) {
+
+    //A fake out, modify the exports, but still prefer the
+    //return value as the module value.
+    exports.name = 'badc';
+
+    return {
+        name: 'c'
+    };
+});
diff --git a/tests/basic/sub/nested/d.js b/tests/basic/sub/nested/d.js
new file mode 100644
index 0000000..54e5329
--- /dev/null
+++ b/tests/basic/sub/nested/d.js
@@ -0,0 +1,12 @@
+if (typeof define !== 'function') { var define = (require('../../../../amdefine'))(module); }
+
+define(function (require, exports, module) {
+    var c = require('../c'),
+        e = require('./e');
+
+    return {
+        name: 'd',
+        e: e,
+        cName: c.name
+    };
+});
diff --git a/tests/basic/sub/nested/e.js b/tests/basic/sub/nested/e.js
new file mode 100644
index 0000000..a297523
--- /dev/null
+++ b/tests/basic/sub/nested/e.js
@@ -0,0 +1,6 @@
+if (typeof define !== 'function') { var define = (require('../../../../amdefine'))(module); }
+
+//Just testing a plain exports case.
+define(function (require, exports) {
+    exports.name = 'e';
+});
diff --git a/tests/doh/LICENSE b/tests/doh/LICENSE
new file mode 100644
index 0000000..ad1676a
--- /dev/null
+++ b/tests/doh/LICENSE
@@ -0,0 +1,195 @@
+Dojo is available under *either* the terms of the modified BSD license *or* the
+Academic Free License version 2.1. As a recipient of Dojo, you may choose which
+license to receive this code under (except as noted in per-module LICENSE
+files). Some modules may not be the copyright of the Dojo Foundation. These
+modules contain explicit declarations of copyright in both the LICENSE files in
+the directories in which they reside and in the code itself. No external
+contributions are allowed under licenses which are fundamentally incompatible
+with the AFL or BSD licenses that Dojo is distributed under.
+
+The text of the AFL and BSD licenses is reproduced below. 
+
+-------------------------------------------------------------------------------
+The "New" BSD License:
+**********************
+
+Copyright (c) 2005-2009, The Dojo Foundation
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are met:
+
+  * Redistributions of source code must retain the above copyright notice, this
+    list of conditions and the following disclaimer.
+  * Redistributions in binary form must reproduce the above copyright notice,
+    this list of conditions and the following disclaimer in the documentation
+    and/or other materials provided with the distribution.
+  * Neither the name of the Dojo Foundation nor the names of its contributors
+    may be used to endorse or promote products derived from this software
+    without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
+FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+-------------------------------------------------------------------------------
+The Academic Free License, v. 2.1:
+**********************************
+
+This Academic Free License (the "License") applies to any original work of
+authorship (the "Original Work") whose owner (the "Licensor") has placed the
+following notice immediately following the copyright notice for the Original
+Work:
+
+Licensed under the Academic Free License version 2.1
+
+1) Grant of Copyright License. Licensor hereby grants You a world-wide,
+royalty-free, non-exclusive, perpetual, sublicenseable license to do the
+following:
+
+a) to reproduce the Original Work in copies;
+
+b) to prepare derivative works ("Derivative Works") based upon the Original
+Work;
+
+c) to distribute copies of the Original Work and Derivative Works to the
+public;
+
+d) to perform the Original Work publicly; and
+
+e) to display the Original Work publicly.
+
+2) Grant of Patent License. Licensor hereby grants You a world-wide,
+royalty-free, non-exclusive, perpetual, sublicenseable license, under patent
+claims owned or controlled by the Licensor that are embodied in the Original
+Work as furnished by the Licensor, to make, use, sell and offer for sale the
+Original Work and Derivative Works.
+
+3) Grant of Source Code License. The term "Source Code" means the preferred
+form of the Original Work for making modifications to it and all available
+documentation describing how to modify the Original Work. Licensor hereby
+agrees to provide a machine-readable copy of the Source Code of the Original
+Work along with each copy of the Original Work that Licensor distributes.
+Licensor reserves the right to satisfy this obligation by placing a
+machine-readable copy of the Source Code in an information repository
+reasonably calculated to permit inexpensive and convenient access by You for as
+long as Licensor continues to distribute the Original Work, and by publishing
+the address of that information repository in a notice immediately following
+the copyright notice that applies to the Original Work.
+
+4) Exclusions From License Grant. Neither the names of Licensor, nor the names
+of any contributors to the Original Work, nor any of their trademarks or
+service marks, may be used to endorse or promote products derived from this
+Original Work without express prior written permission of the Licensor. Nothing
+in this License shall be deemed to grant any rights to trademarks, copyrights,
+patents, trade secrets or any other intellectual property of Licensor except as
+expressly stated herein. No patent license is granted to make, use, sell or
+offer to sell embodiments of any patent claims other than the licensed claims
+defined in Section 2. No right is granted to the trademarks of Licensor even if
+such marks are included in the Original Work. Nothing in this License shall be
+interpreted to prohibit Licensor from licensing under different terms from this
+License any Original Work that Licensor otherwise would have a right to
+license.
+
+5) This section intentionally omitted.
+
+6) Attribution Rights. You must retain, in the Source Code of any Derivative
+Works that You create, all copyright, patent or trademark notices from the
+Source Code of the Original Work, as well as any notices of licensing and any
+descriptive text identified therein as an "Attribution Notice." You must cause
+the Source Code for any Derivative Works that You create to carry a prominent
+Attribution Notice reasonably calculated to inform recipients that You have
+modified the Original Work.
+
+7) Warranty of Provenance and Disclaimer of Warranty. Licensor warrants that
+the copyright in and to the Original Work and the patent rights granted herein
+by Licensor are owned by the Licensor or are sublicensed to You under the terms
+of this License with the permission of the contributor(s) of those copyrights
+and patent rights. Except as expressly stated in the immediately proceeding
+sentence, the Original Work is provided under this License on an "AS IS" BASIS
+and WITHOUT WARRANTY, either express or implied, including, without limitation,
+the warranties of NON-INFRINGEMENT, MERCHANTABILITY or FITNESS FOR A PARTICULAR
+PURPOSE. THE ENTIRE RISK AS TO THE QUALITY OF THE ORIGINAL WORK IS WITH YOU.
+This DISCLAIMER OF WARRANTY constitutes an essential part of this License. No
+license to Original Work is granted hereunder except under this disclaimer.
+
+8) Limitation of Liability. Under no circumstances and under no legal theory,
+whether in tort (including negligence), contract, or otherwise, shall the
+Licensor be liable to any person for any direct, indirect, special, incidental,
+or consequential damages of any character arising as a result of this License
+or the use of the Original Work including, without limitation, damages for loss
+of goodwill, work stoppage, computer failure or malfunction, or any and all
+other commercial damages or losses. This limitation of liability shall not
+apply to liability for death or personal injury resulting from Licensor's
+negligence to the extent applicable law prohibits such limitation. Some
+jurisdictions do not allow the exclusion or limitation of incidental or
+consequential damages, so this exclusion and limitation may not apply to You.
+
+9) Acceptance and Termination. If You distribute copies of the Original Work or
+a Derivative Work, You must make a reasonable effort under the circumstances to
+obtain the express assent of recipients to the terms of this License. Nothing
+else but this License (or another written agreement between Licensor and You)
+grants You permission to create Derivative Works based upon the Original Work
+or to exercise any of the rights granted in Section 1 herein, and any attempt
+to do so except under the terms of this License (or another written agreement
+between Licensor and You) is expressly prohibited by U.S. copyright law, the
+equivalent laws of other countries, and by international treaty. Therefore, by
+exercising any of the rights granted to You in Section 1 herein, You indicate
+Your acceptance of this License and all of its terms and conditions.
+
+10) Termination for Patent Action. This License shall terminate automatically
+and You may no longer exercise any of the rights granted to You by this License
+as of the date You commence an action, including a cross-claim or counterclaim,
+against Licensor or any licensee alleging that the Original Work infringes a
+patent. This termination provision shall not apply for an action alleging
+patent infringement by combinations of the Original Work with other software or
+hardware.
+
+11) Jurisdiction, Venue and Governing Law. Any action or suit relating to this
+License may be brought only in the courts of a jurisdiction wherein the
+Licensor resides or in which Licensor conducts its primary business, and under
+the laws of that jurisdiction excluding its conflict-of-law provisions. The
+application of the United Nations Convention on Contracts for the International
+Sale of Goods is expressly excluded. Any use of the Original Work outside the
+scope of this License or after its termination shall be subject to the
+requirements and penalties of the U.S. Copyright Act, 17 U.S.C. § 101 et
+seq., the equivalent laws of other countries, and international treaty. This
+section shall survive the termination of this License.
+
+12) Attorneys Fees. In any action to enforce the terms of this License or
+seeking damages relating thereto, the prevailing party shall be entitled to
+recover its costs and expenses, including, without limitation, reasonable
+attorneys' fees and costs incurred in connection with such action, including
+any appeal of such action. This section shall survive the termination of this
+License.
+
+13) Miscellaneous. This License represents the complete agreement concerning
+the subject matter hereof. If any provision of this License is held to be
+unenforceable, such provision shall be reformed only to the extent necessary to
+make it enforceable.
+
+14) Definition of "You" in This License. "You" throughout this License, whether
+in upper or lower case, means an individual or a legal entity exercising rights
+under, and complying with all of the terms of, this License. For legal
+entities, "You" includes any entity that controls, is controlled by, or is
+under common control with you. For purposes of this definition, "control" means
+(i) the power, direct or indirect, to cause the direction or management of such
+entity, whether by contract or otherwise, or (ii) ownership of fifty percent
+(50%) or more of the outstanding shares, or (iii) beneficial ownership of such
+entity.
+
+15) Right to Use. You may use the Original Work in all ways not otherwise
+restricted or conditioned by this License or by law, and Licensor promises not
+to interfere with or be responsible for such uses by You.
+
+This license is Copyright (C) 2003-2004 Lawrence E. Rosen. All rights reserved.
+Permission is hereby granted to copy and distribute this license without
+modification. This license may not be modified without the express written
+permission of its copyright owner.
diff --git a/tests/doh/README b/tests/doh/README
new file mode 100644
index 0000000..2f1d91a
--- /dev/null
+++ b/tests/doh/README
@@ -0,0 +1,12 @@
+DOH may be run standalone by issuing a command like the following:
+
+java -jar ../shrinksafe/js.jar runner.js testModule=tests.colors
+
+where the testModule argument is optional and shrinksafe/js.jar is just a
+convenient copy of the Rhino JavaScript engine -- the custom patch is not
+required.
+
+Optional arguments include:
+ * dojoUrl - specifies the location of dojo.js
+ * testUrl - specifies a Javascript file to load with initialization code
+ * testModule - specifies a test module in the dojo package namespace
diff --git a/tests/doh/_browserRunner.js b/tests/doh/_browserRunner.js
new file mode 100644
index 0000000..408b29a
--- /dev/null
+++ b/tests/doh/_browserRunner.js
@@ -0,0 +1,855 @@
+if(window["dojo"]){
+	dojo.provide("doh._browserRunner");
+}
+
+// FIXME: need to add prompting for monkey-do testing
+
+(function(){
+
+	doh.setTimeout = function (fn, time) {
+            return setTimeout(fn, time);
+        };
+
+	try{
+		var topdog = (window.parent == window) || !Boolean(window.parent.doh);
+	}catch(e){
+		//can't access window.parent.doh, then consider ourselves as topdog
+		topdog=true;
+	}
+	if(topdog){
+		// we're the top-dog window.
+
+		// borrowed from Dojo, etc.
+		var byId = function(id){
+			return document.getElementById(id);
+		};
+
+		var _addOnEvt = function(	type,		// string
+									refOrName,	// function or string
+									scope){		// object, defaults is window
+
+			if(!scope){ scope = window; }
+
+			var funcRef = refOrName;
+			if(typeof refOrName == "string"){
+				funcRef = scope[refOrName];
+			}
+			var enclosedFunc = function(){ return funcRef.apply(scope, arguments); };
+
+			if((window["dojo"])&&(type == "load")){
+				dojo.addOnLoad(enclosedFunc);
+			}else{
+				if(window["attachEvent"]){
+					window.attachEvent("on"+type, enclosedFunc);
+				}else if(window["addEventListener"]){
+					window.addEventListener(type, enclosedFunc, false);
+				}else if(document["addEventListener"]){
+					document.addEventListener(type, enclosedFunc, false);
+				}
+			}
+		};
+
+		//
+		// Over-ride or implement base runner.js-provided methods
+		//
+		var escapeXml = function(str){
+			//summary:
+			//		Adds escape sequences for special characters in XML: &<>"'
+			//		Optionally skips escapes for single quotes
+			return str.replace(/&/gm, "&").replace(/</gm, "<").replace(/>/gm, ">").replace(/"/gm, """); // string
+		};
+
+		var _logBacklog = [], _loggedMsgLen = 0;
+		var sendToLogPane = function(args, skip){
+			var msg = "";
+			for(var x=0; x<args.length; x++){
+				msg += " "+args[x];
+			}
+
+			msg = escapeXml(msg);
+
+			// workarounds for IE. Wheeee!!!
+			msg = msg.replace("\t", "    ")
+				.replace(" ", " ")
+				.replace("\n", "<br> ");
+			if(!byId("logBody")){
+				_logBacklog.push(msg);
+				return;
+			}else if(_logBacklog.length && !skip){
+				var tm;
+				while((tm=_logBacklog.shift())){
+					sendToLogPane(tm, true);
+				}
+			}
+			var logBody=byId("logBody");
+			var tn = document.createElement("div");
+			tn.innerHTML = msg;
+			//tn.id="logmsg_"+logBody.childNodes.length;
+			logBody.appendChild(tn);
+			_loggedMsgLen++;
+		}
+
+		var findTarget = function(n){
+			while(n && !n.getAttribute('_target')){
+				n=n.parentNode;
+				if(!n.getAttribute){
+					n=null;
+				}
+			}
+			return n;
+		}
+
+		doh._jumpToLog = function(e){
+			//console.log(e);
+
+			var node = findTarget(e?e.target:window.event.srcElement);
+			if(!node){
+				return;
+			}
+			var _t = Number(node.getAttribute('_target'));
+			var lb = byId("logBody");
+			if(_t>=lb.childNodes.length){
+				return;
+			}
+			var t = lb.childNodes[_t];
+			t.scrollIntoView();
+			if(window.dojo){
+				//t.parentNode.parentNode is <div class="tabBody">, only it has a explicitly set background-color,
+				//all children of it are transparent
+				var bgColor = dojo.style(t.parentNode.parentNode,'backgroundColor');
+				//node.parentNode is the tr which has background-color set explicitly
+				var hicolor = dojo.style(node.parentNode,'backgroundColor');
+				var unhilight = dojo.animateProperty({
+					node: t,
+					duration: 500,
+					properties:
+					{
+						backgroundColor: { start:hicolor, end: bgColor }
+					},
+					onEnd: function(){
+						t.style.backgroundColor="";
+					}
+				});
+				var hilight = dojo.animateProperty({
+					node: t,
+					duration: 500,
+					properties:
+					{
+						backgroundColor: { start:bgColor, end: hicolor }
+					},
+					onEnd: function(){
+						unhilight.play();
+					}
+				});
+				hilight.play();
+			}
+		};
+
+		doh._jumpToSuite = function(e){
+			var node = findTarget(e ? e.target : window.event.srcElement);
+			if(!node){
+				return;
+			}
+			var _g = node.getAttribute('_target');
+			var gn = getGroupNode(_g);
+			if(!gn){
+				return;
+			}
+			gn.scrollIntoView();
+		};
+
+		doh._init = (function(oi){
+			return function(){
+				var lb = byId("logBody");
+				if(lb){
+					// clear the console before each run
+					while(lb.firstChild){
+						lb.removeChild(lb.firstChild);
+					}
+					_loggedMsgLen = 0;
+				}
+				this._totalTime = 0;
+				this._suiteCount = 0;
+				oi.apply(doh, arguments);
+			}
+		})(doh._init);
+
+		doh._setupGroupForRun = (function(os){
+			//overload _setupGroupForRun to record which log line to jump to when a suite is clicked
+			return function(groupName){
+				var tg = doh._groups[groupName];
+				doh._curTestCount = tg.length;
+				doh._curGroupCount = 1;
+				var gn = getGroupNode(groupName);
+				if(gn){
+					//two lines will be added, scroll the second line into view
+					gn.getElementsByTagName("td")[2].setAttribute('_target',_loggedMsgLen+1);
+				}
+				os.apply(doh,arguments);
+			}
+		})(doh._setupGroupForRun);
+
+		doh._report = (function(or){
+			//overload _report to insert a tfoot
+			return function(){
+				var tb = byId("testList");
+				if(tb){
+					var tfoots=tb.getElementsByTagName('tfoot');
+					if(tfoots.length){
+						tb.removeChild(tfoots[0]);
+					}
+					var foot = tb.createTFoot();
+					var row = foot.insertRow(-1);
+					row.className = 'inProgress';
+					var cell=row.insertCell(-1);
+					cell.colSpan=2;
+					cell.innerHTML="Result";
+					cell = row.insertCell(-1);
+					cell.innerHTML=this._testCount+" tests in "+this._groupCount+" groups /<span class='failure'>"+this._errorCount+"</span> errors, <span class='failure'>"+this._failureCount+"</span> failures";
+					cell.setAttribute('_target',_loggedMsgLen+1);
+					row.insertCell(-1).innerHTML=doh._totalTime+"ms";
+				}
+
+				//This location can do the final performance rendering for the results
+				//of any performance tests.
+				var plotResults = null;
+				var standby;
+				if(doh.perfTestResults){
+					if(window.dojo){
+						//If we have dojo and here are perf tests results,
+						//well, we'll use the dojo charting functions
+						dojo.require("dojox.charting.Chart2D");
+						dojo.require("dojox.charting.DataChart");
+						dojo.require("dojox.charting.plot2d.Scatter");
+						dojo.require("dojox.charting.plot2d.Lines");
+						dojo.require("dojo.data.ItemFileReadStore");
+						plotResults = doh._dojoPlotPerfResults;
+					}else{
+						plotResults = doh._asciiPlotPerfResults;
+					}
+					try{
+						var g;
+						var pBody = byId("perfTestsBody");
+						var chartsToRender = [];
+
+						if(doh.perfTestResults){
+							doh.showPerfTestsPage();
+						}
+						for(g in doh.perfTestResults){
+							var grp = doh.perfTestResults[g];
+							var hdr = document.createElement("h1");
+							hdr.appendChild(document.createTextNode("Group: " + g));
+							pBody.appendChild(hdr);
+							var ind = document.createElement("blockquote");
+							pBody.appendChild(ind);
+							var f;
+							for(f in grp){
+								var fResults = grp[f];
+								if(!fResults){ continue; }
+								var fhdr = document.createElement("h3");
+								fhdr.appendChild(document.createTextNode("TEST: " + f));
+								fhdr.style.textDecoration = "underline";
+								ind.appendChild(fhdr);
+								var div = document.createElement("div");
+								ind.appendChild(div);
+
+								//Figure out the basic info
+								var results = "<b>TRIAL SIZE: </b>"  + fResults.trials[0].testIterations + " iterations<br>" +
+									"<b>NUMBER OF TRIALS: </b>" + fResults.trials.length + "<br>";
+
+								//Figure out the average test pass cost.
+								var i;
+								var iAvgArray = [];
+								var tAvgArray = [];
+								for(i = 0; i < fResults.trials.length; i++){
+									iAvgArray.push(fResults.trials[i].average);
+									tAvgArray.push(fResults.trials[i].executionTime);
+								}
+								results += "<b>AVERAGE TRIAL EXECUTION TIME: </b>" + doh.average(tAvgArray).toFixed(10) + "ms.<br>";
+								results += "<b>MAXIMUM TEST ITERATION TIME: </b>" + doh.max(iAvgArray).toFixed(10) + "ms.<br>";
+								results += "<b>MINIMUM TEST ITERATION TIME: </b>" + doh.min(iAvgArray).toFixed(10) + "ms.<br>";
+								results += "<b>AVERAGE TEST ITERATION TIME: </b>" + doh.average(iAvgArray).toFixed(10) + "ms.<br>";
+								results += "<b>MEDIAN TEST ITERATION TIME: </b>" + doh.median(iAvgArray).toFixed(10) + "ms.<br>";
+								results += "<b>VARIANCE TEST ITERATION TIME: </b>" + doh.variance(iAvgArray).toFixed(10) + "ms.<br>";
+								results += "<b>STANDARD DEVIATION ON TEST ITERATION TIME: </b>" + doh.standardDeviation(iAvgArray).toFixed(10) + "ms.<br>";
+
+								//Okay, attach it all in.
+								div.innerHTML = results;
+
+								div = document.createElement("div");
+								div.innerHTML = "<h3>Average Test Execution Time (in milliseconds, with median line)</h3>";
+								ind.appendChild(div);
+								div = document.createElement("div");
+								dojo.style(div, "width", "600px");
+								dojo.style(div, "height", "250px");
+								ind.appendChild(div);
+								chartsToRender.push({
+									div: div,
+									title: "Average Test Execution Time",
+									data: iAvgArray
+								});
+
+								div = document.createElement("div");
+								div.innerHTML = "<h3>Average Trial Execution Time (in milliseconds, with median line)</h3>";
+								ind.appendChild(div);
+								div = document.createElement("div");
+								dojo.style(div, "width", "600px");
+								dojo.style(div, "height", "250px");
+								ind.appendChild(div);
+								chartsToRender.push({
+									div: div,
+									title: "Average Trial Execution Time",
+									data: tAvgArray
+								});
+							}
+						}
+
+						//Lazy-render these to give the browser time and not appear locked.
+						var delayedRenders = function() {
+							if(chartsToRender.length){
+								var chartData = chartsToRender.shift();
+								plotResults(chartData.div, chartData.title, chartData.data);
+							}
+							doh.setTimeout(delayedRenders, 50);
+						};
+						doh.setTimeout(delayedRenders, 150);
+					}catch(e){
+						doh.debug(e);
+					}
+				}
+				or.apply(doh,arguments);
+			}
+		})(doh._report);
+
+		if(this["opera"] && opera.postError){
+			doh.debug = function(){
+				var msg = "";
+				for(var x=0; x<arguments.length; x++){
+					msg += " "+arguments[x];
+				}
+				sendToLogPane([msg]);
+				opera.postError("DEBUG:"+msg);
+			}
+		}else if(window["console"]){
+			doh.debug = function(){
+				var msg = "";
+				for(var x=0; x<arguments.length; x++){
+					msg += " "+arguments[x];
+				}
+				sendToLogPane([msg]);
+				console.log("DEBUG:"+msg);
+			};
+		}else{
+			doh.debug = function(){
+				sendToLogPane.call(window, arguments);
+			}
+		}
+
+		var loaded = false;
+		var groupTemplate = null;
+		var testTemplate = null;
+
+		var groupNodes = {};
+
+		var _groupTogglers = {};
+
+		var _getGroupToggler = function(group, toggle){
+			if(_groupTogglers[group]){ return _groupTogglers[group]; }
+			var rolledUp = true;
+			return (_groupTogglers[group] = function(evt, forceOpen){
+				var nodes = groupNodes[group].__items;
+				var x;
+				if(rolledUp||forceOpen){
+					rolledUp = false;
+					for(x=0; x<nodes.length; x++){
+						nodes[x].style.display = "";
+					}
+					toggle.innerHTML = "▼";
+				}else{
+					rolledUp = true;
+					for(x=0; x<nodes.length; x++){
+						nodes[x].style.display = "none";
+					}
+					toggle.innerHTML = "►";
+				}
+			});
+		};
+
+		var addGroupToList = function(group){
+			if(!byId("testList")){ return; }
+			var tb = byId("testList").tBodies[0];
+			var tg = groupTemplate.cloneNode(true);
+			var tds = tg.getElementsByTagName("td");
+			var toggle = tds[0];
+			toggle.onclick = _getGroupToggler(group, toggle);
+			var cb = tds[1].getElementsByTagName("input")[0];
+			cb.group = group;
+			cb.onclick = function(evt){
+				doh._groups[group].skip = (!this.checked);
+			}
+			tds[2].innerHTML = "<div class='testGroupName'>"+group+"</div><div style='width:0;'> </div>";
+			tds[3].innerHTML = "";
+
+			tb.appendChild(tg);
+			return tg;
+		}
+
+		var addFixtureToList = function(group, fixture){
+			if(!testTemplate){ return; }
+			var cgn = groupNodes[group];
+			if(!cgn["__items"]){ cgn.__items = []; }
+			var tn = testTemplate.cloneNode(true);
+			var tds = tn.getElementsByTagName("td");
+
+			tds[2].innerHTML = fixture.name;
+			tds[3].innerHTML = "";
+
+			var nn = (cgn.__lastFixture||cgn.__groupNode).nextSibling;
+			if(nn){
+				nn.parentNode.insertBefore(tn, nn);
+			}else{
+				cgn.__groupNode.parentNode.appendChild(tn);
+			}
+			// FIXME: need to make group display toggleable!!
+			tn.style.display = "none";
+			cgn.__items.push(tn);
+			return (cgn.__lastFixture = tn);
+		}
+
+		var getFixtureNode = function(group, fixture){
+			if(groupNodes[group]){
+				return groupNodes[group][fixture.name];
+			}
+			return null;
+		}
+
+		var getGroupNode = function(group){
+			if(groupNodes[group]){
+				return groupNodes[group].__groupNode;
+			}
+			return null;
+		}
+
+		var updateBacklog = [];
+		doh._updateTestList = function(group, fixture, unwindingBacklog){
+			if(!loaded){
+				if(group && fixture){
+					updateBacklog.push([group, fixture]);
+				}
+				return;
+			}else if(updateBacklog.length && !unwindingBacklog){
+				var tr;
+				while((tr=updateBacklog.shift())){
+					doh._updateTestList(tr[0], tr[1], true);
+				}
+			}
+			if(group && fixture){
+				if(!groupNodes[group]){
+					groupNodes[group] = {
+						"__groupNode": addGroupToList(group)
+					};
+				}
+				if(!groupNodes[group][fixture.name]){
+					groupNodes[group][fixture.name] = addFixtureToList(group, fixture)
+				}
+			}
+		}
+
+		doh._testRegistered = doh._updateTestList;
+
+		doh._groupStarted = function(group){
+			if(this._suiteCount == 0){
+				this._runedSuite = 0;
+				this._currentGlobalProgressBarWidth = 0;
+				this._suiteCount = this._testCount;
+			}
+			// console.debug("_groupStarted", group);
+			if(doh._inGroup != group){
+				doh._groupTotalTime = 0;
+				doh._runed = 0;
+				doh._inGroup = group;
+				this._runedSuite++;
+			}
+			var gn = getGroupNode(group);
+			if(gn){
+				gn.className = "inProgress";
+			}
+		}
+
+		doh._groupFinished = function(group, success){
+			// console.debug("_groupFinished", group);
+			var gn = getGroupNode(group);
+			if(gn && doh._inGroup == group){
+				doh._totalTime += doh._groupTotalTime;
+				gn.getElementsByTagName("td")[3].innerHTML = doh._groupTotalTime+"ms";
+				gn.getElementsByTagName("td")[2].lastChild.className = "";
+				doh._inGroup = null;
+				//doh._runedSuite++;
+				var failure = doh._updateGlobalProgressBar(this._runedSuite/this._groupCount,success,group);
+				gn.className = failure ? "failure" : "success";
+				//doh._runedSuite--;
+				doh._currentGlobalProgressBarWidth = parseInt(this._runedSuite/this._groupCount*10000)/100;
+				//byId("progressOuter").style.width = parseInt(this._runedSuite/this._suiteCount*100)+"%";
+			}
+			if(doh._inGroup == group){
+				this.debug("Total time for GROUP \"",group,"\" is ",doh._groupTotalTime,"ms");
+			}
+		}
+
+		doh._testStarted = function(group, fixture){
+			// console.debug("_testStarted", group, fixture.name);
+			var fn = getFixtureNode(group, fixture);
+			if(fn){
+				fn.className = "inProgress";
+			}
+		}
+
+		var _nameTimes = {};
+		var _playSound = function(name){
+			if(byId("hiddenAudio") && byId("audio") && byId("audio").checked){
+				// console.debug("playing:", name);
+				var nt = _nameTimes[name];
+				// only play sounds once every second or so
+				if((!nt)||(((new Date)-nt) > 700)){
+					_nameTimes[name] = new Date();
+					var tc = document.createElement("span");
+					byId("hiddenAudio").appendChild(tc);
+					tc.innerHTML = '<embed src="_sounds/'+name+'.wav" autostart="true" loop="false" hidden="true" width="1" height="1"></embed>';
+				}
+			}
+		}
+
+		doh._updateGlobalProgressBar = function(p,success,group){
+			var outerContainer=byId("progressOuter");
+
+			var gdiv=outerContainer.childNodes[doh._runedSuite-1];
+			if(!gdiv){
+				gdiv=document.createElement('div');
+				outerContainer.appendChild(gdiv);
+				gdiv.className='success';
+				gdiv.setAttribute('_target',group);
+			}
+			if(!success && !gdiv._failure){
+				gdiv._failure=true;
+				gdiv.className='failure';
+				if(group){
+					gdiv.setAttribute('title','failed group '+group);
+				}
+			}
+			var tp=parseInt(p*10000)/100;
+			gdiv.style.width = (tp-doh._currentGlobalProgressBarWidth)+"%";
+			return gdiv._failure;
+		}
+		doh._testFinished = function(group, fixture, success){
+			var fn = getFixtureNode(group, fixture);
+			var elapsed = fixture.endTime-fixture.startTime;
+			if(fn){
+				fn.getElementsByTagName("td")[3].innerHTML = elapsed+"ms";
+				fn.className = (success) ? "success" : "failure";
+				fn.getElementsByTagName("td")[2].setAttribute('_target', _loggedMsgLen);
+				if(!success){
+					_playSound("doh");
+					var gn = getGroupNode(group);
+					if(gn){
+						gn.className = "failure";
+						_getGroupToggler(group)(null, true);
+					}
+				}
+			}
+			if(doh._inGroup == group){
+				var gn = getGroupNode(group);
+				doh._runed++;
+				if(gn && doh._curTestCount){
+					var p = doh._runed/doh._curTestCount;
+					var groupfail = this._updateGlobalProgressBar((doh._runedSuite+p-1)/doh._groupCount,success,group);
+
+					var pbar = gn.getElementsByTagName("td")[2].lastChild;
+					pbar.className = groupfail?"failure":"success";
+					pbar.style.width = parseInt(p*100)+"%";
+					gn.getElementsByTagName("td")[3].innerHTML = parseInt(p*10000)/100+"%";
+				}
+			}
+			this._groupTotalTime += elapsed;
+			this.debug((success ? "PASSED" : "FAILED"), "test:", fixture.name, elapsed, 'ms');
+		}
+
+		// FIXME: move implementation to _browserRunner?
+		doh.registerUrl = function(	/*String*/ group,
+										/*String*/ url,
+										/*Integer*/ timeout){
+			var tg = new String(group);
+			this.register(group, {
+				name: url,
+				setUp: function(){
+					doh.currentGroupName = tg;
+					doh.currentGroup = this;
+					doh.currentUrl = url;
+					this.d = new doh.Deferred();
+					doh.currentTestDeferred = this.d;
+					doh.showTestPage();
+					byId("testBody").src = url;
+				},
+				timeout: timeout||10000, // 10s
+				// timeout: timeout||1000, // 10s
+				runTest: function(){
+					// FIXME: implement calling into the url's groups here!!
+					return this.d;
+				},
+				tearDown: function(){
+					doh.currentGroupName = null;
+					doh.currentGroup = null;
+					doh.currentTestDeferred = null;
+					doh.currentUrl = null;
+					// this.d.errback(false);
+					// byId("testBody").src = "about:blank";
+					doh.showLogPage();
+				}
+			});
+		}
+
+		//
+		// Utility code for runner.html
+		//
+		// var isSafari = navigator.appVersion.indexOf("Safari") >= 0;
+		var tabzidx = 1;
+		var _showTab = function(toShow, toHide){
+			// FIXME: I don't like hiding things this way.
+			var i;
+			for(i = 0; i < toHide.length; i++){
+				var node = byId(toHide[i]);
+				if(node){
+					node.style.display="none";
+				}
+			}
+			toShow = byId(toShow);
+			if(toShow){
+				with(toShow.style){
+					display = "";
+					zIndex = ++tabzidx;
+				}
+			}
+		}
+
+		doh.showTestPage = function(){
+			_showTab("testBody", ["logBody", "perfTestsBody"]);
+		}
+
+		doh.showLogPage = function(){
+			_showTab("logBody", ["testBody", "perfTestsBody"]);
+		}
+
+		doh.showPerfTestsPage = function(){
+			_showTab("perfTestsBody", ["testBody", "logBody"]);
+		}
+
+		var runAll = true;
+		doh.toggleRunAll = function(){
+			// would be easier w/ query...sigh
+			runAll = !runAll;
+			if(!byId("testList")){ return; }
+			var tb = byId("testList").tBodies[0];
+			var inputs = tb.getElementsByTagName("input");
+			var x=0; var tn;
+			while((tn=inputs[x++])){
+				tn.checked = runAll;
+				doh._groups[tn.group].skip = (!runAll);
+			}
+		}
+
+		var listHeightTimer = null;
+		var setListHeight = function(){
+			if(listHeightTimer){
+				clearTimeout(listHeightTimer);
+			}
+			var tl = byId("testList");
+			if(!tl){ return; }
+			listHeightTimer = doh.setTimeout(function(){
+				tl.style.display = "none";
+				tl.style.display = "";
+
+			}, 10);
+		}
+
+		_addOnEvt("resize", setListHeight);
+		_addOnEvt("load", setListHeight);
+		_addOnEvt("load", function(){
+			if(loaded){ return; }
+			loaded = true;
+			groupTemplate = byId("groupTemplate");
+			if(!groupTemplate){
+				// make sure we've got an ammenable DOM structure
+				return;
+			}
+			groupTemplate.parentNode.removeChild(groupTemplate);
+			groupTemplate.style.display = "";
+			testTemplate = byId("testTemplate");
+			testTemplate.parentNode.removeChild(testTemplate);
+			testTemplate.style.display = "";
+			doh._updateTestList();
+		});
+
+		_addOnEvt("load",
+			function(){
+				// let robot code run if it gets to this first
+				var __onEnd = doh._onEnd;
+				doh._onEnd = function(){
+					__onEnd.apply(doh, arguments);
+					if(doh._failureCount == 0){
+						doh.debug("WOOHOO!!");
+						_playSound("woohoo");
+					}else{
+						console.debug("doh._failureCount:", doh._failureCount);
+					}
+					if(byId("play")){
+						toggleRunning();
+					}
+				}
+				if(!byId("play")){
+					// make sure we've got an amenable DOM structure
+					return;
+				}
+				var isRunning = false;
+				var toggleRunning = function(){
+					// ugg, this would be so much better w/ dojo.query()
+					if(isRunning){
+						byId("play").style.display = byId("pausedMsg").style.display = "";
+						byId("playingMsg").style.display = byId("pause").style.display = "none";
+						isRunning = false;
+					}else{
+						byId("play").style.display = byId("pausedMsg").style.display = "none";
+						byId("playingMsg").style.display = byId("pause").style.display = "";
+						isRunning = true;
+					}
+				}
+				doh.run = (function(oldRun){
+					return function(){
+						if(!doh._currentGroup){
+							toggleRunning();
+						}
+						return oldRun.apply(doh, arguments);
+					}
+				})(doh.run);
+				var btns = byId("toggleButtons").getElementsByTagName("span");
+				var node; var idx=0;
+				while((node=btns[idx++])){
+					node.onclick = toggleRunning;
+				}
+
+				//Performance report generating functions!
+				doh._dojoPlotPerfResults = function(div, name, dataArray) {
+					var median = doh.median(dataArray);
+					var medarray = [];
+
+					var i;
+					for(i = 0; i < dataArray.length; i++){
+						medarray.push(median);
+					}
+
+					var data = {
+						label: "name",
+						items: [
+							{name: name, trials: dataArray},
+							{name: "Median", trials: medarray}
+						]
+					};
+					var ifs = new dojo.data.ItemFileReadStore({data: data});
+
+					var min = Math.floor(doh.min(dataArray));
+					var max = Math.ceil(doh.max(dataArray));
+					var step = (max - min)/10;
+
+					//Lets try to pad out the bottom and top a bit
+					//Then recalc the step.
+					if(min > 0){
+						min = min - step;
+						if(min < 0){
+							min = 0;
+						}
+						min = Math.floor(min);
+					}
+					if(max > 0){
+						max = max + step;
+						max = Math.ceil(max);
+					}
+					step = (max - min)/10;
+
+					var chart = new dojox.charting.DataChart(div, {
+						type: dojox.charting.plot2d.Lines,
+						displayRange:dataArray.length,
+						xaxis: {min: 1, max: dataArray.length, majorTickStep: Math.ceil((dataArray.length - 1)/10), htmlLabels: false},
+						yaxis: {min: min, max: max, majorTickStep: step, vertical: true, htmlLabels: false}
+					});
+					chart.setStore(ifs, {name:"*"}, "trials");
+				};
+
+				doh._asciiPlotPerfResults = function(){
+					//TODO:  Implement!
+				};
+			}
+		);
+	}else{
+		// we're in an iframe environment. Time to mix it up a bit.
+
+		_doh = window.parent.doh;
+		var _thisGroup = _doh.currentGroupName;
+		var _thisUrl = _doh.currentUrl;
+		if(_thisGroup){
+			doh._testRegistered = function(group, tObj){
+				_doh._updateTestList(_thisGroup, tObj);
+			}
+			doh._onEnd = function(){
+				_doh._errorCount += doh._errorCount;
+				_doh._failureCount += doh._failureCount;
+				_doh._testCount += doh._testCount;
+				// should we be really adding raw group counts?
+				//_doh._groupCount += doh._groupCount;
+				_doh.currentTestDeferred.callback(true);
+			}
+			var otr = doh._getTestObj;
+			doh._getTestObj = function(){
+				var tObj = otr.apply(doh, arguments);
+				tObj.name = _thisUrl+"::"+arguments[0]+"::"+tObj.name;
+				return tObj;
+			}
+			doh.debug = doh.hitch(_doh, "debug");
+			doh.registerUrl = doh.hitch(_doh, "registerUrl");
+			doh._testStarted = function(group, fixture){
+				_doh._testStarted(_thisGroup, fixture);
+			}
+			doh._testFinished = function(g, f, s){
+				_doh._testFinished(_thisGroup, f, s);
+
+				//Okay, there may be performance info we need to filter back
+				//to the parent, so do that here.
+				if(doh.perfTestResults){
+					try{
+						gName = g.toString();
+						var localFName = f.name;
+						while(localFName.indexOf("::") >= 0){
+							localFName = localFName.substring(localFName.indexOf("::") + 2, localFName.length);
+						}
+						if(!_doh.perfTestResults){
+							_doh.perfTestResults = {};
+						}
+						if(!_doh.perfTestResults[gName]){
+							_doh.perfTestResults[gName] = {};
+						}
+						_doh.perfTestResults[gName][f.name] = doh.perfTestResults[gName][localFName];
+					}catch (e){
+						doh.debug(e);
+					}
+				}
+			}
+			doh._groupStarted = function(g){
+				if(!this._setParent){
+					_doh._curTestCount = this._testCount;
+					_doh._curGroupCount = this._groupCount;
+					this._setParent = true;
+				}
+			}
+			doh._report = function(){
+			};
+		}
+	}
+
+})();
diff --git a/tests/doh/_nodeRunner.js b/tests/doh/_nodeRunner.js
new file mode 100644
index 0000000..4a71f6a
--- /dev/null
+++ b/tests/doh/_nodeRunner.js
@@ -0,0 +1,20 @@
+
+/*global doh: false, process: false */
+
+var aps = Array.prototype.slice;
+
+doh.debug = function () {
+    //Could have multiple args, join them all together.
+    var msg = aps.call(arguments, 0).join(' ');
+    console.log(msg);
+};
+
+// Override the doh._report method to make it quit with an
+// appropriate exit code in case of test failures.
+var oldReport = doh._report;
+doh._report = function () {
+    oldReport.apply(doh, arguments);
+    if (this._failureCount > 0 || this._errorCount > 0) {
+        process.exit(1);
+    }
+};
diff --git a/tests/doh/_rhinoRunner.js b/tests/doh/_rhinoRunner.js
new file mode 100644
index 0000000..ae47597
--- /dev/null
+++ b/tests/doh/_rhinoRunner.js
@@ -0,0 +1,17 @@
+if(this["dojo"]){
+	dojo.provide("doh._rhinoRunner");
+}
+
+doh.debug = print;
+
+// Override the doh._report method to make it quit with an 
+// appropriate exit code in case of test failures.
+(function(){
+	var oldReport = doh._report;
+	doh._report = function(){
+		oldReport.apply(doh, arguments);
+		if(this._failureCount > 0 || this._errorCount > 0){
+			quit(1);
+		}
+	}
+})();
diff --git a/tests/doh/runner.html b/tests/doh/runner.html
new file mode 100644
index 0000000..2aa2176
--- /dev/null
+++ b/tests/doh/runner.html
@@ -0,0 +1,316 @@
+<html>
+	<!--
+		NOTE: we are INTENTIONALLY in quirks mode. It makes it much easier to
+		get a "full screen" UI w/ straightforward CSS.
+	-->
+	<!--
+		// TODO: provide a UI for prompted tests
+	-->
+	<head>
+		<title>RequireJS Tests Via The Dojo Unit Test Harness, $Rev: 20149 $</title>
+
+		<script type="text/javascript">
+			// workaround for bug in Safari 3.  See #7189
+			if (/3[\.0-9]+ Safari/.test(navigator.appVersion))
+			{
+				window.console = {
+				    origConsole: window.console,
+				    log: function(s){
+						this.origConsole.log(s);
+					},
+					info: function(s){
+						this.origConsole.info(s);
+					},
+					error: function(s){
+						this.origConsole.error(s);
+					},
+					warn: function(s){
+						this.origConsole.warn(s);
+					}
+				};
+			}
+		</script>
+
+		<script type="text/javascript">
+			window.dojoUrl = "../../dojo/dojo.js";
+			window.testUrl = "";
+			window.testModule = "";
+
+			// parse out our test URL and our Dojo URL from the query string
+			var qstr = window.location.search.substr(1);
+			if(qstr.length){
+				var qparts = qstr.split("&");
+				for(var x=0; x<qparts.length; x++){
+					var tp = qparts[x].split("=");
+					if(tp[0] == "dojoUrl"){
+						window.dojoUrl = tp[1];
+					}
+					if(tp[0] == "testUrl"){
+						window.testUrl = tp[1];
+					}
+					if(tp[0] == "testModule"){
+						window.testModule = tp[1];
+					}
+					if(tp[0] == "registerModulePath"){
+						var modules = tp[1].split(";");
+						window.registerModulePath=[];
+						for (var i=0; i<modules.length;i++){
+							window.registerModulePath.push(modules[i].split(","));
+						}
+					}
+				}
+			}
+
+			//document.write("<scr"+"ipt type='text/javascript' djConfig='isDebug: true' src='"+dojoUrl+"'></scr"+"ipt>");
+		</script>
+		<script type="text/javascript" src="runner.js"></script>
+		<script type="text/javascript" src="_browserRunner.js"></script>
+
+		<script type="text/javascript">
+			if(testUrl.length){
+				document.write("<scr"+"ipt type='text/javascript' src='"+testUrl+".js'></scr"+"ipt>");
+			}
+		</script>
+		<style type="text/css">
+			/* @import "../../dojo/resources/dojo.css"; */
+			/*
+			body {
+				margin: 0px;
+				padding: 0px;
+				font-size: 13px;
+				color: #292929;
+				font-family: Myriad, Lucida Grande, Bitstream Vera Sans, Arial, Helvetica, sans-serif;
+				*font-size: small;
+				*font: x-small;
+			}
+
+			th, td {
+				font-size: 13px;
+				color: #292929;
+				font-family: Myriad, Lucida Grande, Bitstream Vera Sans, Arial, Helvetica, sans-serif;
+				font-weight: normal;
+			}
+
+			* body {
+				line-height: 1.25em;
+			}
+			
+			table {
+				border-collapse: collapse;
+			}
+			*/
+
+			#testLayout {
+				position: relative;
+				left: 0px;
+				top: 0px;
+				width: 100%;
+				height: 100%;
+				border: 1px solid black;
+				border: 0px;
+			}
+
+			.tabBody {
+				margin: 0px;
+				padding: 0px;
+				/*
+				border: 1px solid black;
+				*/
+				background-color: #DEDEDE;
+				border: 0px;
+				width: 100%;
+				height: 100%;
+				position: absolute;
+				left: 0px; 
+				top: 0px;
+				overflow: auto;
+			}
+
+			#logBody {
+				padding-left: 5px;
+				padding-top: 5px;
+				font-family: Monaco, monospace;
+				font-size: 11px;
+				white-space: pre;
+			}
+
+			#progressOuter {
+				background:#e9e9e9 url("http://o.aolcdn.com/dojo/1.3/dijit/themes/tundra/images/dojoTundraGradientBg.png") repeat-x 0 0;
+				height: 1em;
+				/*the following trick is necessary to prevent IE from wrapping the last piece of progress bar into a new line*/
+				_margin:1px;
+				_padding: -1px;
+				
+				/*
+				border-color: #e8e8e8;
+				*/
+			}
+
+			#progressOuter .success, #progressOuter .failure{
+				float: left;
+				height: 1em;
+			}
+
+			#play, #pause {
+				font-family: Arial;
+				font-size: 1.4em;
+				border: 1px solid #DEDEDE;
+				cursor: pointer;
+				padding-right: 0.5em;
+			}
+
+			.header {
+				border: 1px solid #DEDEDE;
+			}
+
+			button.tab {
+				border-width: 1px 1px 0px 1px;
+				border-style: solid;
+				border-color: #DEDEDE;
+				margin-right: 5px;
+			}
+
+			#testListContainer {
+				/*
+				border: 1px solid black;
+				*/
+				position: relative;
+				height: 99%;
+				width: 100%;
+				overflow: auto;
+			}
+
+			#testList {
+				border-collapse: collapse;
+				position: absolute;
+				left: 0px;
+				width: 100%;
+			}
+
+			#testList td {
+				border-bottom: 1px solid #DEDEDE;
+				border-right : 1px solid #DEDEDE;
+				padding: 3px;
+			}
+
+			#testListHeader th {
+				border-bottom: 1px solid #DEDEDE;
+				border-right : 1px solid #DEDEDE;
+				padding: 3px;
+				font-weight: bolder;
+				font-style: italic;
+			}
+			
+			#testList tfoot {
+				font-weight: bold;
+			}
+
+			#toggleButtons {
+				float: left;
+				background-color: #DEDEDE;
+			}
+
+			div.testGroupName {
+				position: absolute;
+			}
+
+			.inProgress {
+				background-color: #85afde;
+			}
+
+			.success {
+				background-color: #7cdea7;
+			}
+
+			.failure {
+				background-color: #de827b;
+			}
+		</style>
+	</head>
+	<body>
+		<table id="testLayout" cellpadding="0" cellspacing="0" style="margin: 0;">
+			<tr valign="top" height="40">
+				<td colspan="2" id="logoBar">
+					<h3 style="margin: 5px 5px 0px 5px; float: left;">RequireJS Tests Via D.O.H.: The Dojo Objective Harness</h3>
+					<img src="small_logo.png" height="40" style="margin: 0px 5px 0px 5px; float: right;">
+					<span style="margin: 10px 5px 0px 5px; float: right;">
+						<input type="checkbox" id="audio" name="audio">
+						<label for="audio">sounds?</label>
+					</span>
+				</td>
+			</tr>
+			<tr valign="top" height="10">
+				<td colspan="2"><div id="progressOuter" onclick="doh._jumpToSuite(arguments[0]);"></div></td>
+			</tr>
+			<tr valign="top" height="30">
+				<td width="30%" class="header">
+					<span id="toggleButtons" onclick="doh.togglePaused();">
+						<button id="play">►</button>
+						<button id="pause" style="display: none;">║</button>
+					</span>
+					<span id="runningStatus">
+						<span id="pausedMsg">Stopped</span>
+						<span id="playingMsg" style="display: none;">Tests Running</span>
+					</span>
+				</td>
+				<td width="*" class="header" valign="bottom">
+					<button class="tab" onclick="doh.showTestPage();">Test Page</button>
+					<button class="tab" onclick="doh.showLogPage();">Log</button>
+                    <button class="tab" onclick="doh.showPerfTestsPage();">Performance Tests Results</button>
+				</td>
+			</tr>
+			<tr valign="top" style="border: 0; padding: 0; margin: 0;">
+				<td height="100%" style="border: 0; padding: 0; margin: 0;">
+					<div id="testListContainer">
+						<table cellpadding="0" cellspacing="0" border="0"
+							width="100%" id="testList" style="margin: 0;" onclick="doh._jumpToLog(arguments[0]);">
+							<thead>
+								<tr id="testListHeader" style="border: 0; padding: 0; margin: 0;" >
+									<th> </th>
+									<th width="20">
+										<input type="checkbox" checked 
+											onclick="doh.toggleRunAll();">
+									</th>
+									<th width="*" style="text-align: left;">test</th>
+									<th width="50">time</th>
+								</tr>
+							</thead>
+							<tbody valign="top">
+								<tr id="groupTemplate" style="display: none;">
+									<td style="font-family: Arial; width: 15px;">►</td>
+									<td>
+										<input type="checkbox" checked>
+									</td>
+									<td>group name</td>
+									<td>10ms</td>
+								</tr>
+								<tr id="testTemplate" style="display: none;">
+									<td> </td>
+									<td> </td>
+									<td style="padding-left: 20px;">test name</td>
+									<td>10ms</td>
+								</tr>
+							</tbody>
+						</table>
+					</div>
+				</td>
+				<td>
+					<div style="position: relative; width: 99%; height: 100%; top: 0px; left: 0px;">
+						<div class="tabBody"
+							style="z-index: 1;">
+							<pre id="logBody"></pre>
+							<div id="perfTestsBody" style="background-color: white;"></div>
+						</div>
+						<iframe id="testBody" class="tabBody"
+							style="z-index: -1;"></iframe>
+						<!--
+							src="http://redesign.dojotoolkit.org"></iframe>
+						-->
+					</div>
+				</td>
+			</tr>
+		</table>
+		<span id="hiddenAudio"></span>
+	</body>
+</html>
+
diff --git a/tests/doh/runner.js b/tests/doh/runner.js
new file mode 100644
index 0000000..2bf1260
--- /dev/null
+++ b/tests/doh/runner.js
@@ -0,0 +1,1499 @@
+// package system gunk.
+//try{
+//	dojo.provide("doh.runner");
+//}catch(e){
+	if(!this["doh"]){
+		doh = {};
+	}
+//}
+
+//
+// Utility Functions and Classes
+//
+
+doh.selfTest = false;
+
+doh.global = this;
+
+doh.hitch = function(/*Object*/thisObject, /*Function|String*/method /*, ...*/){
+	var args = [];
+	for(var x=2; x<arguments.length; x++){
+		args.push(arguments[x]);
+	}
+	var fcn = ((typeof method == "string") ? thisObject[method] : method) || function(){};
+	return function(){
+		var ta = args.concat([]); // make a copy
+		for(var x=0; x<arguments.length; x++){
+			ta.push(arguments[x]);
+		}
+		return fcn.apply(thisObject, ta); // Function
+	};
+}
+
+doh._mixin = function(/*Object*/ obj, /*Object*/ props){
+	// summary:
+	//		Adds all properties and methods of props to obj. This addition is
+	//		"prototype extension safe", so that instances of objects will not
+	//		pass along prototype defaults.
+	var tobj = {};
+	for(var x in props){
+		// the "tobj" condition avoid copying properties in "props"
+		// inherited from Object.prototype.  For example, if obj has a custom
+		// toString() method, don't overwrite it with the toString() method
+		// that props inherited from Object.protoype
+		if(tobj[x] === undefined || tobj[x] != props[x]){
+			obj[x] = props[x];
+		}
+	}
+	// IE doesn't recognize custom toStrings in for..in
+	if(	this["document"]
+		&& document.all
+		&& (typeof props["toString"] == "function")
+		&& (props["toString"] != obj["toString"])
+		&& (props["toString"] != tobj["toString"])
+	){
+		obj.toString = props.toString;
+	}
+	return obj; // Object
+}
+
+doh.mixin = function(/*Object*/obj, /*Object...*/props){
+	// summary:	Adds all properties and methods of props to obj.
+	for(var i=1, l=arguments.length; i<l; i++){
+		doh._mixin(obj, arguments[i]);
+	}
+	return obj; // Object
+}
+
+doh.extend = function(/*Object*/ constructor, /*Object...*/ props){
+	// summary:
+	//		Adds all properties and methods of props to constructor's
+	//		prototype, making them available to all instances created with
+	//		constructor.
+	for(var i=1, l=arguments.length; i<l; i++){
+		doh._mixin(constructor.prototype, arguments[i]);
+	}
+	return constructor; // Object
+}
+
+
+doh._line = "------------------------------------------------------------";
+
+/*
+doh._delegate = function(obj, props){
+	// boodman-crockford delegation
+	function TMP(){};
+	TMP.prototype = obj;
+	var tmp = new TMP();
+	if(props){
+		dojo.lang.mixin(tmp, props);
+	}
+	return tmp;
+}
+*/
+
+doh.debug = function(){
+	// summary:
+	//		takes any number of arguments and sends them to whatever debugging
+	//		or logging facility is available in this environment
+
+	// YOUR TEST RUNNER NEEDS TO IMPLEMENT THIS
+}
+
+doh._AssertFailure = function(msg, hint){
+	// idea for this as way of dis-ambiguating error types is from JUM.
+	// The JUM is dead! Long live the JUM!
+
+	if(!(this instanceof doh._AssertFailure)){
+		return new doh._AssertFailure(msg, hint);
+	}
+	if(hint){
+		msg = (new String(msg||""))+" with hint: \n\t\t"+(new String(hint)+"\n");
+	}
+	this.message = new String(msg||"");
+	return this;
+}
+doh._AssertFailure.prototype = new Error();
+doh._AssertFailure.prototype.constructor = doh._AssertFailure;
+doh._AssertFailure.prototype.name = "doh._AssertFailure";
+
+doh.Deferred = function(canceller){
+	this.chain = [];
+	this.id = this._nextId();
+	this.fired = -1;
+	this.paused = 0;
+	this.results = [null, null];
+	this.canceller = canceller;
+	this.silentlyCancelled = false;
+};
+
+doh.extend(doh.Deferred, {
+	getTestErrback: function(cb, scope){
+		// summary: Replaces outer getTextCallback's in nested situations to avoid multiple callback(true)'s
+		var _this = this;
+		return function(){
+			try{
+				cb.apply(scope||doh.global||_this, arguments);
+			}catch(e){
+				_this.errback(e);
+			}
+		};
+	},
+
+	getTestCallback: function(cb, scope){
+		var _this = this;
+		return function(){
+			try{
+				cb.apply(scope||doh.global||_this, arguments);
+			}catch(e){
+				_this.errback(e);
+				return;
+			}
+			_this.callback(true);
+		};
+	},
+
+	getFunctionFromArgs: function(){
+		var a = arguments;
+		if((a[0])&&(!a[1])){
+			if(typeof a[0] == "function"){
+				return a[0];
+			}else if(typeof a[0] == "string"){
+				return doh.global[a[0]];
+			}
+		}else if((a[0])&&(a[1])){
+			return doh.hitch(a[0], a[1]);
+		}
+		return null;
+	},
+
+	makeCalled: function() {
+		var deferred = new doh.Deferred();
+		deferred.callback();
+		return deferred;
+	},
+
+	_nextId: (function(){
+		var n = 1;
+		return function(){ return n++; };
+	})(),
+
+	cancel: function(){
+		if(this.fired == -1){
+			if (this.canceller){
+				this.canceller(this);
+			}else{
+				this.silentlyCancelled = true;
+			}
+			if(this.fired == -1){
+				this.errback(new Error("Deferred(unfired)"));
+			}
+		}else if(this.fired == 0 &&
+					(this.results[0] instanceof doh.Deferred)){
+			this.results[0].cancel();
+		}
+	},
+
+
+	_pause: function(){
+		this.paused++;
+	},
+
+	_unpause: function(){
+		this.paused--;
+		if ((this.paused == 0) && (this.fired >= 0)) {
+			this._fire();
+		}
+	},
+
+	_continue: function(res){
+		this._resback(res);
+		this._unpause();
+	},
+
+	_resback: function(res){
+		this.fired = ((res instanceof Error) ? 1 : 0);
+		this.results[this.fired] = res;
+		this._fire();
+	},
+
+	_check: function(){
+		if(this.fired != -1){
+			if(!this.silentlyCancelled){
+				throw new Error("already called!");
+			}
+			this.silentlyCancelled = false;
+			return;
+		}
+	},
+
+	callback: function(res){
+		this._check();
+		this._resback(res);
+	},
+
+	errback: function(res){
+		this._check();
+		if(!(res instanceof Error)){
+			res = new Error(res);
+		}
+		this._resback(res);
+	},
+
+	addBoth: function(cb, cbfn){
+		var enclosed = this.getFunctionFromArgs(cb, cbfn);
+		if(arguments.length > 2){
+			enclosed = doh.hitch(null, enclosed, arguments, 2);
+		}
+		return this.addCallbacks(enclosed, enclosed);
+	},
+
+	addCallback: function(cb, cbfn){
+		var enclosed = this.getFunctionFromArgs(cb, cbfn);
+		if(arguments.length > 2){
+			enclosed = doh.hitch(null, enclosed, arguments, 2);
+		}
+		return this.addCallbacks(enclosed, null);
+	},
+
+	addErrback: function(cb, cbfn){
+		var enclosed = this.getFunctionFromArgs(cb, cbfn);
+		if(arguments.length > 2){
+			enclosed = doh.hitch(null, enclosed, arguments, 2);
+		}
+		return this.addCallbacks(null, enclosed);
+	},
+
+	addCallbacks: function(cb, eb){
+		this.chain.push([cb, eb]);
+		if(this.fired >= 0){
+			this._fire();
+		}
+		return this;
+	},
+
+	_fire: function(){
+		var chain = this.chain;
+		var fired = this.fired;
+		var res = this.results[fired];
+		var self = this;
+		var cb = null;
+		while(chain.length > 0 && this.paused == 0){
+			// Array
+			var pair = chain.shift();
+			var f = pair[fired];
+			if(f == null){
+				continue;
+			}
+			try {
+				res = f(res);
+				fired = ((res instanceof Error) ? 1 : 0);
+				if(res instanceof doh.Deferred){
+					cb = function(res){
+						self._continue(res);
+					};
+					this._pause();
+				}
+			}catch(err){
+				fired = 1;
+				res = err;
+			}
+		}
+		this.fired = fired;
+		this.results[fired] = res;
+		if((cb)&&(this.paused)){
+			res.addBoth(cb);
+		}
+	}
+});
+
+//
+// State Keeping and Reporting
+//
+
+doh._testCount = 0;
+doh._groupCount = 0;
+doh._errorCount = 0;
+doh._failureCount = 0;
+doh._currentGroup = null;
+doh._currentTest = null;
+doh._paused = true;
+
+doh._init = function(){
+	this._currentGroup = null;
+	this._currentTest = null;
+	this._errorCount = 0;
+	this._failureCount = 0;
+	this.debug(this._testCount, "tests to run in", this._groupCount, "groups");
+}
+
+// doh._urls = [];
+doh._groups = {};
+
+//
+// Test Registration
+//
+
+doh.registerTestNs = function(/*String*/ group, /*Object*/ ns){
+	// summary:
+	//		adds the passed namespace object to the list of objects to be
+	//		searched for test groups. Only "public" functions (not prefixed
+	//		with "_") will be added as tests to be run. If you'd like to use
+	//		fixtures (setUp(), tearDown(), and runTest()), please use
+	//		registerTest() or registerTests().
+	for(var x in ns){
+		if(	(x.charAt(0) != "_") &&
+			(typeof ns[x] == "function") ){
+			this.registerTest(group, ns[x]);
+		}
+	}
+}
+
+doh._testRegistered = function(group, fixture){
+	// slot to be filled in
+}
+
+doh._groupStarted = function(group){
+	// slot to be filled in
+}
+
+doh._groupFinished = function(group, success){
+	// slot to be filled in
+}
+
+doh._testStarted = function(group, fixture){
+	// slot to be filled in
+}
+
+doh._testFinished = function(group, fixture, success){
+	// slot to be filled in
+}
+
+doh.registerGroup = function(	/*String*/ group,
+								/*Array||Function||Object*/ tests,
+								/*Function*/ setUp,
+								/*Function*/ tearDown,
+								/*String*/ type){
+	// summary:
+	//		registers an entire group of tests at once and provides a setUp and
+	//		tearDown facility for groups. If you call this method with only
+	//		setUp and tearDown parameters, they will replace previously
+	//		installed setUp or tearDown functions for the group with the new
+	//		methods.
+	// group:
+	//		string name of the group
+	// tests:
+	//		either a function or an object or an array of functions/objects. If
+	//		an object, it must contain at *least* a "runTest" method, and may
+	//		also contain "setUp" and "tearDown" methods. These will be invoked
+	//		on either side of the "runTest" method (respectively) when the test
+	//		is run. If an array, it must contain objects matching the above
+	//		description or test functions.
+	// setUp: a function for initializing the test group
+	// tearDown: a function for initializing the test group
+	// type: The type of tests these are, such as a group of performance tests
+	//		null/undefied are standard DOH tests, the valye 'perf' enables
+	//		registering them as performance tests.
+	if(tests){
+		this.register(group, tests, type);
+	}
+	if(setUp){
+		this._groups[group].setUp = setUp;
+	}
+	if(tearDown){
+		this._groups[group].tearDown = tearDown;
+	}
+}
+
+doh._getTestObj = function(group, test, type){
+	var tObj = test;
+	if(typeof test == "string"){
+		if(test.substr(0, 4)=="url:"){
+			return this.registerUrl(group, test);
+		}else{
+			tObj = {
+				name: test.replace("/\s/g", "_") // FIXME: bad escapement
+			};
+			tObj.runTest = new Function("t", test);
+		}
+	}else if(typeof test == "function"){
+		// if we didn't get a fixture, wrap the function
+		tObj = { "runTest": test };
+		if(test["name"]){
+			tObj.name = test.name;
+		}else{
+			try{
+				var fStr = "function ";
+				var ts = tObj.runTest+"";
+				if(0 <= ts.indexOf(fStr)){
+					tObj.name = ts.split(fStr)[1].split("(", 1)[0];
+				}
+				// doh.debug(tObj.runTest.toSource());
+			}catch(e){
+			}
+		}
+		// FIXME: try harder to get the test name here
+	}
+
+	//Augment the test with some specific options to make it identifiable as a
+	//particular type of test so it can be executed properly.
+	if(type === "perf" || tObj.testType === "perf"){
+		tObj.testType = "perf";
+
+		//Build an object on the root DOH class to contain all the test results.
+		//Cache it on the test object for quick lookup later for results storage.
+		if(!doh.perfTestResults){
+			doh.perfTestResults = {};
+			doh.perfTestResults[group] = {};
+		}
+		if(!doh.perfTestResults[group]){
+			doh.perfTestResults[group] = {};
+		}
+		if(!doh.perfTestResults[group][tObj.name]){
+			doh.perfTestResults[group][tObj.name] = {};
+		}
+		tObj.results = doh.perfTestResults[group][tObj.name];
+
+		//If it's not set, then set the trial duration
+		//default to 100ms.
+		if(!("trialDuration" in tObj)){
+			tObj.trialDuration = 100;
+		}
+
+		//If it's not set, then set the delay between trial runs to 100ms
+		//default to 100ms to allow for GC and to make IE happy.
+		if(!("trialDelay" in tObj)){
+			tObj.trialDelay = 100;
+		}
+
+		//If it's not set, then set number of times a trial is run to 10.
+		if(!("trialIterations" in tObj)){
+			tObj.trialIterations = 10;
+		}
+	}
+	return tObj;
+}
+
+doh.registerTest = function(/*String*/ group, /*Function||Object*/ test, /*String*/ type){
+	// summary:
+	//		add the provided test function or fixture object to the specified
+	//		test group.
+	// group:
+	//		string name of the group to add the test to
+	// test:
+	//		either a function or an object. If an object, it must contain at
+	//		*least* a "runTest" method, and may also contain "setUp" and
+	//		"tearDown" methods. These will be invoked on either side of the
+	//		"runTest" method (respectively) when the test is run.
+	// type:
+	//		An identifier denoting the type of testing that the test performs, such
+	//		as a performance test.  If null, defaults to regular DOH test.
+	if(!this._groups[group]){
+		this._groupCount++;
+		this._groups[group] = [];
+		this._groups[group].inFlight = 0;
+	}
+	var tObj = this._getTestObj(group, test, type);
+	if(!tObj){ return null; }
+	this._groups[group].push(tObj);
+	this._testCount++;
+	this._testRegistered(group, tObj);
+	return tObj;
+}
+
+doh.registerTests = function(/*String*/ group, /*Array*/ testArr, /*String*/ type){
+	// summary:
+	//		registers a group of tests, treating each element of testArr as
+	//		though it were being (along with group) passed to the registerTest
+	//		method.  It also uses the type to decide how the tests should
+	//		behave, by defining the type of tests these are, such as performance tests
+	for(var x=0; x<testArr.length; x++){
+		this.registerTest(group, testArr[x], type);
+	}
+}
+
+// FIXME: move implementation to _browserRunner?
+doh.registerUrl = function(	/*String*/ group,
+								/*String*/ url,
+								/*Integer*/ timeout,
+								/*String*/ type){
+	this.debug("ERROR:");
+	this.debug("\tNO registerUrl() METHOD AVAILABLE.");
+	// this._urls.push(url);
+}
+
+doh.registerString = function(group, str, type){
+}
+
+// FIXME: remove the doh.add alias SRTL.
+doh.register = doh.add = function(groupOrNs, testOrNull, type){
+	// summary:
+	// 		"magical" variant of registerTests, registerTest, and
+	// 		registerTestNs. Will accept the calling arguments of any of these
+	// 		methods and will correctly guess the right one to register with.
+	if(	(arguments.length == 1)&&
+		(typeof groupOrNs == "string") ){
+		if(groupOrNs.substr(0, 4)=="url:"){
+			this.registerUrl(groupOrNs, null, null, type);
+		}else{
+			this.registerTest("ungrouped", groupOrNs, type);
+		}
+	}
+	if(arguments.length == 1){
+		this.debug("invalid args passed to doh.register():", groupOrNs, ",", testOrNull);
+		return;
+	}
+	if(typeof testOrNull == "string"){
+		if(testOrNull.substr(0, 4)=="url:"){
+			this.registerUrl(testOrNull, null, null, type);
+		}else{
+			this.registerTest(groupOrNs, testOrNull, type);
+		}
+		// this.registerTestNs(groupOrNs, testOrNull);
+		return;
+	}
+	if(doh._isArray(testOrNull)){
+		this.registerTests(groupOrNs, testOrNull, type);
+		return;
+	}
+	this.registerTest(groupOrNs, testOrNull, type);
+};
+
+doh.registerDocTests = function(module){
+	// no-op for when Dojo isn't loaded into the page
+	this.debug("registerDocTests() requires dojo to be loaded into the environment. Skipping doctest set for module:", module);
+};
+(function(){
+	if(typeof dojo != "undefined"){
+		try{
+			dojo.require("dojox.testing.DocTest");
+		}catch(e){
+			// if the DocTest module isn't available (e.g., the build we're
+			// running from doesn't include it), stub it out and log the error
+			console.debug(e);
+
+			doh.registerDocTests = function(){}
+			return;
+		}
+		doh.registerDocTests = function(module){
+			//	summary:
+			//		Get all the doctests from the given module and register each of them
+			//		as a single test case here.
+			//
+
+			var docTest = new dojox.testing.DocTest();
+			var docTests = docTest.getTests(module);
+			var len = docTests.length;
+			var tests = [];
+			for (var i=0; i<len; i++){
+				var test = docTests[i];
+				// Extract comment on first line and add to test name.
+				var comment = "";
+				if (test.commands.length && test.commands[0].indexOf("//")!=-1) {
+					var parts = test.commands[0].split("//");
+					comment = ", "+parts[parts.length-1]; // Get all after the last //, so we dont get trapped by http:// or alikes :-).
+				}
+				tests.push({
+					runTest: (function(test){
+						return function(t){
+							var r = docTest.runTest(test.commands, test.expectedResult);
+							t.assertTrue(r.success);
+						}
+					})(test),
+					name:"Line "+test.line+comment
+				}
+				);
+			}
+			this.register("DocTests: "+module, tests);
+		}
+	}
+})();
+
+//
+// Assertions and In-Test Utilities
+//
+
+doh.t = doh.assertTrue = function(/*Object*/ condition, /*String?*/ hint){
+	// summary:
+	//		is the passed item "truthy"?
+	if(arguments.length < 1){
+		throw new doh._AssertFailure("assertTrue failed because it was not passed at least 1 argument");
+	}
+	if(!eval(condition)){
+		throw new doh._AssertFailure("assertTrue('" + condition + "') failed", hint);
+	}
+}
+
+doh.f = doh.assertFalse = function(/*Object*/ condition, /*String?*/ hint){
+	// summary:
+	//		is the passed item "falsey"?
+	if(arguments.length < 1){
+		throw new doh._AssertFailure("assertFalse failed because it was not passed at least 1 argument");
+	}
+	if(eval(condition)){
+		throw new doh._AssertFailure("assertFalse('" + condition + "') failed", hint);
+	}
+}
+
+doh.e = doh.assertError = function(/*Error object*/expectedError, /*Object*/scope, /*String*/functionName, /*Array*/args, /*String?*/ hint){
+	//	summary:
+	//		Test for a certain error to be thrown by the given function.
+	//	example:
+	//		t.assertError(dojox.data.QueryReadStore.InvalidAttributeError, store, "getValue", [item, "NOT THERE"]);
+	//		t.assertError(dojox.data.QueryReadStore.InvalidItemError, store, "getValue", ["not an item", "NOT THERE"]);
+	try{
+		scope[functionName].apply(scope, args);
+	}catch (e){
+		if(e instanceof expectedError){
+			return true;
+		}else{
+			throw new doh._AssertFailure("assertError() failed:\n\texpected error\n\t\t"+expectedError+"\n\tbut got\n\t\t"+e+"\n\n", hint);
+		}
+	}
+	throw new doh._AssertFailure("assertError() failed:\n\texpected error\n\t\t"+expectedError+"\n\tbut no error caught\n\n", hint);
+}
+
+
+doh.is = doh.assertEqual = function(/*Object*/ expected, /*Object*/ actual, /*String?*/ hint){
+	// summary:
+	//		are the passed expected and actual objects/values deeply
+	//		equivalent?
+
+	// Compare undefined always with three equal signs, because undefined==null
+	// is true, but undefined===null is false.
+	if((expected === undefined)&&(actual === undefined)){
+		return true;
+	}
+	if(arguments.length < 2){
+		throw doh._AssertFailure("assertEqual failed because it was not passed 2 arguments");
+	}
+	if((expected === actual)||(expected == actual)||
+				( typeof expected == "number" && typeof actual == "number" && isNaN(expected) && isNaN(actual) )){
+		return true;
+	}
+	if(	(this._isArray(expected) && this._isArray(actual))&&
+		(this._arrayEq(expected, actual)) ){
+		return true;
+	}
+	if( ((typeof expected == "object")&&((typeof actual == "object")))&&
+		(this._objPropEq(expected, actual)) ){
+		return true;
+	}
+	throw new doh._AssertFailure("assertEqual() failed:\n\texpected\n\t\t"+expected+"\n\tbut got\n\t\t"+actual+"\n\n", hint);
+}
+
+doh.isNot = doh.assertNotEqual = function(/*Object*/ notExpected, /*Object*/ actual, /*String?*/ hint){
+	// summary:
+	//		are the passed notexpected and actual objects/values deeply
+	//		not equivalent?
+
+	// Compare undefined always with three equal signs, because undefined==null
+	// is true, but undefined===null is false.
+	if((notExpected === undefined)&&(actual === undefined)){
+        throw new doh._AssertFailure("assertNotEqual() failed: not expected |"+notExpected+"| but got |"+actual+"|", hint);
+	}
+	if(arguments.length < 2){
+		throw doh._AssertFailure("assertEqual failed because it was not passed 2 arguments");
+	}
+	if((notExpected === actual)||(notExpected == actual)){
+        throw new doh._AssertFailure("assertNotEqual() failed: not expected |"+notExpected+"| but got |"+actual+"|", hint);
+	}
+	if(	(this._isArray(notExpected) && this._isArray(actual))&&
+		(this._arrayEq(notExpected, actual)) ){
+		throw new doh._AssertFailure("assertNotEqual() failed: not expected |"+notExpected+"| but got |"+actual+"|", hint);
+	}
+	if( ((typeof notExpected == "object")&&((typeof actual == "object")))&&
+		(this._objPropEq(notExpected, actual)) ){
+        throw new doh._AssertFailure("assertNotEqual() failed: not expected |"+notExpected+"| but got |"+actual+"|", hint);
+	}
+    return true;
+}
+
+doh._arrayEq = function(expected, actual){
+	if(expected.length != actual.length){ return false; }
+	// FIXME: we're not handling circular refs. Do we care?
+	for(var x=0; x<expected.length; x++){
+		if(!doh.assertEqual(expected[x], actual[x])){ return false; }
+	}
+	return true;
+}
+
+doh._objPropEq = function(expected, actual){
+	// Degenerate case: if they are both null, then their "properties" are equal.
+	if(expected === null && actual === null){
+		return true;
+	}
+	// If only one is null, they aren't equal.
+	if(expected === null || actual === null){
+		return false;
+	}
+	if(expected instanceof Date){
+		return actual instanceof Date && expected.getTime()==actual.getTime();
+	}
+	var x;
+	// Make sure ALL THE SAME properties are in both objects!
+	for(x in actual){ // Lets check "actual" here, expected is checked below.
+		if(expected[x] === undefined){
+			return false;
+		}
+	};
+
+	for(x in expected){
+		if(!doh.assertEqual(expected[x], actual[x])){
+			return false;
+		}
+	}
+	return true;
+}
+
+doh._isArray = function(it){
+	return (it && it instanceof Array || typeof it == "array" ||
+		(
+			!!doh.global["dojo"] &&
+			doh.global["dojo"]["NodeList"] !== undefined &&
+			it instanceof doh.global["dojo"]["NodeList"]
+		)
+	);
+}
+
+//
+// Runner-Wrapper
+//
+
+doh._setupGroupForRun = function(/*String*/ groupName, /*Integer*/ idx){
+	var tg = this._groups[groupName];
+	this.debug(this._line);
+	this.debug("GROUP", "\""+groupName+"\"", "has", tg.length, "test"+((tg.length > 1) ? "s" : "")+" to run");
+}
+
+doh._handleFailure = function(groupName, fixture, e){
+	// this.debug("FAILED test:", fixture.name);
+	// mostly borrowed from JUM
+	this._groups[groupName].failures++;
+	var out = "";
+	if(e instanceof this._AssertFailure){
+		this._failureCount++;
+		if(e["fileName"]){ out += e.fileName + ':'; }
+		if(e["lineNumber"]){ out += e.lineNumber + ' '; }
+		out += e+": "+e.message;
+		this.debug("\t_AssertFailure:", out);
+	}else{
+		this._errorCount++;
+	}
+	this.debug(e);
+	if(fixture.runTest["toSource"]){
+		var ss = fixture.runTest.toSource();
+		this.debug("\tERROR IN:\n\t\t", ss);
+	}else{
+		this.debug("\tERROR IN:\n\t\t", fixture.runTest);
+	}
+
+	if(e.rhinoException){
+		e.rhinoException.printStackTrace();
+	}else if(e.javaException){
+		e.javaException.printStackTrace();
+	}
+}
+
+//Assume a setTimeout implementation that is synchronous, so that
+//the Node and Rhino envs work similar to each other. Node defines
+//a setTimeout, so testing for setTimeout is not enough, each environment
+//adapter should set this value accordingly.
+doh.setTimeout = function(func){
+	return func();
+};
+
+doh._runPerfFixture = function(/*String*/groupName, /*Object*/fixture){
+	//	summary:
+	//		This function handles how to execute a 'performance' test
+	//		which is different from a straight UT style test.  These
+	//		will often do numerous iterations of the same operation and
+	//		gather execution statistics about it, like max, min, average,
+	//		etc.  It makes use of the already in place DOH deferred test
+	//		handling since it is a good idea to put a pause inbetween each
+	//		iteration to allow for GC cleanup and the like.
+	//
+	//	groupName:
+	//		The test group that contains this performance test.
+	//	fixture:
+	//		The performance test fixture.
+	var tg = this._groups[groupName];
+	fixture.startTime = new Date();
+
+	//Perf tests always need to act in an async manner as there is a
+	//number of iterations to flow through.
+	var def = new doh.Deferred();
+	tg.inFlight++;
+	def.groupName = groupName;
+	def.fixture = fixture;
+
+	def.addErrback(function(err){
+		doh._handleFailure(groupName, fixture, err);
+	});
+
+	//Set up the finalizer.
+	var retEnd = function(){
+		if(fixture["tearDown"]){ fixture.tearDown(doh); }
+		tg.inFlight--;
+		if((!tg.inFlight)&&(tg.iterated)){
+			doh._groupFinished(groupName, !tg.failures);
+		}
+		doh._testFinished(groupName, fixture, def.results[0]);
+		if(doh._paused){
+			doh.run();
+		}
+	};
+
+	//Since these can take who knows how long, we don't want to timeout
+	//unless explicitly set
+	var timer;
+	var to = fixture.timeout;
+	if(to > 0) {
+		timer = doh.setTimeout(function(){
+			// ret.cancel();
+			// retEnd();
+			def.errback(new Error("test timeout in "+fixture.name.toString()));
+		}, to);
+	}
+
+	//Set up the end calls to the test into the deferred we'll return.
+	def.addBoth(function(arg){
+		if(timer){
+			clearTimeout(timer);
+		}
+		retEnd();
+	});
+
+	//Okay, now set up the timing loop for the actual test.
+	//This is down as an async type test where there is a delay
+	//between each execution to allow for GC time, etc, so the GC
+	//has less impact on the tests.
+	var res = fixture.results;
+	res.trials = [];
+
+	//Try to figure out how many calls are needed to hit a particular threshold.
+	var itrDef = doh._calcTrialIterations(groupName, fixture);
+	itrDef.addErrback(function(err){
+		fixture.endTime = new Date();
+		def.errback(err);
+	});
+
+	//Blah, since tests can be deferred, the actual run has to be deferred until after
+	//we know how many iterations to run.  This is just plain ugly.
+	itrDef.addCallback(function(iterations){
+		if(iterations){
+			var countdown = fixture.trialIterations;
+			doh.debug("TIMING TEST: [" + fixture.name +
+					  "]\n\t\tITERATIONS PER TRIAL: " +
+					  iterations + "\n\tTRIALS: " +
+					  countdown);
+
+			//Figure out how many times we want to run our 'trial'.
+			//Where each trial consists of 'iterations' of the test.
+
+			var trialRunner = function() {
+				//Set up our function to execute a block of tests
+				var start = new Date();
+				var tTimer = new doh.Deferred();
+				var tCountdown = iterations;
+
+				var tState = {
+					countdown: iterations
+				};
+				var testRunner = function(state){
+					while(state){
+						try{
+							state.countdown--;
+							if(state.countdown){
+								var ret = fixture.runTest(doh);
+								if(ret instanceof doh.Deferred){
+									//Deferreds have to be handled async,
+									//otherwise we just keep looping.
+									var atState = {
+										countdown: state.countdown
+									};
+									ret.addCallback(function(){
+										testRunner(atState);
+									});
+									ret.addErrback(function(err) {
+										doh._handleFailure(groupName, fixture, err);
+										fixture.endTime = new Date();
+										def.errback(err);
+									});
+									state = null;
+								}
+							}else{
+								tTimer.callback(new Date());
+								state = null;
+							}
+						}catch(err){
+							fixture.endTime = new Date();
+							tTimer.errback(err);
+						}
+					}
+				};
+				tTimer.addCallback(function(end){
+					//Figure out the results and try to factor out function call costs.
+					var tResults = {
+						trial: (fixture.trialIterations - countdown),
+						testIterations: iterations,
+						executionTime: (end.getTime() - start.getTime()),
+						average: (end.getTime() - start.getTime())/iterations
+					};
+					res.trials.push(tResults);
+					doh.debug("\n\t\tTRIAL #: " +
+							  tResults.trial + "\n\tTIME: " +
+							  tResults.executionTime + "ms.\n\tAVG TEST TIME: " +
+							  (tResults.executionTime/tResults.testIterations) + "ms.");
+
+					//Okay, have we run all the trials yet?
+					countdown--;
+					if(countdown){
+						doh.setTimeout(trialRunner, fixture.trialDelay);
+					}else{
+						//Okay, we're done, lets compute some final performance results.
+						var t = res.trials;
+
+
+
+						//We're done.
+						fixture.endTime = new Date();
+						def.callback(true);
+					}
+				});
+				tTimer.addErrback(function(err){
+					fixture.endTime = new Date();
+					def.errback(err);
+				});
+				testRunner(tState);
+			};
+			trialRunner();
+		}
+	});
+
+	//Set for a pause, returned the deferred.
+	if(def.fired < 0){
+		doh.pause();
+	}
+	return def;
+};
+
+doh._calcTrialIterations =  function(/*String*/ groupName, /*Object*/ fixture){
+	//	summary:
+	//		This function determines the rough number of iterations to
+	//		use to reach a particular MS threshold.  This returns a deferred
+	//		since tests can theoretically by async.  Async tests aren't going to
+	//		give great perf #s, though.
+	//		The callback is passed the # of iterations to hit the requested
+	//		threshold.
+	//
+	//	fixture:
+	//		The test fixture we want to calculate iterations for.
+	var def = new doh.Deferred();
+	var calibrate = function () {
+		var testFunc = fixture.runTest;
+
+		//Set the initial state.  We have to do this as a loop instead
+		//of a recursive function.  Otherwise, it blows the call stack
+		//on some browsers.
+		var iState = {
+			start: new Date(),
+			curIter: 0,
+			iterations: 5
+		};
+		var handleIteration = function(state){
+			while(state){
+				if(state.curIter < state.iterations){
+					try{
+						var ret = testFunc(doh);
+						if(ret instanceof doh.Deferred){
+							var aState = {
+								start: state.start,
+								curIter: state.curIter + 1,
+								iterations: state.iterations
+							};
+							ret.addCallback(function(){
+								handleIteration(aState);
+							});
+							ret.addErrback(function(err) {
+								fixture.endTime = new Date();
+								def.errback(err);
+							});
+							state = null;
+						}else{
+							state.curIter++;
+						}
+					}catch(err){
+						fixture.endTime = new Date();
+						def.errback(err);
+						return;
+					}
+				}else{
+					var end = new Date();
+					var totalTime = (end.getTime() - state.start.getTime());
+					if(totalTime < fixture.trialDuration){
+						var nState = {
+							iterations: state.iterations * 2,
+							curIter: 0
+						}
+						state = null;
+						doh.setTimeout(function(){
+							nState.start = new Date();
+							handleIteration(nState);
+						}, 50);
+					}else{
+						var itrs = state.iterations;
+						doh.setTimeout(function(){def.callback(itrs)}, 50);
+						state = null;
+					}
+				}
+			}
+		};
+		handleIteration(iState);
+	};
+	doh.setTimeout(calibrate, 10);
+	return def;
+};
+
+doh._runRegFixture = function(/*String*/groupName, /*Object*/fixture){
+	//	summary:
+	//		Function to run a generic doh test.  These are not
+	//		specialized tests, like performance groups and such.
+	//
+	//	groupName:
+	//		The groupName of the test.
+	//	fixture:
+	//		The test fixture to execute.
+	var tg = this._groups[groupName];
+	fixture.startTime = new Date();
+	var ret = fixture.runTest(this);
+	fixture.endTime = new Date();
+	// if we get a deferred back from the test runner, we know we're
+	// gonna wait for an async result. It's up to the test code to trap
+	// errors and give us an errback or callback.
+	if(ret instanceof doh.Deferred){
+		tg.inFlight++;
+		ret.groupName = groupName;
+		ret.fixture = fixture;
+
+		ret.addErrback(function(err){
+			doh._handleFailure(groupName, fixture, err);
+		});
+
+		var retEnd = function(){
+			if(fixture["tearDown"]){ fixture.tearDown(doh); }
+			tg.inFlight--;
+			if((!tg.inFlight)&&(tg.iterated)){
+				doh._groupFinished(groupName, !tg.failures);
+			}
+			doh._testFinished(groupName, fixture, ret.results[0]);
+			if(doh._paused){
+				doh.run();
+			}
+		}
+
+		var timer = doh.setTimeout(function(){
+			// ret.cancel();
+			// retEnd();
+			ret.errback(new Error("test timeout in "+fixture.name.toString()));
+		}, fixture["timeout"]||1000);
+
+		ret.addBoth(function(arg){
+			clearTimeout(timer);
+			retEnd();
+		});
+		if(ret.fired < 0){
+			doh.pause();
+		}
+		return ret;
+	}
+};
+
+doh._runFixture = function(groupName, fixture){
+	var tg = this._groups[groupName];
+	this._testStarted(groupName, fixture);
+	var threw = false;
+	var err = null;
+	// run it, catching exceptions and reporting them
+	try{
+		// let doh reference "this.group.thinger..." which can be set by
+		// another test or group-level setUp function
+		fixture.group = tg;
+		// only execute the parts of the fixture we've got
+
+		if(fixture["setUp"]){ fixture.setUp(this); }
+		if(fixture["runTest"]){  // should we error out of a fixture doesn't have a runTest?
+			if(fixture.testType === "perf"){
+				//Always async deferred, so return it.
+				return doh._runPerfFixture(groupName, fixture);
+			}else{
+				//May or may not by async.
+				var ret = doh._runRegFixture(groupName, fixture);
+				if(ret){
+					return ret;
+				}
+			}
+		}
+		if(fixture["tearDown"]){ fixture.tearDown(this); }
+	}catch(e){
+		threw = true;
+		err = e;
+		if(!fixture.endTime){
+			fixture.endTime = new Date();
+		}
+	}
+	var d = new doh.Deferred();
+	doh.setTimeout(this.hitch(this, function(){
+		if(threw){
+			this._handleFailure(groupName, fixture, err);
+		}
+		this._testFinished(groupName, fixture, !threw);
+
+		if((!tg.inFlight)&&(tg.iterated)){
+			doh._groupFinished(groupName, !tg.failures);
+		}else if(tg.inFlight > 0){
+			doh.setTimeout(this.hitch(this, function(){
+				doh.runGroup(groupName); // , idx);
+			}), 100);
+			this._paused = true;
+		}
+		if(doh._paused){
+			doh.run();
+		}
+	}), 30);
+	doh.pause();
+	return d;
+}
+
+doh._testId = 0;
+doh.runGroup = function(/*String*/ groupName, /*Integer*/ idx){
+	// summary:
+	//		runs the specified test group
+
+	// the general structure of the algorithm is to run through the group's
+	// list of doh, checking before and after each of them to see if we're in
+	// a paused state. This can be caused by the test returning a deferred or
+	// the user hitting the pause button. In either case, we want to halt
+	// execution of the test until something external to us restarts it. This
+	// means we need to pickle off enough state to pick up where we left off.
+
+	// FIXME: need to make fixture execution async!!
+
+	var tg = this._groups[groupName];
+	if(tg.skip === true){ return; }
+	if(this._isArray(tg)){
+		if(idx<=tg.length){
+			if((!tg.inFlight)&&(tg.iterated == true)){
+				if(tg["tearDown"]){ tg.tearDown(this); }
+				doh._groupFinished(groupName, !tg.failures);
+				return;
+			}
+		}
+		if(!idx){
+			tg.inFlight = 0;
+			tg.iterated = false;
+			tg.failures = 0;
+		}
+		doh._groupStarted(groupName);
+		if(!idx){
+			this._setupGroupForRun(groupName, idx);
+			if(tg["setUp"]){ tg.setUp(this); }
+		}
+		for(var y=(idx||0); y<tg.length; y++){
+			if(this._paused){
+				this._currentTest = y;
+				// this.debug("PAUSED at:", tg[y].name, this._currentGroup, this._currentTest);
+				return;
+			}
+			doh._runFixture(groupName, tg[y]);
+			if(this._paused){
+				this._currentTest = y+1;
+				if(this._currentTest == tg.length){
+					tg.iterated = true;
+				}
+				// this.debug("PAUSED at:", tg[y].name, this._currentGroup, this._currentTest);
+				return;
+			}
+		}
+		tg.iterated = true;
+		if(!tg.inFlight){
+			if(tg["tearDown"]){ tg.tearDown(this); }
+			doh._groupFinished(groupName, !tg.failures);
+		}
+	}
+}
+
+doh._onEnd = function(){}
+
+doh._report = function(){
+	// summary:
+	//		a private method to be implemented/replaced by the "locally
+	//		appropriate" test runner
+
+	// this.debug("ERROR:");
+	// this.debug("\tNO REPORTING OUTPUT AVAILABLE.");
+	// this.debug("\tIMPLEMENT doh._report() IN YOUR TEST RUNNER");
+
+	this.debug(this._line);
+	this.debug("| TEST SUMMARY:");
+	this.debug(this._line);
+	this.debug("\t", this._testCount, "tests in", this._groupCount, "groups");
+	this.debug("\t", this._errorCount, "errors");
+	this.debug("\t", this._failureCount, "failures");
+}
+
+doh.togglePaused = function(){
+	this[(this._paused) ? "run" : "pause"]();
+}
+
+doh.pause = function(){
+	// summary:
+	//		halt test run. Can be resumed.
+	this._paused = true;
+}
+
+doh.run = function(){
+	// summary:
+	//		begins or resumes the test process.
+	// this.debug("STARTING");
+	this._paused = false;
+	var cg = this._currentGroup;
+	var ct = this._currentTest;
+	var found = false;
+	if(!cg){
+		this._init(); // we weren't paused
+		found = true;
+	}
+	this._currentGroup = null;
+	this._currentTest = null;
+
+	for(var x in this._groups){
+		if(
+			( (!found)&&(x == cg) )||( found )
+		){
+			if(this._paused){ return; }
+			this._currentGroup = x;
+			if(!found){
+				found = true;
+				this.runGroup(x, ct);
+			}else{
+				this.runGroup(x);
+			}
+			if(this._paused){ return; }
+		}
+	}
+	this._currentGroup = null;
+	this._currentTest = null;
+	this._paused = false;
+	this._onEnd();
+	this._report();
+}
+
+//Statistics functions to handle computing performance metrics.
+//Taken from dojox.math
+//	basic statistics
+doh.standardDeviation = function(/* Number[] */a){
+	//	summary:
+	//		Returns the standard deviation of the passed arguments.
+	return Math.sqrt(this.variance(a));	//	Number
+};
+
+doh.variance = function(/* Number[] */a){
+	//	summary:
+	//		Find the variance in the passed array of numbers.
+	var mean=0, squares=0;
+	dojo.forEach(a, function(item){
+		mean+=item;
+		squares+=Math.pow(item,2);
+	});
+	return (squares/a.length)-Math.pow(mean/a.length, 2);	//	Number
+};
+
+doh.mean = function(/* Number[] */a){
+	//	summary:
+	//		Returns the mean value in the passed array.
+	var t=0;
+	dojo.forEach(a, function(v){
+		t += v;
+	});
+	return t / Math.max(a.length, 1);	//	Number
+};
+
+doh.min = function(/* Number[] */a){
+	//	summary:
+	//		Returns the min value in the passed array.
+	return Math.min.apply(null, a);		//	Number
+};
+
+doh.max = function(/* Number[] */a){
+	//	summary:
+	//		Returns the max value in the passed array.
+	return Math.max.apply(null, a);		//	Number
+},
+
+doh.median= function(/* Number[] */a){
+	//	summary:
+	//		Returns the value closest to the middle from a sorted version of the passed array.
+	return a.slice(0).sort()[Math.ceil(a.length/2)-1];	//	Number
+},
+
+doh.mode = function(/* Number[] */a){
+	//	summary:
+	//		Returns the mode from the passed array (number that appears the most often).
+	//		This is not the most efficient method, since it requires a double scan, but
+	//		is ensures accuracy.
+	var o = {}, r = 0, m = Number.MIN_VALUE;
+	dojo.forEach(a, function(v){
+		(o[v]!==undefined)?o[v]++:o[v]=1;
+	});
+
+	//	we did the lookup map because we need the number that appears the most.
+	for(var p in o){
+		if(m < o[p]){
+			m = o[p], r = p;
+		}
+	}
+	return r;	//	Number
+};
+
+doh.average = function(/* Number [] */ a){
+	var i;
+	var s = 0;
+	for(i = 0; i < a.length; i++){
+		s += a[i];
+	}
+	return s/a.length;
+}
+
+tests = doh;
+
+if (typeof skipDohSetup === "undefined") {
+
+    (function(){
+            // scope protection
+            var x;
+            try{
+                    if(typeof dojo != "undefined"){
+                            dojo.platformRequire({
+                                    browser: ["doh._browserRunner"],
+                                    rhino: ["doh._rhinoRunner"],
+                                    spidermonkey: ["doh._rhinoRunner"]
+                            });
+                            try{
+                                    var _shouldRequire = dojo.isBrowser ? (dojo.global == dojo.global["parent"] || !Boolean(dojo.global.parent.doh) ) : true;
+                            }catch(e){
+                                    //can't access dojo.global.parent.doh, then we need to do require
+                                    _shouldRequire = true;
+                            }
+                            if(_shouldRequire){
+                                    if(dojo.isBrowser){
+                                            dojo.addOnLoad(function(){
+                                                    if (dojo.global.registerModulePath){
+                                                            dojo.forEach(dojo.global.registerModulePath, function(m){
+                                                                    dojo.registerModulePath(m[0], m[1]);
+                                                            });
+                                                    }
+                                                    if(dojo.byId("testList")){
+                                                            var _tm = ( (dojo.global.testModule && dojo.global.testModule.length) ? dojo.global.testModule : "dojo.tests.module");
+                                                            dojo.forEach(_tm.split(","), dojo.require, dojo);
+                                                            doh.setTimeout(function(){
+                                                                    doh.run();
+                                                            }, 500);
+                                                    }
+                                            });
+                                    }else{
+                                            // dojo.require("doh._base");
+                                    }
+                            }
+                    }else{
+                            if(typeof load == "function" &&
+                                    (typeof Packages == "function" || typeof Packages == "object")){
+                                    throw new Error();
+                            }else if(typeof load == "function"){
+                                    throw new Error();
+                            }
+
+                            if(this["document"]){
+                                    /*
+                                    // if we survived all of that, we're probably in a browser but
+                                    // don't have Dojo handy. Load _browserRunner.js using a
+                                    // document.write() call.
+
+                                    // find runner.js, load _browserRunner relative to it
+                                    var scripts = document.getElementsByTagName("script"), runnerFile;
+                                    for(x=0; x<scripts.length; x++){
+                                            var s = scripts[x].src;
+                                            if(s){
+                                                    if(!runnerFile && s.substr(s.length - 9) == "runner.js"){
+                                                            runnerFile = s;
+                                                    }else if(s.substr(s.length - 17) == "_browserRunner.js"){
+                                                            runnerFile = null;
+                                                            break;
+                                                    }
+                                            }
+                                    }
+                                    if(runnerFile){
+                                            document.write("<scri"+"pt src='" + runnerFile.substr(0, runnerFile.length - 9)
+                                                    + "_browserRunner.js' type='text/javascript'></scr"+"ipt>");
+                                    }
+                                    */
+                            }
+                    }
+            }catch(e){
+                    print("\n"+doh._line);
+                    print("The Dojo Unit Test Harness, $Rev: 20389 $");
+                    print("Copyright (c) 2009, The Dojo Foundation, All Rights Reserved");
+                    print(doh._line, "\n");
+
+                    try{
+                            var dojoUrl = "../../dojo/dojo.js";
+                            var testUrl = "";
+                            var testModule = "dojo.tests.module";
+                            var dohBase = "";
+                            for(x=0; x<arguments.length; x++){
+                                    if(arguments[x].indexOf("=") > 0){
+                                            var tp = arguments[x].split("=");
+                                            if(tp[0] == "dohBase"){
+                                                    dohBase = tp[1];
+                                                    //Convert slashes to unix style and make sure properly
+                                                    //ended.
+                                                    dohBase = dohBase.replace(/\\/g, "/");
+                                                    if(dohBase.charAt(dohBase.length - 1) != "/"){
+                                                            dohBase += "/";
+                                                    }
+                                            }
+                                            if(tp[0] == "dojoUrl"){
+                                                    dojoUrl = tp[1];
+                                            }
+                                            if(tp[0] == "testUrl"){
+                                                    testUrl = tp[1];
+                                            }
+                                            if(tp[0] == "testModule"){
+                                                    testModule = tp[1];
+                                            }
+                                    }
+                            }
+
+                            load(dohBase + "_rhinoRunner.js");
+
+                            if(dojoUrl.length){
+                                    if(!this["djConfig"]){
+                                            djConfig = {};
+                                    }
+                                    djConfig.baseUrl = dojoUrl.split("dojo.js")[0];
+                                    load(dojoUrl);
+                            }
+                            if(testUrl.length){
+                                    load(testUrl);
+                            }
+                            if(testModule.length){
+                                    dojo.forEach(testModule.split(","), dojo.require, dojo);
+                            }
+                    }catch(e){
+                            print("An exception occurred: " + e);
+                    }
+
+                    doh.run();
+            }
+    }).apply(this, typeof arguments != "undefined" ? arguments : [null]);
+}
diff --git a/tests/doh/runner.sh b/tests/doh/runner.sh
new file mode 100755
index 0000000..22ec076
--- /dev/null
+++ b/tests/doh/runner.sh
@@ -0,0 +1,3 @@
+#!/bin/sh
+
+java -jar ../../build/lib/rhino/js.jar runner.js "$@"
diff --git a/tests/doh/small_logo.png b/tests/doh/small_logo.png
new file mode 100644
index 0000000..2fda23c
Binary files /dev/null and b/tests/doh/small_logo.png differ
diff --git a/tests/named/lib.js b/tests/named/lib.js
new file mode 100644
index 0000000..293e74c
--- /dev/null
+++ b/tests/named/lib.js
@@ -0,0 +1,46 @@
+if (typeof define !== 'function') { var define = require('../../amdefine')(module) }
+
+define('sub/nested/d', function (require, exports, module) {
+    var c = require('../c'),
+        e = require('./e'),
+        // if sub/nested/other is not defined, look for a file called
+        // other.js in the current directory
+        other = require('./other');
+
+    return {
+        name: 'd',
+        e: e,
+        cName: c.name,
+        otherName: other.name
+    };
+});
+
+
+define('sub/nested/e', function (require, exports) {
+    exports.name = 'e';
+});
+
+define('b', {
+    name: 'b'
+});
+
+define('sub/c', function (require, exports, module) {
+
+    //A fake out, modify the exports, but still prefer the
+    //return value as the module value.
+    exports.name = 'badc';
+
+    return {
+        name: 'c'
+    };
+});
+
+define('lib', ['./b', './sub/nested/d'], function (b, d) {
+    return {
+        name: 'lib',
+        b: b,
+        d: d
+    };
+});
+
+module.exports = define.require('lib');
diff --git a/tests/named/named-tests.js b/tests/named/named-tests.js
new file mode 100644
index 0000000..c9d3903
--- /dev/null
+++ b/tests/named/named-tests.js
@@ -0,0 +1,16 @@
+doh.register(
+    "named",
+    [
+        function named(t){
+            var lib = require('./lib');
+
+            t.is('lib', lib.name);
+            t.is('b', lib.b.name);
+            t.is('d', lib.d.name);
+            t.is('c', lib.d.cName);
+            t.is('e', lib.d.e.name);
+        }
+    ]
+);
+
+doh.run();
diff --git a/tests/named/other.js b/tests/named/other.js
new file mode 100644
index 0000000..4a85a34
--- /dev/null
+++ b/tests/named/other.js
@@ -0,0 +1,9 @@
+if (typeof define !== 'function') { var define = require('../../amdefine')(module) }
+
+define('other', function (require, exports, module) {
+    return {
+        name: 'other'
+    };
+});
+
+module.exports = define.require('other');
diff --git a/tests/node_modules/amdefine.js b/tests/node_modules/amdefine.js
new file mode 100644
index 0000000..a84776f
--- /dev/null
+++ b/tests/node_modules/amdefine.js
@@ -0,0 +1,299 @@
+/** vim: et:ts=4:sw=4:sts=4
+ * @license amdefine 0.0.8 Copyright (c) 2011, The Dojo Foundation All Rights Reserved.
+ * Available via the MIT or new BSD license.
+ * see: http://github.com/jrburke/amdefine for details
+ */
+
+/*jslint node: true */
+/*global module, process */
+'use strict';
+
+/**
+ * Creates a define for node.
+ * @param {Object} module the "module" object that is defined by Node for the
+ * current module.
+ * @param {Function} [requireFn]. Node's require function for the current module.
+ * It only needs to be passed in Node versions before 0.5, when module.require
+ * did not exist.
+ * @returns {Function} a define function that is usable for the current node
+ * module.
+ */
+function amdefine(module, requireFn) {
+    'use strict';
+    var defineCache = {},
+        loaderCache = {},
+        alreadyCalled = false,
+        path = require('path'),
+        makeRequire, stringRequire;
+
+    /**
+     * Trims the . and .. from an array of path segments.
+     * It will keep a leading path segment if a .. will become
+     * the first path segment, to help with module name lookups,
+     * which act like paths, but can be remapped. But the end result,
+     * all paths that use this function should look normalized.
+     * NOTE: this method MODIFIES the input array.
+     * @param {Array} ary the array of path segments.
+     */
+    function trimDots(ary) {
+        var i, part;
+        for (i = 0; ary[i]; i+= 1) {
+            part = ary[i];
+            if (part === '.') {
+                ary.splice(i, 1);
+                i -= 1;
+            } else if (part === '..') {
+                if (i === 1 && (ary[2] === '..' || ary[0] === '..')) {
+                    //End of the line. Keep at least one non-dot
+                    //path segment at the front so it can be mapped
+                    //correctly to disk. Otherwise, there is likely
+                    //no path mapping for a path starting with '..'.
+                    //This can still fail, but catches the most reasonable
+                    //uses of ..
+                    break;
+                } else if (i > 0) {
+                    ary.splice(i - 1, 2);
+                    i -= 2;
+                }
+            }
+        }
+    }
+
+    function normalize(name, baseName) {
+        var baseParts;
+
+        //Adjust any relative paths.
+        if (name && name.charAt(0) === '.') {
+            //If have a base name, try to normalize against it,
+            //otherwise, assume it is a top-level require that will
+            //be relative to baseUrl in the end.
+            if (baseName) {
+                baseParts = baseName.split('/');
+                baseParts = baseParts.slice(0, baseParts.length - 1);
+                baseParts = baseParts.concat(name.split('/'));
+                trimDots(baseParts);
+                name = baseParts.join('/');
+            }
+        }
+
+        return name;
+    }
+
+    /**
+     * Create the normalize() function passed to a loader plugin's
+     * normalize method.
+     */
+    function makeNormalize(relName) {
+        return function (name) {
+            return normalize(name, relName);
+        };
+    }
+
+    function makeLoad(id) {
+        function load(value) {
+            loaderCache[id] = value;
+        }
+
+        load.fromText = function (id, text) {
+            //This one is difficult because the text can/probably uses
+            //define, and any relative paths and requires should be relative
+            //to that id was it would be found on disk. But this would require
+            //bootstrapping a module/require fairly deeply from node core.
+            //Not sure how best to go about that yet.
+            throw new Error('amdefine does not implement load.fromText');
+        };
+
+        return load;
+    }
+
+    makeRequire = function (systemRequire, exports, module, relId) {
+        function amdRequire(deps, callback) {
+            if (typeof deps === 'string') {
+                //Synchronous, single module require('')
+                return stringRequire(systemRequire, exports, module, deps, relId);
+            } else {
+                //Array of dependencies with a callback.
+
+                //Convert the dependencies to modules.
+                deps = deps.map(function (depName) {
+                    return stringRequire(systemRequire, exports, module, depName, relId);
+                });
+
+                //Wait for next tick to call back the require call.
+                process.nextTick(function () {
+                    callback.apply(null, deps);
+                });
+            }
+        }
+
+        amdRequire.toUrl = function (filePath) {
+            if (filePath.indexOf('.') === 0) {
+                return normalize(filePath, path.dirname(module.filename));
+            } else {
+                return filePath;
+            }
+        };
+
+        return amdRequire;
+    };
+
+    //Favor explicit value, passed in if the module wants to support Node 0.4.
+    requireFn = requireFn || function req() {
+        return module.require.apply(module, arguments);
+    };
+
+    function runFactory(id, deps, factory) {
+        var r, e, m, result;
+
+        if (id) {
+            e = loaderCache[id] = {};
+            m = {
+                id: id,
+                uri: __filename,
+                exports: e
+            };
+            r = makeRequire(requireFn, e, m, id);
+        } else {
+            //Only support one define call per file
+            if (alreadyCalled) {
+                throw new Error('amdefine with no module ID cannot be called more than once per file.');
+            }
+            alreadyCalled = true;
+
+            //Use the real variables from node
+            //Use module.exports for exports, since
+            //the exports in here is amdefine exports.
+            e = module.exports;
+            m = module;
+            r = makeRequire(requireFn, e, m, module.id);
+        }
+
+        //If there are dependencies, they are strings, so need
+        //to convert them to dependency values.
+        if (deps) {
+            deps = deps.map(function (depName) {
+                return r(depName);
+            });
+        }
+
+        //Call the factory with the right dependencies.
+        if (typeof factory === 'function') {
+            result = factory.apply(m.exports, deps);
+        } else {
+            result = factory;
+        }
+
+        if (result !== undefined) {
+            m.exports = result;
+            if (id) {
+                loaderCache[id] = m.exports;
+            }
+        }
+    }
+
+    stringRequire = function (systemRequire, exports, module, id, relId) {
+        //Split the ID by a ! so that
+        var index = id.indexOf('!'),
+            originalId = id,
+            prefix, plugin;
+
+        if (index === -1) {
+            id = normalize(id, relId);
+
+            //Straight module lookup. If it is one of the special dependencies,
+            //deal with it, otherwise, delegate to node.
+            if (id === 'require') {
+                return makeRequire(systemRequire, exports, module, relId);
+            } else if (id === 'exports') {
+                return exports;
+            } else if (id === 'module') {
+                return module;
+            } else if (loaderCache.hasOwnProperty(id)) {
+                return loaderCache[id];
+            } else if (defineCache[id]) {
+                runFactory.apply(null, defineCache[id]);
+                return loaderCache[id];
+            } else {
+                if(systemRequire) {
+                    return systemRequire(originalId);
+                } else {
+                    throw new Error('No module with ID: ' + id);
+                }
+            }
+        } else {
+            //There is a plugin in play.
+            prefix = id.substring(0, index);
+            id = id.substring(index + 1, id.length);
+
+            plugin = stringRequire(systemRequire, exports, module, prefix, relId);
+
+            if (plugin.normalize) {
+                id = plugin.normalize(id, makeNormalize(relId));
+            } else {
+                //Normalize the ID normally.
+                id = normalize(id, relId);
+            }
+
+            if (loaderCache[id]) {
+                return loaderCache[id];
+            } else {
+                plugin.load(id, makeRequire(systemRequire, exports, module, relId), makeLoad(id), {});
+
+                return loaderCache[id];
+            }
+        }
+    };
+
+    //Create a define function specific to the module asking for amdefine.
+    function define(id, deps, factory) {
+        if (Array.isArray(id)) {
+            factory = deps;
+            deps = id;
+            id = undefined;
+        } else if (typeof id !== 'string') {
+            factory = id;
+            id = deps = undefined;
+        }
+
+        if (deps && !Array.isArray(deps)) {
+            factory = deps;
+            deps = undefined;
+        }
+
+        if (!deps) {
+            deps = ['require', 'exports', 'module'];
+        }
+
+        //Set up properties for this module. If an ID, then use
+        //internal cache. If no ID, then use the external variables
+        //for this node module.
+        if (id) {
+            //Put the module in deep freeze until there is a
+            //require call for it.
+            defineCache[id] = [id, deps, factory];
+        } else {
+            runFactory(id, deps, factory);
+        }
+    }
+
+    //define.require, which has access to all the values in the
+    //cache. Useful for AMD modules that all have IDs in the file,
+    //but need to finally export a value to node based on one of those
+    //IDs.
+    define.require = function (id) {
+        if (loaderCache[id]) {
+            return loaderCache[id];
+        }
+
+        if (defineCache[id]) {
+            runFactory.apply(null, defineCache[id]);
+            return loaderCache[id];
+        }
+    };
+
+    define.amd = {};
+
+    return define;
+}
+
+module.exports = amdefine;
diff --git a/tests/plugins/coffeescript/coffeescript-tests.js b/tests/plugins/coffeescript/coffeescript-tests.js
new file mode 100644
index 0000000..acd9851
--- /dev/null
+++ b/tests/plugins/coffeescript/coffeescript-tests.js
@@ -0,0 +1,14 @@
+doh.register(
+    "coffeescript",
+    [
+        function coffeescript(t){
+            var main = require('./main');
+
+            t.is('regular', main.regular.name);
+            t.is('attach', main.controller.attach());
+            t.is('render', main.view.render());
+        }
+    ]
+);
+
+doh.run();
diff --git a/tests/plugins/coffeescript/controller.coffee b/tests/plugins/coffeescript/controller.coffee
new file mode 100644
index 0000000..4b16064
--- /dev/null
+++ b/tests/plugins/coffeescript/controller.coffee
@@ -0,0 +1,6 @@
+if typeof define isnt 'function'
+  define = (require('../../../amdefine'))(module)
+
+define ->
+  attach: () ->
+    return 'attach'
diff --git a/tests/plugins/coffeescript/cs.js b/tests/plugins/coffeescript/cs.js
new file mode 100644
index 0000000..429c4a3
--- /dev/null
+++ b/tests/plugins/coffeescript/cs.js
@@ -0,0 +1,4517 @@
+/**
+ * @license cs 0.3.1 Copyright (c) 2010-2011, The Dojo Foundation All Rights Reserved.
+ * Available via the MIT or new BSD license.
+ * see: http://github.com/jrburke/require-cs for details
+ *
+ * CoffeeScript is Copyright (c) 2011 Jeremy Ashkenas
+ * http://jashkenas.github.com/coffee-script/
+ * CoffeeScriptVersion: '1.1.2'
+ */
+
+if (typeof define !== 'function') { var define = (require('../../../amdefine'))(module); }
+
+/* Yes, deliciously evil. */
+/*jslint evil: true, strict: false, plusplus: false, regexp: false */
+/*global require: false, XMLHttpRequest: false, ActiveXObject: false,
+  define: false, process: false, window: false */
+
+(function () {
+
+//>>excludeStart('excludeCoffeeScript', pragmas.excludeCoffeeScript)
+
+    var fs, getXhr, CoffeeScript,
+        progIds = ['Msxml2.XMLHTTP', 'Microsoft.XMLHTTP', 'Msxml2.XMLHTTP.4.0'],
+        fetchText = function () {
+            throw new Error('Environment unsupported.');
+        },
+        buildMap = [];
+
+//START COFFEESCRIPT
+CoffeeScript = (function () {
+var __MODULES = {}; function require(name) { return __MODULES[name.substring(2)]; };
+(function () {
+var exports = __MODULES['helpers'] = {};
+(function() {
+  var extend, flatten;
+  exports.starts = function(string, literal, start) {
+    return literal === string.substr(start, literal.length);
+  };
+  exports.ends = function(string, literal, back) {
+    var len;
+    len = literal.length;
+    return literal === string.substr(string.length - len - (back || 0), len);
+  };
+  exports.compact = function(array) {
+    var item, _i, _len, _results;
+    _results = [];
+    for (_i = 0, _len = array.length; _i < _len; _i++) {
+      item = array[_i];
+      if (item) {
+        _results.push(item);
+      }
+    }
+    return _results;
+  };
+  exports.count = function(string, substr) {
+    var num, pos;
+    num = pos = 0;
+    if (!substr.length) {
+      return 1 / 0;
+    }
+    while (pos = 1 + string.indexOf(substr, pos)) {
+      num++;
+    }
+    return num;
+  };
+  exports.merge = function(options, overrides) {
+    return extend(extend({}, options), overrides);
+  };
+  extend = exports.extend = function(object, properties) {
+    var key, val;
+    for (key in properties) {
+      val = properties[key];
+      object[key] = val;
+    }
+    return object;
+  };
+  exports.flatten = flatten = function(array) {
+    var element, flattened, _i, _len;
+    flattened = [];
+    for (_i = 0, _len = array.length; _i < _len; _i++) {
+      element = array[_i];
+      if (element instanceof Array) {
+        flattened = flattened.concat(flatten(element));
+      } else {
+        flattened.push(element);
+      }
+    }
+    return flattened;
+  };
+  exports.del = function(obj, key) {
+    var val;
+    val = obj[key];
+    delete obj[key];
+    return val;
+  };
+  exports.last = function(array, back) {
+    return array[array.length - (back || 0) - 1];
+  };
+}).call(this);
+return exports;
+}());(function () {
+var exports = __MODULES['rewriter'] = {};
+(function() {
+  var BALANCED_PAIRS, EXPRESSION_CLOSE, EXPRESSION_END, EXPRESSION_START, IMPLICIT_BLOCK, IMPLICIT_CALL, IMPLICIT_END, IMPLICIT_FUNC, IMPLICIT_UNSPACED_CALL, INVERSES, LINEBREAKS, SINGLE_CLOSERS, SINGLE_LINERS, left, rite, _i, _len, _ref;
+  var __indexOf = Array.prototype.indexOf || function(item) {
+    for (var i = 0, l = this.length; i < l; i++) {
+      if (this[i] === item) return i;
+    }
+    return -1;
+  }, __slice = Array.prototype.slice;
+  exports.Rewriter = (function() {
+    function Rewriter() {}
+    Rewriter.prototype.rewrite = function(tokens) {
+      this.tokens = tokens;
+      this.removeLeadingNewlines();
+      this.removeMidExpressionNewlines();
+      this.closeOpenCalls();
+      this.closeOpenIndexes();
+      this.addImplicitIndentation();
+      this.tagPostfixConditionals();
+      this.addImplicitBraces();
+      this.addImplicitParentheses();
+      this.ensureBalance(BALANCED_PAIRS);
+      this.rewriteClosingParens();
+      return this.tokens;
+    };
+    Rewriter.prototype.scanTokens = function(block) {
+      var i, token, tokens;
+      tokens = this.tokens;
+      i = 0;
+      while (token = tokens[i]) {
+        i += block.call(this, token, i, tokens);
+      }
+      return true;
+    };
+    Rewriter.prototype.detectEnd = function(i, condition, action) {
+      var levels, token, tokens, _ref, _ref2;
+      tokens = this.tokens;
+      levels = 0;
+      while (token = tokens[i]) {
+        if (levels === 0 && condition.call(this, token, i)) {
+          return action.call(this, token, i);
+        }
+        if (!token || levels < 0) {
+          return action.call(this, token, i - 1);
+        }
+        if (_ref = token[0], __indexOf.call(EXPRESSION_START, _ref) >= 0) {
+          levels += 1;
+        } else if (_ref2 = token[0], __indexOf.call(EXPRESSION_END, _ref2) >= 0) {
+          levels -= 1;
+        }
+        i += 1;
+      }
+      return i - 1;
+    };
+    Rewriter.prototype.removeLeadingNewlines = function() {
+      var i, tag, _len, _ref;
+      _ref = this.tokens;
+      for (i = 0, _len = _ref.length; i < _len; i++) {
+        tag = _ref[i][0];
+        if (tag !== 'TERMINATOR') {
+          break;
+        }
+      }
+      if (i) {
+        return this.tokens.splice(0, i);
+      }
+    };
+    Rewriter.prototype.removeMidExpressionNewlines = function() {
+      return this.scanTokens(function(token, i, tokens) {
+        var _ref;
+        if (!(token[0] === 'TERMINATOR' && (_ref = this.tag(i + 1), __indexOf.call(EXPRESSION_CLOSE, _ref) >= 0))) {
+          return 1;
+        }
+        tokens.splice(i, 1);
+        return 0;
+      });
+    };
+    Rewriter.prototype.closeOpenCalls = function() {
+      var action, condition;
+      condition = function(token, i) {
+        var _ref;
+        return ((_ref = token[0]) === ')' || _ref === 'CALL_END') || token[0] === 'OUTDENT' && this.tag(i - 1) === ')';
+      };
+      action = function(token, i) {
+        return this.tokens[token[0] === 'OUTDENT' ? i - 1 : i][0] = 'CALL_END';
+      };
+      return this.scanTokens(function(token, i) {
+        if (token[0] === 'CALL_START') {
+          this.detectEnd(i + 1, condition, action);
+        }
+        return 1;
+      });
+    };
+    Rewriter.prototype.closeOpenIndexes = function() {
+      var action, condition;
+      condition = function(token, i) {
+        var _ref;
+        return (_ref = token[0]) === ']' || _ref === 'INDEX_END';
+      };
+      action = function(token, i) {
+        return token[0] = 'INDEX_END';
+      };
+      return this.scanTokens(function(token, i) {
+        if (token[0] === 'INDEX_START') {
+          this.detectEnd(i + 1, condition, action);
+        }
+        return 1;
+      });
+    };
+    Rewriter.prototype.addImplicitBraces = function() {
+      var action, condition, stack, start, startIndent;
+      stack = [];
+      start = null;
+      startIndent = 0;
+      condition = function(token, i) {
+        var one, tag, three, two, _ref, _ref2;
+        _ref = this.tokens.slice(i + 1, (i + 3 + 1) || 9e9), one = _ref[0], two = _ref[1], three = _ref[2];
+        if ('HERECOMMENT' === (one != null ? one[0] : void 0)) {
+          return false;
+        }
+        tag = token[0];
+        return ((tag === 'TERMINATOR' || tag === 'OUTDENT') && !((two != null ? two[0] : void 0) === ':' || (one != null ? one[0] : void 0) === '@' && (three != null ? three[0] : void 0) === ':')) || (tag === ',' && one && ((_ref2 = one[0]) !== 'IDENTIFIER' && _ref2 !== 'NUMBER' && _ref2 !== 'STRING' && _ref2 !== '@' && _ref2 !== 'TERMINATOR' && _ref2 !== 'OUTDENT'));
+      };
+      action = function(token, i) {
+        var tok;
+        tok = ['}', '}', token[2]];
+        tok.generated = true;
+        return this.tokens.splice(i, 0, tok);
+      };
+      return this.scanTokens(function(token, i, tokens) {
+        var ago, idx, tag, tok, value, _ref, _ref2;
+        if (_ref = (tag = token[0]), __indexOf.call(EXPRESSION_START, _ref) >= 0) {
+          stack.push([(tag === 'INDENT' && this.tag(i - 1) === '{' ? '{' : tag), i]);
+          return 1;
+        }
+        if (__indexOf.call(EXPRESSION_END, tag) >= 0) {
+          start = stack.pop();
+          return 1;
+        }
+        if (!(tag === ':' && ((ago = this.tag(i - 2)) === ':' || ((_ref2 = stack[stack.length - 1]) != null ? _ref2[0] : void 0) !== '{'))) {
+          return 1;
+        }
+        stack.push(['{']);
+        idx = ago === '@' ? i - 2 : i - 1;
+        while (this.tag(idx - 2) === 'HERECOMMENT') {
+          idx -= 2;
+        }
+        value = new String('{');
+        value.generated = true;
+        tok = ['{', value, token[2]];
+        tok.generated = true;
+        tokens.splice(idx, 0, tok);
+        this.detectEnd(i + 2, condition, action);
+        return 2;
+      });
+    };
+    Rewriter.prototype.addImplicitParentheses = function() {
+      var action, noCall;
+      noCall = false;
+      action = function(token, i) {
+        var idx;
+        idx = token[0] === 'OUTDENT' ? i + 1 : i;
+        return this.tokens.splice(idx, 0, ['CALL_END', ')', token[2]]);
+      };
+      return this.scanTokens(function(token, i, tokens) {
+        var callObject, current, next, prev, seenControl, seenSingle, tag, _ref, _ref2, _ref3;
+        tag = token[0];
+        if (tag === 'CLASS' || tag === 'IF') {
+          noCall = true;
+        }
+        _ref = tokens.slice(i - 1, (i + 1 + 1) || 9e9), prev = _ref[0], current = _ref[1], next = _ref[2];
+        callObject = !noCall && tag === 'INDENT' && next && next.generated && next[0] === '{' && prev && (_ref2 = prev[0], __indexOf.call(IMPLICIT_FUNC, _ref2) >= 0);
+        seenSingle = false;
+        seenControl = false;
+        if (__indexOf.call(LINEBREAKS, tag) >= 0) {
+          noCall = false;
+        }
+        if (prev && !prev.spaced && tag === '?') {
+          token.call = true;
+        }
+        if (token.fromThen) {
+          return 1;
+        }
+        if (!(callObject || (prev != null ? prev.spaced : void 0) && (prev.call || (_ref3 = prev[0], __indexOf.call(IMPLICIT_FUNC, _ref3) >= 0)) && (__indexOf.call(IMPLICIT_CALL, tag) >= 0 || !(token.spaced || token.newLine) && __indexOf.call(IMPLICIT_UNSPACED_CALL, tag) >= 0))) {
+          return 1;
+        }
+        tokens.splice(i, 0, ['CALL_START', '(', token[2]]);
+        this.detectEnd(i + 1, function(token, i) {
+          var post, _ref4;
+          tag = token[0];
+          if (!seenSingle && token.fromThen) {
+            return true;
+          }
+          if (tag === 'IF' || tag === 'ELSE' || tag === 'CATCH' || tag === '->' || tag === '=>') {
+            seenSingle = true;
+          }
+          if (tag === 'IF' || tag === 'ELSE' || tag === 'SWITCH' || tag === 'TRY') {
+            seenControl = true;
+          }
+          if ((tag === '.' || tag === '?.' || tag === '::') && this.tag(i - 1) === 'OUTDENT') {
+            return true;
+          }
+          return !token.generated && this.tag(i - 1) !== ',' && (__indexOf.call(IMPLICIT_END, tag) >= 0 || (tag === 'INDENT' && !seenControl)) && (tag !== 'INDENT' || (this.tag(i - 2) !== 'CLASS' && (_ref4 = this.tag(i - 1), __indexOf.call(IMPLICIT_BLOCK, _ref4) < 0) && !((post = this.tokens[i + 1]) && post.generated && post[0] === '{')));
+        }, action);
+        if (prev[0] === '?') {
+          prev[0] = 'FUNC_EXIST';
+        }
+        return 2;
+      });
+    };
+    Rewriter.prototype.addImplicitIndentation = function() {
+      return this.scanTokens(function(token, i, tokens) {
+        var action, condition, indent, outdent, starter, tag, _ref, _ref2;
+        tag = token[0];
+        if (tag === 'TERMINATOR' && this.tag(i + 1) === 'THEN') {
+          tokens.splice(i, 1);
+          return 0;
+        }
+        if (tag === 'ELSE' && this.tag(i - 1) !== 'OUTDENT') {
+          tokens.splice.apply(tokens, [i, 0].concat(__slice.call(this.indentation(token))));
+          return 2;
+        }
+        if (tag === 'CATCH' && ((_ref = this.tag(i + 2)) === 'OUTDENT' || _ref === 'TERMINATOR' || _ref === 'FINALLY')) {
+          tokens.splice.apply(tokens, [i + 2, 0].concat(__slice.call(this.indentation(token))));
+          return 4;
+        }
+        if (__indexOf.call(SINGLE_LINERS, tag) >= 0 && this.tag(i + 1) !== 'INDENT' && !(tag === 'ELSE' && this.tag(i + 1) === 'IF')) {
+          starter = tag;
+          _ref2 = this.indentation(token), indent = _ref2[0], outdent = _ref2[1];
+          if (starter === 'THEN') {
+            indent.fromThen = true;
+          }
+          indent.generated = outdent.generated = true;
+          tokens.splice(i + 1, 0, indent);
+          condition = function(token, i) {
+            var _ref3;
+            return token[1] !== ';' && (_ref3 = token[0], __indexOf.call(SINGLE_CLOSERS, _ref3) >= 0) && !(token[0] === 'ELSE' && (starter !== 'IF' && starter !== 'THEN'));
+          };
+          action = function(token, i) {
+            return this.tokens.splice((this.tag(i - 1) === ',' ? i - 1 : i), 0, outdent);
+          };
+          this.detectEnd(i + 2, condition, action);
+          if (tag === 'THEN') {
+            tokens.splice(i, 1);
+          }
+          return 1;
+        }
+        return 1;
+      });
+    };
+    Rewriter.prototype.tagPostfixConditionals = function() {
+      var condition;
+      condition = function(token, i) {
+        var _ref;
+        return (_ref = token[0]) === 'TERMINATOR' || _ref === 'INDENT';
+      };
+      return this.scanTokens(function(token, i) {
+        var original;
+        if (token[0] !== 'IF') {
+          return 1;
+        }
+        original = token;
+        this.detectEnd(i + 1, condition, function(token, i) {
+          if (token[0] !== 'INDENT') {
+            return original[0] = 'POST_' + original[0];
+          }
+        });
+        return 1;
+      });
+    };
+    Rewriter.prototype.ensureBalance = function(pairs) {
+      var close, level, levels, open, openLine, tag, token, _i, _j, _len, _len2, _ref, _ref2;
+      levels = {};
+      openLine = {};
+      _ref = this.tokens;
+      for (_i = 0, _len = _ref.length; _i < _len; _i++) {
+        token = _ref[_i];
+        tag = token[0];
+        for (_j = 0, _len2 = pairs.length; _j < _len2; _j++) {
+          _ref2 = pairs[_j], open = _ref2[0], close = _ref2[1];
+          levels[open] |= 0;
+          if (tag === open) {
+            if (levels[open]++ === 0) {
+              openLine[open] = token[2];
+            }
+          } else if (tag === close && --levels[open] < 0) {
+            throw Error("too many " + token[1] + " on line " + (token[2] + 1));
+          }
+        }
+      }
+      for (open in levels) {
+        level = levels[open];
+        if (level > 0) {
+          throw Error("unclosed " + open + " on line " + (openLine[open] + 1));
+        }
+      }
+      return this;
+    };
+    Rewriter.prototype.rewriteClosingParens = function() {
+      var debt, key, stack;
+      stack = [];
+      debt = {};
+      for (key in INVERSES) {
+        debt[key] = 0;
+      }
+      return this.scanTokens(function(token, i, tokens) {
+        var inv, match, mtag, oppos, tag, val, _ref;
+        if (_ref = (tag = token[0]), __indexOf.call(EXPRESSION_START, _ref) >= 0) {
+          stack.push(token);
+          return 1;
+        }
+        if (__indexOf.call(EXPRESSION_END, tag) < 0) {
+          return 1;
+        }
+        if (debt[inv = INVERSES[tag]] > 0) {
+          debt[inv] -= 1;
+          tokens.splice(i, 1);
+          return 0;
+        }
+        match = stack.pop();
+        mtag = match[0];
+        oppos = INVERSES[mtag];
+        if (tag === oppos) {
+          return 1;
+        }
+        debt[mtag] += 1;
+        val = [oppos, mtag === 'INDENT' ? match[1] : oppos];
+        if (this.tag(i + 2) === mtag) {
+          tokens.splice(i + 3, 0, val);
+          stack.push(match);
+        } else {
+          tokens.splice(i, 0, val);
+        }
+        return 1;
+      });
+    };
+    Rewriter.prototype.indentation = function(token) {
+      return [['INDENT', 2, token[2]], ['OUTDENT', 2, token[2]]];
+    };
+    Rewriter.prototype.tag = function(i) {
+      var _ref;
+      return (_ref = this.tokens[i]) != null ? _ref[0] : void 0;
+    };
+    return Rewriter;
+  })();
+  BALANCED_PAIRS = [['(', ')'], ['[', ']'], ['{', '}'], ['INDENT', 'OUTDENT'], ['CALL_START', 'CALL_END'], ['PARAM_START', 'PARAM_END'], ['INDEX_START', 'INDEX_END']];
+  INVERSES = {};
+  EXPRESSION_START = [];
+  EXPRESSION_END = [];
+  for (_i = 0, _len = BALANCED_PAIRS.length; _i < _len; _i++) {
+    _ref = BALANCED_PAIRS[_i], left = _ref[0], rite = _ref[1];
+    EXPRESSION_START.push(INVERSES[rite] = left);
+    EXPRESSION_END.push(INVERSES[left] = rite);
+  }
+  EXPRESSION_CLOSE = ['CATCH', 'WHEN', 'ELSE', 'FINALLY'].concat(EXPRESSION_END);
+  IMPLICIT_FUNC = ['IDENTIFIER', 'SUPER', ')', 'CALL_END', ']', 'INDEX_END', '@', 'THIS'];
+  IMPLICIT_CALL = ['IDENTIFIER', 'NUMBER', 'STRING', 'JS', 'REGEX', 'NEW', 'PARAM_START', 'CLASS', 'IF', 'TRY', 'SWITCH', 'THIS', 'BOOL', 'UNARY', 'SUPER', '@', '->', '=>', '[', '(', '{', '--', '++'];
+  IMPLICIT_UNSPACED_CALL = ['+', '-'];
+  IMPLICIT_BLOCK = ['->', '=>', '{', '[', ','];
+  IMPLICIT_END = ['POST_IF', 'FOR', 'WHILE', 'UNTIL', 'WHEN', 'BY', 'LOOP', 'TERMINATOR'];
+  SINGLE_LINERS = ['ELSE', '->', '=>', 'TRY', 'FINALLY', 'THEN'];
+  SINGLE_CLOSERS = ['TERMINATOR', 'CATCH', 'FINALLY', 'ELSE', 'OUTDENT', 'LEADING_WHEN'];
+  LINEBREAKS = ['TERMINATOR', 'INDENT', 'OUTDENT'];
+}).call(this);
+return exports;
+}());(function () {
+var exports = __MODULES['lexer'] = {};
+(function() {
+  var ASSIGNED, BOOL, CALLABLE, CODE, COFFEE_ALIASES, COFFEE_ALIAS_MAP, COFFEE_KEYWORDS, COMMENT, COMPARE, COMPOUND_ASSIGN, HEREDOC, HEREDOC_ILLEGAL, HEREDOC_INDENT, HEREGEX, HEREGEX_OMIT, IDENTIFIER, INDEXABLE, JSTOKEN, JS_FORBIDDEN, JS_KEYWORDS, LINE_BREAK, LINE_CONTINUER, LOGIC, Lexer, MATH, MULTILINER, MULTI_DENT, NOT_REGEX, NOT_SPACED_REGEX, NO_NEWLINE, NUMBER, OPERATOR, REGEX, RELATION, RESERVED, Rewriter, SHIFT, SIMPLESTR, TRAILING_SPACES, UNARY, WHITESPACE, compact, count, key, l [...]
+  var __indexOf = Array.prototype.indexOf || function(item) {
+    for (var i = 0, l = this.length; i < l; i++) {
+      if (this[i] === item) return i;
+    }
+    return -1;
+  };
+  Rewriter = require('./rewriter').Rewriter;
+  _ref = require('./helpers'), count = _ref.count, starts = _ref.starts, compact = _ref.compact, last = _ref.last;
+  exports.Lexer = Lexer = (function() {
+    function Lexer() {}
+    Lexer.prototype.tokenize = function(code, opts) {
+      var i;
+      if (opts == null) {
+        opts = {};
+      }
+      if (WHITESPACE.test(code)) {
+        code = "\n" + code;
+      }
+      code = code.replace(/\r/g, '').replace(TRAILING_SPACES, '');
+      this.code = code;
+      this.line = opts.line || 0;
+      this.indent = 0;
+      this.indebt = 0;
+      this.outdebt = 0;
+      this.indents = [];
+      this.tokens = [];
+      i = 0;
+      while (this.chunk = code.slice(i)) {
+        i += this.identifierToken() || this.commentToken() || this.whitespaceToken() || this.lineToken() || this.heredocToken() || this.stringToken() || this.numberToken() || this.regexToken() || this.jsToken() || this.literalToken();
+      }
+      this.closeIndentation();
+      if (opts.rewrite === false) {
+        return this.tokens;
+      }
+      return (new Rewriter).rewrite(this.tokens);
+    };
+    Lexer.prototype.identifierToken = function() {
+      var colon, forcedIdentifier, id, input, match, prev, tag, _ref2, _ref3;
+      if (!(match = IDENTIFIER.exec(this.chunk))) {
+        return 0;
+      }
+      input = match[0], id = match[1], colon = match[2];
+      if (id === 'own' && this.tag() === 'FOR') {
+        this.token('OWN', id);
+        return id.length;
+      }
+      forcedIdentifier = colon || (prev = last(this.tokens)) && (((_ref2 = prev[0]) === '.' || _ref2 === '?.' || _ref2 === '::') || !prev.spaced && prev[0] === '@');
+      tag = 'IDENTIFIER';
+      if (!forcedIdentifier && (__indexOf.call(JS_KEYWORDS, id) >= 0 || __indexOf.call(COFFEE_KEYWORDS, id) >= 0)) {
+        tag = id.toUpperCase();
+        if (tag === 'WHEN' && (_ref3 = this.tag(), __indexOf.call(LINE_BREAK, _ref3) >= 0)) {
+          tag = 'LEADING_WHEN';
+        } else if (tag === 'FOR') {
+          this.seenFor = true;
+        } else if (tag === 'UNLESS') {
+          tag = 'IF';
+        } else if (__indexOf.call(UNARY, tag) >= 0) {
+          tag = 'UNARY';
+        } else if (__indexOf.call(RELATION, tag) >= 0) {
+          if (tag !== 'INSTANCEOF' && this.seenFor) {
+            tag = 'FOR' + tag;
+            this.seenFor = false;
+          } else {
+            tag = 'RELATION';
+            if (this.value() === '!') {
+              this.tokens.pop();
+              id = '!' + id;
+            }
+          }
+        }
+      }
+      if (__indexOf.call(JS_FORBIDDEN, id) >= 0) {
+        if (forcedIdentifier) {
+          tag = 'IDENTIFIER';
+          id = new String(id);
+          id.reserved = true;
+        } else if (__indexOf.call(RESERVED, id) >= 0) {
+          this.identifierError(id);
+        }
+      }
+      if (!forcedIdentifier) {
+        if (__indexOf.call(COFFEE_ALIASES, id) >= 0) {
+          id = COFFEE_ALIAS_MAP[id];
+        }
+        tag = (function() {
+          switch (id) {
+            case '!':
+              return 'UNARY';
+            case '==':
+            case '!=':
+              return 'COMPARE';
+            case '&&':
+            case '||':
+              return 'LOGIC';
+            case 'true':
+            case 'false':
+            case 'null':
+            case 'undefined':
+              return 'BOOL';
+            case 'break':
+            case 'continue':
+            case 'debugger':
+              return 'STATEMENT';
+            default:
+              return tag;
+          }
+        })();
+      }
+      this.token(tag, id);
+      if (colon) {
+        this.token(':', ':');
+      }
+      return input.length;
+    };
+    Lexer.prototype.numberToken = function() {
+      var match, number;
+      if (!(match = NUMBER.exec(this.chunk))) {
+        return 0;
+      }
+      number = match[0];
+      this.token('NUMBER', number);
+      return number.length;
+    };
+    Lexer.prototype.stringToken = function() {
+      var match, string;
+      switch (this.chunk.charAt(0)) {
+        case "'":
+          if (!(match = SIMPLESTR.exec(this.chunk))) {
+            return 0;
+          }
+          this.token('STRING', (string = match[0]).replace(MULTILINER, '\\\n'));
+          break;
+        case '"':
+          if (!(string = this.balancedString(this.chunk, '"'))) {
+            return 0;
+          }
+          if (0 < string.indexOf('#{', 1)) {
+            this.interpolateString(string.slice(1, -1));
+          } else {
+            this.token('STRING', this.escapeLines(string));
+          }
+          break;
+        default:
+          return 0;
+      }
+      this.line += count(string, '\n');
+      return string.length;
+    };
+    Lexer.prototype.heredocToken = function() {
+      var doc, heredoc, match, quote;
+      if (!(match = HEREDOC.exec(this.chunk))) {
+        return 0;
+      }
+      heredoc = match[0];
+      quote = heredoc.charAt(0);
+      doc = this.sanitizeHeredoc(match[2], {
+        quote: quote,
+        indent: null
+      });
+      if (quote === '"' && 0 <= doc.indexOf('#{')) {
+        this.interpolateString(doc, {
+          heredoc: true
+        });
+      } else {
+        this.token('STRING', this.makeString(doc, quote, true));
+      }
+      this.line += count(heredoc, '\n');
+      return heredoc.length;
+    };
+    Lexer.prototype.commentToken = function() {
+      var comment, here, match;
+      if (!(match = this.chunk.match(COMMENT))) {
+        return 0;
+      }
+      comment = match[0], here = match[1];
+      if (here) {
+        this.token('HERECOMMENT', this.sanitizeHeredoc(here, {
+          herecomment: true,
+          indent: Array(this.indent + 1).join(' ')
+        }));
+        this.token('TERMINATOR', '\n');
+      }
+      this.line += count(comment, '\n');
+      return comment.length;
+    };
+    Lexer.prototype.jsToken = function() {
+      var match, script;
+      if (!(this.chunk.charAt(0) === '`' && (match = JSTOKEN.exec(this.chunk)))) {
+        return 0;
+      }
+      this.token('JS', (script = match[0]).slice(1, -1));
+      return script.length;
+    };
+    Lexer.prototype.regexToken = function() {
+      var length, match, prev, regex, _ref2;
+      if (this.chunk.charAt(0) !== '/') {
+        return 0;
+      }
+      if (match = HEREGEX.exec(this.chunk)) {
+        length = this.heregexToken(match);
+        this.line += count(match[0], '\n');
+        return length;
+      }
+      prev = last(this.tokens);
+      if (prev && (_ref2 = prev[0], __indexOf.call((prev.spaced ? NOT_REGEX : NOT_SPACED_REGEX), _ref2) >= 0)) {
+        return 0;
+      }
+      if (!(match = REGEX.exec(this.chunk))) {
+        return 0;
+      }
+      regex = match[0];
+      this.token('REGEX', regex === '//' ? '/(?:)/' : regex);
+      return regex.length;
+    };
+    Lexer.prototype.heregexToken = function(match) {
+      var body, flags, heregex, re, tag, tokens, value, _i, _len, _ref2, _ref3, _ref4, _ref5;
+      heregex = match[0], body = match[1], flags = match[2];
+      if (0 > body.indexOf('#{')) {
+        re = body.replace(HEREGEX_OMIT, '').replace(/\//g, '\\/');
+        this.token('REGEX', "/" + (re || '(?:)') + "/" + flags);
+        return heregex.length;
+      }
+      this.token('IDENTIFIER', 'RegExp');
+      this.tokens.push(['CALL_START', '(']);
+      tokens = [];
+      _ref2 = this.interpolateString(body, {
+        regex: true
+      });
+      for (_i = 0, _len = _ref2.length; _i < _len; _i++) {
+        _ref3 = _ref2[_i], tag = _ref3[0], value = _ref3[1];
+        if (tag === 'TOKENS') {
+          tokens.push.apply(tokens, value);
+        } else {
+          if (!(value = value.replace(HEREGEX_OMIT, ''))) {
+            continue;
+          }
+          value = value.replace(/\\/g, '\\\\');
+          tokens.push(['STRING', this.makeString(value, '"', true)]);
+        }
+        tokens.push(['+', '+']);
+      }
+      tokens.pop();
+      if (((_ref4 = tokens[0]) != null ? _ref4[0] : void 0) !== 'STRING') {
+        this.tokens.push(['STRING', '""'], ['+', '+']);
+      }
+      (_ref5 = this.tokens).push.apply(_ref5, tokens);
+      if (flags) {
+        this.tokens.push([',', ','], ['STRING', '"' + flags + '"']);
+      }
+      this.token(')', ')');
+      return heregex.length;
+    };
+    Lexer.prototype.lineToken = function() {
+      var diff, indent, match, noNewlines, prev, size;
+      if (!(match = MULTI_DENT.exec(this.chunk))) {
+        return 0;
+      }
+      indent = match[0];
+      this.line += count(indent, '\n');
+      prev = last(this.tokens, 1);
+      size = indent.length - 1 - indent.lastIndexOf('\n');
+      noNewlines = this.unfinished();
+      if (size - this.indebt === this.indent) {
+        if (noNewlines) {
+          this.suppressNewlines();
+        } else {
+          this.newlineToken();
+        }
+        return indent.length;
+      }
+      if (size > this.indent) {
+        if (noNewlines) {
+          this.indebt = size - this.indent;
+          this.suppressNewlines();
+          return indent.length;
+        }
+        diff = size - this.indent + this.outdebt;
+        this.token('INDENT', diff);
+        this.indents.push(diff);
+        this.outdebt = this.indebt = 0;
+      } else {
+        this.indebt = 0;
+        this.outdentToken(this.indent - size, noNewlines);
+      }
+      this.indent = size;
+      return indent.length;
+    };
+    Lexer.prototype.outdentToken = function(moveOut, noNewlines, close) {
+      var dent, len;
+      while (moveOut > 0) {
+        len = this.indents.length - 1;
+        if (this.indents[len] === void 0) {
+          moveOut = 0;
+        } else if (this.indents[len] === this.outdebt) {
+          moveOut -= this.outdebt;
+          this.outdebt = 0;
+        } else if (this.indents[len] < this.outdebt) {
+          this.outdebt -= this.indents[len];
+          moveOut -= this.indents[len];
+        } else {
+          dent = this.indents.pop() - this.outdebt;
+          moveOut -= dent;
+          this.outdebt = 0;
+          this.token('OUTDENT', dent);
+        }
+      }
+      if (dent) {
+        this.outdebt -= moveOut;
+      }
+      if (!(this.tag() === 'TERMINATOR' || noNewlines)) {
+        this.token('TERMINATOR', '\n');
+      }
+      return this;
+    };
+    Lexer.prototype.whitespaceToken = function() {
+      var match, nline, prev;
+      if (!((match = WHITESPACE.exec(this.chunk)) || (nline = this.chunk.charAt(0) === '\n'))) {
+        return 0;
+      }
+      prev = last(this.tokens);
+      if (prev) {
+        prev[match ? 'spaced' : 'newLine'] = true;
+      }
+      if (match) {
+        return match[0].length;
+      } else {
+        return 0;
+      }
+    };
+    Lexer.prototype.newlineToken = function() {
+      if (this.tag() !== 'TERMINATOR') {
+        this.token('TERMINATOR', '\n');
+      }
+      return this;
+    };
+    Lexer.prototype.suppressNewlines = function() {
+      if (this.value() === '\\') {
+        this.tokens.pop();
+      }
+      return this;
+    };
+    Lexer.prototype.literalToken = function() {
+      var match, prev, tag, value, _ref2, _ref3, _ref4, _ref5;
+      if (match = OPERATOR.exec(this.chunk)) {
+        value = match[0];
+        if (CODE.test(value)) {
+          this.tagParameters();
+        }
+      } else {
+        value = this.chunk.charAt(0);
+      }
+      tag = value;
+      prev = last(this.tokens);
+      if (value === '=' && prev) {
+        if (!prev[1].reserved && (_ref2 = prev[1], __indexOf.call(JS_FORBIDDEN, _ref2) >= 0)) {
+          this.assignmentError();
+        }
+        if ((_ref3 = prev[1]) === '||' || _ref3 === '&&') {
+          prev[0] = 'COMPOUND_ASSIGN';
+          prev[1] += '=';
+          return value.length;
+        }
+      }
+      if (value === ';') {
+        tag = 'TERMINATOR';
+      } else if (__indexOf.call(MATH, value) >= 0) {
+        tag = 'MATH';
+      } else if (__indexOf.call(COMPARE, value) >= 0) {
+        tag = 'COMPARE';
+      } else if (__indexOf.call(COMPOUND_ASSIGN, value) >= 0) {
+        tag = 'COMPOUND_ASSIGN';
+      } else if (__indexOf.call(UNARY, value) >= 0) {
+        tag = 'UNARY';
+      } else if (__indexOf.call(SHIFT, value) >= 0) {
+        tag = 'SHIFT';
+      } else if (__indexOf.call(LOGIC, value) >= 0 || value === '?' && (prev != null ? prev.spaced : void 0)) {
+        tag = 'LOGIC';
+      } else if (prev && !prev.spaced) {
+        if (value === '(' && (_ref4 = prev[0], __indexOf.call(CALLABLE, _ref4) >= 0)) {
+          if (prev[0] === '?') {
+            prev[0] = 'FUNC_EXIST';
+          }
+          tag = 'CALL_START';
+        } else if (value === '[' && (_ref5 = prev[0], __indexOf.call(INDEXABLE, _ref5) >= 0)) {
+          tag = 'INDEX_START';
+          switch (prev[0]) {
+            case '?':
+              prev[0] = 'INDEX_SOAK';
+              break;
+            case '::':
+              prev[0] = 'INDEX_PROTO';
+          }
+        }
+      }
+      this.token(tag, value);
+      return value.length;
+    };
+    Lexer.prototype.sanitizeHeredoc = function(doc, options) {
+      var attempt, herecomment, indent, match, _ref2;
+      indent = options.indent, herecomment = options.herecomment;
+      if (herecomment) {
+        if (HEREDOC_ILLEGAL.test(doc)) {
+          throw new Error("block comment cannot contain \"*/\", starting on line " + (this.line + 1));
+        }
+        if (doc.indexOf('\n') <= 0) {
+          return doc;
+        }
+      } else {
+        while (match = HEREDOC_INDENT.exec(doc)) {
+          attempt = match[1];
+          if (indent === null || (0 < (_ref2 = attempt.length) && _ref2 < indent.length)) {
+            indent = attempt;
+          }
+        }
+      }
+      if (indent) {
+        doc = doc.replace(RegExp("\\n" + indent, "g"), '\n');
+      }
+      if (!herecomment) {
+        doc = doc.replace(/^\n/, '');
+      }
+      return doc;
+    };
+    Lexer.prototype.tagParameters = function() {
+      var i, stack, tok, tokens;
+      if (this.tag() !== ')') {
+        return this;
+      }
+      stack = [];
+      tokens = this.tokens;
+      i = tokens.length;
+      tokens[--i][0] = 'PARAM_END';
+      while (tok = tokens[--i]) {
+        switch (tok[0]) {
+          case ')':
+            stack.push(tok);
+            break;
+          case '(':
+          case 'CALL_START':
+            if (stack.length) {
+              stack.pop();
+            } else if (tok[0] === '(') {
+              tok[0] = 'PARAM_START';
+              return this;
+            } else {
+              return this;
+            }
+        }
+      }
+      return this;
+    };
+    Lexer.prototype.closeIndentation = function() {
+      return this.outdentToken(this.indent);
+    };
+    Lexer.prototype.identifierError = function(word) {
+      throw SyntaxError("Reserved word \"" + word + "\" on line " + (this.line + 1));
+    };
+    Lexer.prototype.assignmentError = function() {
+      throw SyntaxError("Reserved word \"" + (this.value()) + "\" on line " + (this.line + 1) + " can't be assigned");
+    };
+    Lexer.prototype.balancedString = function(str, end) {
+      var i, letter, match, prev, stack, _ref2;
+      stack = [end];
+      for (i = 1, _ref2 = str.length; 1 <= _ref2 ? i < _ref2 : i > _ref2; 1 <= _ref2 ? i++ : i--) {
+        switch (letter = str.charAt(i)) {
+          case '\\':
+            i++;
+            continue;
+          case end:
+            stack.pop();
+            if (!stack.length) {
+              return str.slice(0, i + 1);
+            }
+            end = stack[stack.length - 1];
+            continue;
+        }
+        if (end === '}' && (letter === '"' || letter === "'")) {
+          stack.push(end = letter);
+        } else if (end === '}' && letter === '/' && (match = HEREGEX.exec(str.slice(i)) || REGEX.exec(str.slice(i)))) {
+          i += match[0].length - 1;
+        } else if (end === '}' && letter === '{') {
+          stack.push(end = '}');
+        } else if (end === '"' && prev === '#' && letter === '{') {
+          stack.push(end = '}');
+        }
+        prev = letter;
+      }
+      throw new Error("missing " + (stack.pop()) + ", starting on line " + (this.line + 1));
+    };
+    Lexer.prototype.interpolateString = function(str, options) {
+      var expr, heredoc, i, inner, interpolated, len, letter, nested, pi, regex, tag, tokens, value, _len, _ref2, _ref3, _ref4;
+      if (options == null) {
+        options = {};
+      }
+      heredoc = options.heredoc, regex = options.regex;
+      tokens = [];
+      pi = 0;
+      i = -1;
+      while (letter = str.charAt(i += 1)) {
+        if (letter === '\\') {
+          i += 1;
+          continue;
+        }
+        if (!(letter === '#' && str.charAt(i + 1) === '{' && (expr = this.balancedString(str.slice(i + 1), '}')))) {
+          continue;
+        }
+        if (pi < i) {
+          tokens.push(['NEOSTRING', str.slice(pi, i)]);
+        }
+        inner = expr.slice(1, -1);
+        if (inner.length) {
+          nested = new Lexer().tokenize(inner, {
+            line: this.line,
+            rewrite: false
+          });
+          nested.pop();
+          if (((_ref2 = nested[0]) != null ? _ref2[0] : void 0) === 'TERMINATOR') {
+            nested.shift();
+          }
+          if (len = nested.length) {
+            if (len > 1) {
+              nested.unshift(['(', '(']);
+              nested.push([')', ')']);
+            }
+            tokens.push(['TOKENS', nested]);
+          }
+        }
+        i += expr.length;
+        pi = i + 1;
+      }
+      if ((i > pi && pi < str.length)) {
+        tokens.push(['NEOSTRING', str.slice(pi)]);
+      }
+      if (regex) {
+        return tokens;
+      }
+      if (!tokens.length) {
+        return this.token('STRING', '""');
+      }
+      if (tokens[0][0] !== 'NEOSTRING') {
+        tokens.unshift(['', '']);
+      }
+      if (interpolated = tokens.length > 1) {
+        this.token('(', '(');
+      }
+      for (i = 0, _len = tokens.length; i < _len; i++) {
+        _ref3 = tokens[i], tag = _ref3[0], value = _ref3[1];
+        if (i) {
+          this.token('+', '+');
+        }
+        if (tag === 'TOKENS') {
+          (_ref4 = this.tokens).push.apply(_ref4, value);
+        } else {
+          this.token('STRING', this.makeString(value, '"', heredoc));
+        }
+      }
+      if (interpolated) {
+        this.token(')', ')');
+      }
+      return tokens;
+    };
+    Lexer.prototype.token = function(tag, value) {
+      return this.tokens.push([tag, value, this.line]);
+    };
+    Lexer.prototype.tag = function(index, tag) {
+      var tok;
+      return (tok = last(this.tokens, index)) && (tag ? tok[0] = tag : tok[0]);
+    };
+    Lexer.prototype.value = function(index, val) {
+      var tok;
+      return (tok = last(this.tokens, index)) && (val ? tok[1] = val : tok[1]);
+    };
+    Lexer.prototype.unfinished = function() {
+      var prev, value;
+      return LINE_CONTINUER.test(this.chunk) || (prev = last(this.tokens, 1)) && prev[0] !== '.' && (value = this.value()) && !value.reserved && NO_NEWLINE.test(value) && !CODE.test(value) && !ASSIGNED.test(this.chunk);
+    };
+    Lexer.prototype.escapeLines = function(str, heredoc) {
+      return str.replace(MULTILINER, heredoc ? '\\n' : '');
+    };
+    Lexer.prototype.makeString = function(body, quote, heredoc) {
+      if (!body) {
+        return quote + quote;
+      }
+      body = body.replace(/\\([\s\S])/g, function(match, contents) {
+        if (contents === '\n' || contents === quote) {
+          return contents;
+        } else {
+          return match;
+        }
+      });
+      body = body.replace(RegExp("" + quote, "g"), '\\$&');
+      return quote + this.escapeLines(body, heredoc) + quote;
+    };
+    return Lexer;
+  })();
+  JS_KEYWORDS = ['true', 'false', 'null', 'this', 'new', 'delete', 'typeof', 'in', 'instanceof', 'return', 'throw', 'break', 'continue', 'debugger', 'if', 'else', 'switch', 'for', 'while', 'do', 'try', 'catch', 'finally', 'class', 'extends', 'super'];
+  COFFEE_KEYWORDS = ['undefined', 'then', 'unless', 'until', 'loop', 'of', 'by', 'when'];
+  COFFEE_ALIAS_MAP = {
+    and: '&&',
+    or: '||',
+    is: '==',
+    isnt: '!=',
+    not: '!',
+    yes: 'true',
+    no: 'false',
+    on: 'true',
+    off: 'false'
+  };
+  COFFEE_ALIASES = (function() {
+    var _results;
+    _results = [];
+    for (key in COFFEE_ALIAS_MAP) {
+      _results.push(key);
+    }
+    return _results;
+  })();
+  COFFEE_KEYWORDS = COFFEE_KEYWORDS.concat(COFFEE_ALIASES);
+  RESERVED = ['case', 'default', 'function', 'var', 'void', 'with', 'const', 'let', 'enum', 'export', 'import', 'native', '__hasProp', '__extends', '__slice', '__bind', '__indexOf'];
+  JS_FORBIDDEN = JS_KEYWORDS.concat(RESERVED);
+  exports.RESERVED = RESERVED.concat(JS_KEYWORDS).concat(COFFEE_KEYWORDS);
+  IDENTIFIER = /^([$A-Za-z_\x7f-\uffff][$\w\x7f-\uffff]*)([^\n\S]*:(?!:))?/;
+  NUMBER = /^0x[\da-f]+|^\d*\.?\d+(?:e[+-]?\d+)?/i;
+  HEREDOC = /^("""|''')([\s\S]*?)(?:\n[^\n\S]*)?\1/;
+  OPERATOR = /^(?:[-=]>|[-+*\/%<>&|^!?=]=|>>>=?|([-+:])\1|([&|<>])\2=?|\?\.|\.{2,3})/;
+  WHITESPACE = /^[^\n\S]+/;
+  COMMENT = /^###([^#][\s\S]*?)(?:###[^\n\S]*|(?:###)?$)|^(?:\s*#(?!##[^#]).*)+/;
+  CODE = /^[-=]>/;
+  MULTI_DENT = /^(?:\n[^\n\S]*)+/;
+  SIMPLESTR = /^'[^\\']*(?:\\.[^\\']*)*'/;
+  JSTOKEN = /^`[^\\`]*(?:\\.[^\\`]*)*`/;
+  REGEX = /^\/(?![\s=])[^[\/\n\\]*(?:(?:\\[\s\S]|\[[^\]\n\\]*(?:\\[\s\S][^\]\n\\]*)*])[^[\/\n\\]*)*\/[imgy]{0,4}(?!\w)/;
+  HEREGEX = /^\/{3}([\s\S]+?)\/{3}([imgy]{0,4})(?!\w)/;
+  HEREGEX_OMIT = /\s+(?:#.*)?/g;
+  MULTILINER = /\n/g;
+  HEREDOC_INDENT = /\n+([^\n\S]*)/g;
+  HEREDOC_ILLEGAL = /\*\//;
+  ASSIGNED = /^\s*@?([$A-Za-z_][$\w\x7f-\uffff]*|['"].*['"])[^\n\S]*?[:=][^:=>]/;
+  LINE_CONTINUER = /^\s*(?:,|\??\.(?![.\d])|::)/;
+  TRAILING_SPACES = /\s+$/;
+  NO_NEWLINE = /^(?:[-+*&|\/%=<>!.\\][<>=&|]*|and|or|is(?:nt)?|n(?:ot|ew)|delete|typeof|instanceof)$/;
+  COMPOUND_ASSIGN = ['-=', '+=', '/=', '*=', '%=', '||=', '&&=', '?=', '<<=', '>>=', '>>>=', '&=', '^=', '|='];
+  UNARY = ['!', '~', 'NEW', 'TYPEOF', 'DELETE', 'DO'];
+  LOGIC = ['&&', '||', '&', '|', '^'];
+  SHIFT = ['<<', '>>', '>>>'];
+  COMPARE = ['==', '!=', '<', '>', '<=', '>='];
+  MATH = ['*', '/', '%'];
+  RELATION = ['IN', 'OF', 'INSTANCEOF'];
+  BOOL = ['TRUE', 'FALSE', 'NULL', 'UNDEFINED'];
+  NOT_REGEX = ['NUMBER', 'REGEX', 'BOOL', '++', '--', ']'];
+  NOT_SPACED_REGEX = NOT_REGEX.concat(')', '}', 'THIS', 'IDENTIFIER', 'STRING');
+  CALLABLE = ['IDENTIFIER', 'STRING', 'REGEX', ')', ']', '}', '?', '::', '@', 'THIS', 'SUPER'];
+  INDEXABLE = CALLABLE.concat('NUMBER', 'BOOL');
+  LINE_BREAK = ['INDENT', 'OUTDENT', 'TERMINATOR'];
+}).call(this);
+return exports;
+}());(function () {
+var exports = __MODULES['parser'] = {};
+/* Jison generated parser */
+var parser = (function(){
+var parser = {trace: function trace() { },
+yy: {},
+symbols_: {"error":2,"Root":3,"Body":4,"Block":5,"TERMINATOR":6,"Line":7,"Expression":8,"Statement":9,"Return":10,"Throw":11,"Comment":12,"STATEMENT":13,"Value":14,"Invocation":15,"Code":16,"Operation":17,"Assign":18,"If":19,"Try":20,"While":21,"For":22,"Switch":23,"Class":24,"INDENT":25,"OUTDENT":26,"Identifier":27,"IDENTIFIER":28,"AlphaNumeric":29,"NUMBER":30,"STRING":31,"Literal":32,"JS":33,"REGEX":34,"BOOL":35,"Assignable":36,"=":37,"AssignObj":38,"ObjAssignable":39,":":40,"ThisPrope [...]
+terminals_: {2:"error",6:"TERMINATOR",13:"STATEMENT",25:"INDENT",26:"OUTDENT",28:"IDENTIFIER",30:"NUMBER",31:"STRING",33:"JS",34:"REGEX",35:"BOOL",37:"=",40:":",42:"RETURN",43:"HERECOMMENT",44:"PARAM_START",46:"PARAM_END",48:"->",49:"=>",51:",",54:"...",63:".",64:"?.",65:"::",67:"INDEX_START",69:"INDEX_END",70:"INDEX_SOAK",71:"INDEX_PROTO",73:"{",75:"}",76:"CLASS",77:"EXTENDS",80:"SUPER",81:"FUNC_EXIST",82:"CALL_START",83:"CALL_END",85:"THIS",86:"@",87:"[",88:"]",90:"..",93:"TRY",95:"FIN [...]
+productions_: [0,[3,0],[3,1],[3,2],[4,1],[4,3],[4,2],[7,1],[7,1],[9,1],[9,1],[9,1],[9,1],[8,1],[8,1],[8,1],[8,1],[8,1],[8,1],[8,1],[8,1],[8,1],[8,1],[8,1],[5,2],[5,3],[27,1],[29,1],[29,1],[32,1],[32,1],[32,1],[32,1],[18,3],[18,5],[38,1],[38,3],[38,5],[38,1],[39,1],[39,1],[39,1],[10,2],[10,1],[12,1],[16,5],[16,2],[47,1],[47,1],[50,0],[50,1],[45,0],[45,1],[45,3],[52,1],[52,2],[52,3],[53,1],[53,1],[53,1],[53,1],[57,2],[58,1],[58,2],[58,2],[58,1],[36,1],[36,1],[36,1],[14,1],[14,1],[14,1],[14 [...]
+performAction: function anonymous(yytext,yyleng,yylineno,yy,yystate,$$,_$) {
+
+var $0 = $$.length - 1;
+switch (yystate) {
+case 1:return this.$ = new yy.Block;
+break;
+case 2:return this.$ = $$[$0];
+break;
+case 3:return this.$ = $$[$0-1];
+break;
+case 4:this.$ = yy.Block.wrap([$$[$0]]);
+break;
+case 5:this.$ = $$[$0-2].push($$[$0]);
+break;
+case 6:this.$ = $$[$0-1];
+break;
+case 7:this.$ = $$[$0];
+break;
+case 8:this.$ = $$[$0];
+break;
+case 9:this.$ = $$[$0];
+break;
+case 10:this.$ = $$[$0];
+break;
+case 11:this.$ = $$[$0];
+break;
+case 12:this.$ = new yy.Literal($$[$0]);
+break;
+case 13:this.$ = $$[$0];
+break;
+case 14:this.$ = $$[$0];
+break;
+case 15:this.$ = $$[$0];
+break;
+case 16:this.$ = $$[$0];
+break;
+case 17:this.$ = $$[$0];
+break;
+case 18:this.$ = $$[$0];
+break;
+case 19:this.$ = $$[$0];
+break;
+case 20:this.$ = $$[$0];
+break;
+case 21:this.$ = $$[$0];
+break;
+case 22:this.$ = $$[$0];
+break;
+case 23:this.$ = $$[$0];
+break;
+case 24:this.$ = new yy.Block;
+break;
+case 25:this.$ = $$[$0-1];
+break;
+case 26:this.$ = new yy.Literal($$[$0]);
+break;
+case 27:this.$ = new yy.Literal($$[$0]);
+break;
+case 28:this.$ = new yy.Literal($$[$0]);
+break;
+case 29:this.$ = $$[$0];
+break;
+case 30:this.$ = new yy.Literal($$[$0]);
+break;
+case 31:this.$ = new yy.Literal($$[$0]);
+break;
+case 32:this.$ = (function () {
+        var val;
+        val = new yy.Literal($$[$0]);
+        if ($$[$0] === 'undefined') {
+          val.isUndefined = true;
+        }
+        return val;
+      }());
+break;
+case 33:this.$ = new yy.Assign($$[$0-2], $$[$0]);
+break;
+case 34:this.$ = new yy.Assign($$[$0-4], $$[$0-1]);
+break;
+case 35:this.$ = new yy.Value($$[$0]);
+break;
+case 36:this.$ = new yy.Assign(new yy.Value($$[$0-2]), $$[$0], 'object');
+break;
+case 37:this.$ = new yy.Assign(new yy.Value($$[$0-4]), $$[$0-1], 'object');
+break;
+case 38:this.$ = $$[$0];
+break;
+case 39:this.$ = $$[$0];
+break;
+case 40:this.$ = $$[$0];
+break;
+case 41:this.$ = $$[$0];
+break;
+case 42:this.$ = new yy.Return($$[$0]);
+break;
+case 43:this.$ = new yy.Return;
+break;
+case 44:this.$ = new yy.Comment($$[$0]);
+break;
+case 45:this.$ = new yy.Code($$[$0-3], $$[$0], $$[$0-1]);
+break;
+case 46:this.$ = new yy.Code([], $$[$0], $$[$0-1]);
+break;
+case 47:this.$ = 'func';
+break;
+case 48:this.$ = 'boundfunc';
+break;
+case 49:this.$ = $$[$0];
+break;
+case 50:this.$ = $$[$0];
+break;
+case 51:this.$ = [];
+break;
+case 52:this.$ = [$$[$0]];
+break;
+case 53:this.$ = $$[$0-2].concat($$[$0]);
+break;
+case 54:this.$ = new yy.Param($$[$0]);
+break;
+case 55:this.$ = new yy.Param($$[$0-1], null, true);
+break;
+case 56:this.$ = new yy.Param($$[$0-2], $$[$0]);
+break;
+case 57:this.$ = $$[$0];
+break;
+case 58:this.$ = $$[$0];
+break;
+case 59:this.$ = $$[$0];
+break;
+case 60:this.$ = $$[$0];
+break;
+case 61:this.$ = new yy.Splat($$[$0-1]);
+break;
+case 62:this.$ = new yy.Value($$[$0]);
+break;
+case 63:this.$ = $$[$0-1].push($$[$0]);
+break;
+case 64:this.$ = new yy.Value($$[$0-1], [$$[$0]]);
+break;
+case 65:this.$ = $$[$0];
+break;
+case 66:this.$ = $$[$0];
+break;
+case 67:this.$ = new yy.Value($$[$0]);
+break;
+case 68:this.$ = new yy.Value($$[$0]);
+break;
+case 69:this.$ = $$[$0];
+break;
+case 70:this.$ = new yy.Value($$[$0]);
+break;
+case 71:this.$ = new yy.Value($$[$0]);
+break;
+case 72:this.$ = new yy.Value($$[$0]);
+break;
+case 73:this.$ = $$[$0];
+break;
+case 74:this.$ = new yy.Access($$[$0]);
+break;
+case 75:this.$ = new yy.Access($$[$0], 'soak');
+break;
+case 76:this.$ = new yy.Access($$[$0], 'proto');
+break;
+case 77:this.$ = new yy.Access(new yy.Literal('prototype'));
+break;
+case 78:this.$ = $$[$0];
+break;
+case 79:this.$ = $$[$0-1];
+break;
+case 80:this.$ = yy.extend($$[$0], {
+          soak: true
+        });
+break;
+case 81:this.$ = yy.extend($$[$0], {
+          proto: true
+        });
+break;
+case 82:this.$ = new yy.Index($$[$0]);
+break;
+case 83:this.$ = new yy.Slice($$[$0]);
+break;
+case 84:this.$ = new yy.Obj($$[$0-2], $$[$0-3].generated);
+break;
+case 85:this.$ = [];
+break;
+case 86:this.$ = [$$[$0]];
+break;
+case 87:this.$ = $$[$0-2].concat($$[$0]);
+break;
+case 88:this.$ = $$[$0-3].concat($$[$0]);
+break;
+case 89:this.$ = $$[$0-5].concat($$[$0-2]);
+break;
+case 90:this.$ = new yy.Class;
+break;
+case 91:this.$ = new yy.Class(null, null, $$[$0]);
+break;
+case 92:this.$ = new yy.Class(null, $$[$0]);
+break;
+case 93:this.$ = new yy.Class(null, $$[$0-1], $$[$0]);
+break;
+case 94:this.$ = new yy.Class($$[$0]);
+break;
+case 95:this.$ = new yy.Class($$[$0-1], null, $$[$0]);
+break;
+case 96:this.$ = new yy.Class($$[$0-2], $$[$0]);
+break;
+case 97:this.$ = new yy.Class($$[$0-3], $$[$0-1], $$[$0]);
+break;
+case 98:this.$ = new yy.Call($$[$0-2], $$[$0], $$[$0-1]);
+break;
+case 99:this.$ = new yy.Call($$[$0-2], $$[$0], $$[$0-1]);
+break;
+case 100:this.$ = new yy.Call('super', [new yy.Splat(new yy.Literal('arguments'))]);
+break;
+case 101:this.$ = new yy.Call('super', $$[$0]);
+break;
+case 102:this.$ = false;
+break;
+case 103:this.$ = true;
+break;
+case 104:this.$ = [];
+break;
+case 105:this.$ = $$[$0-2];
+break;
+case 106:this.$ = new yy.Value(new yy.Literal('this'));
+break;
+case 107:this.$ = new yy.Value(new yy.Literal('this'));
+break;
+case 108:this.$ = new yy.Value(new yy.Literal('this'), [new yy.Access($$[$0])], 'this');
+break;
+case 109:this.$ = new yy.Arr([]);
+break;
+case 110:this.$ = new yy.Arr($$[$0-2]);
+break;
+case 111:this.$ = 'inclusive';
+break;
+case 112:this.$ = 'exclusive';
+break;
+case 113:this.$ = new yy.Range($$[$0-3], $$[$0-1], $$[$0-2]);
+break;
+case 114:this.$ = new yy.Range($$[$0-2], $$[$0], $$[$0-1]);
+break;
+case 115:this.$ = new yy.Range($$[$0-1], null, $$[$0]);
+break;
+case 116:this.$ = new yy.Range(null, $$[$0], $$[$0-1]);
+break;
+case 117:this.$ = [$$[$0]];
+break;
+case 118:this.$ = $$[$0-2].concat($$[$0]);
+break;
+case 119:this.$ = $$[$0-3].concat($$[$0]);
+break;
+case 120:this.$ = $$[$0-2];
+break;
+case 121:this.$ = $$[$0-5].concat($$[$0-2]);
+break;
+case 122:this.$ = $$[$0];
+break;
+case 123:this.$ = $$[$0];
+break;
+case 124:this.$ = $$[$0];
+break;
+case 125:this.$ = [].concat($$[$0-2], $$[$0]);
+break;
+case 126:this.$ = new yy.Try($$[$0]);
+break;
+case 127:this.$ = new yy.Try($$[$0-1], $$[$0][0], $$[$0][1]);
+break;
+case 128:this.$ = new yy.Try($$[$0-2], null, null, $$[$0]);
+break;
+case 129:this.$ = new yy.Try($$[$0-3], $$[$0-2][0], $$[$0-2][1], $$[$0]);
+break;
+case 130:this.$ = [$$[$0-1], $$[$0]];
+break;
+case 131:this.$ = new yy.Throw($$[$0]);
+break;
+case 132:this.$ = new yy.Parens($$[$0-1]);
+break;
+case 133:this.$ = new yy.Parens($$[$0-2]);
+break;
+case 134:this.$ = new yy.While($$[$0]);
+break;
+case 135:this.$ = new yy.While($$[$0-2], {
+          guard: $$[$0]
+        });
+break;
+case 136:this.$ = new yy.While($$[$0], {
+          invert: true
+        });
+break;
+case 137:this.$ = new yy.While($$[$0-2], {
+          invert: true,
+          guard: $$[$0]
+        });
+break;
+case 138:this.$ = $$[$0-1].addBody($$[$0]);
+break;
+case 139:this.$ = $$[$0].addBody(yy.Block.wrap([$$[$0-1]]));
+break;
+case 140:this.$ = $$[$0].addBody(yy.Block.wrap([$$[$0-1]]));
+break;
+case 141:this.$ = $$[$0];
+break;
+case 142:this.$ = new yy.While(new yy.Literal('true')).addBody($$[$0]);
+break;
+case 143:this.$ = new yy.While(new yy.Literal('true')).addBody(yy.Block.wrap([$$[$0]]));
+break;
+case 144:this.$ = new yy.For($$[$0-1], $$[$0]);
+break;
+case 145:this.$ = new yy.For($$[$0-1], $$[$0]);
+break;
+case 146:this.$ = new yy.For($$[$0], $$[$0-1]);
+break;
+case 147:this.$ = {
+          source: new yy.Value($$[$0])
+        };
+break;
+case 148:this.$ = (function () {
+        $$[$0].own = $$[$0-1].own;
+        $$[$0].name = $$[$0-1][0];
+        $$[$0].index = $$[$0-1][1];
+        return $$[$0];
+      }());
+break;
+case 149:this.$ = $$[$0];
+break;
+case 150:this.$ = (function () {
+        $$[$0].own = true;
+        return $$[$0];
+      }());
+break;
+case 151:this.$ = $$[$0];
+break;
+case 152:this.$ = new yy.Value($$[$0]);
+break;
+case 153:this.$ = new yy.Value($$[$0]);
+break;
+case 154:this.$ = [$$[$0]];
+break;
+case 155:this.$ = [$$[$0-2], $$[$0]];
+break;
+case 156:this.$ = {
+          source: $$[$0]
+        };
+break;
+case 157:this.$ = {
+          source: $$[$0],
+          object: true
+        };
+break;
+case 158:this.$ = {
+          source: $$[$0-2],
+          guard: $$[$0]
+        };
+break;
+case 159:this.$ = {
+          source: $$[$0-2],
+          guard: $$[$0],
+          object: true
+        };
+break;
+case 160:this.$ = {
+          source: $$[$0-2],
+          step: $$[$0]
+        };
+break;
+case 161:this.$ = {
+          source: $$[$0-4],
+          guard: $$[$0-2],
+          step: $$[$0]
+        };
+break;
+case 162:this.$ = {
+          source: $$[$0-4],
+          step: $$[$0-2],
+          guard: $$[$0]
+        };
+break;
+case 163:this.$ = new yy.Switch($$[$0-3], $$[$0-1]);
+break;
+case 164:this.$ = new yy.Switch($$[$0-5], $$[$0-3], $$[$0-1]);
+break;
+case 165:this.$ = new yy.Switch(null, $$[$0-1]);
+break;
+case 166:this.$ = new yy.Switch(null, $$[$0-3], $$[$0-1]);
+break;
+case 167:this.$ = $$[$0];
+break;
+case 168:this.$ = $$[$0-1].concat($$[$0]);
+break;
+case 169:this.$ = [[$$[$0-1], $$[$0]]];
+break;
+case 170:this.$ = [[$$[$0-2], $$[$0-1]]];
+break;
+case 171:this.$ = new yy.If($$[$0-1], $$[$0], {
+          type: $$[$0-2]
+        });
+break;
+case 172:this.$ = $$[$0-4].addElse(new yy.If($$[$0-1], $$[$0], {
+          type: $$[$0-2]
+        }));
+break;
+case 173:this.$ = $$[$0];
+break;
+case 174:this.$ = $$[$0-2].addElse($$[$0]);
+break;
+case 175:this.$ = new yy.If($$[$0], yy.Block.wrap([$$[$0-2]]), {
+          type: $$[$0-1],
+          statement: true
+        });
+break;
+case 176:this.$ = new yy.If($$[$0], yy.Block.wrap([$$[$0-2]]), {
+          type: $$[$0-1],
+          statement: true
+        });
+break;
+case 177:this.$ = new yy.Op($$[$0-1], $$[$0]);
+break;
+case 178:this.$ = new yy.Op('-', $$[$0]);
+break;
+case 179:this.$ = new yy.Op('+', $$[$0]);
+break;
+case 180:this.$ = new yy.Op('--', $$[$0]);
+break;
+case 181:this.$ = new yy.Op('++', $$[$0]);
+break;
+case 182:this.$ = new yy.Op('--', $$[$0-1], null, true);
+break;
+case 183:this.$ = new yy.Op('++', $$[$0-1], null, true);
+break;
+case 184:this.$ = new yy.Existence($$[$0-1]);
+break;
+case 185:this.$ = new yy.Op('+', $$[$0-2], $$[$0]);
+break;
+case 186:this.$ = new yy.Op('-', $$[$0-2], $$[$0]);
+break;
+case 187:this.$ = new yy.Op($$[$0-1], $$[$0-2], $$[$0]);
+break;
+case 188:this.$ = new yy.Op($$[$0-1], $$[$0-2], $$[$0]);
+break;
+case 189:this.$ = new yy.Op($$[$0-1], $$[$0-2], $$[$0]);
+break;
+case 190:this.$ = new yy.Op($$[$0-1], $$[$0-2], $$[$0]);
+break;
+case 191:this.$ = (function () {
+        if ($$[$0-1].charAt(0) === '!') {
+          return new yy.Op($$[$0-1].slice(1), $$[$0-2], $$[$0]).invert();
+        } else {
+          return new yy.Op($$[$0-1], $$[$0-2], $$[$0]);
+        }
+      }());
+break;
+case 192:this.$ = new yy.Assign($$[$0-2], $$[$0], $$[$0-1]);
+break;
+case 193:this.$ = new yy.Assign($$[$0-4], $$[$0-1], $$[$0-3]);
+break;
+case 194:this.$ = new yy.Extends($$[$0-2], $$[$0]);
+break;
+}
+},
+table: [{1:[2,1],3:1,4:2,5:3,7:4,8:6,9:7,10:19,11:20,12:21,13:[1,22],14:8,15:9,16:10,17:11,18:12,19:13,20:14,21:15,22:16,23:17,24:18,25:[1,5],27:59,28:[1,70],29:49,30:[1,68],31:[1,69],32:24,33:[1,50],34:[1,51],35:[1,52],36:23,41:60,42:[1,44],43:[1,46],44:[1,29],47:30,48:[1,57],49:[1,58],55:47,56:48,58:36,60:25,61:26,62:27,73:[1,67],76:[1,43],80:[1,28],85:[1,55],86:[1,56],87:[1,54],93:[1,38],97:[1,45],98:[1,53],100:39,101:[1,62],103:[1,63],104:40,105:[1,64],106:41,107:[1,65],108:66,116:[1 [...]
+defaultActions: {57:[2,47],58:[2,48],72:[2,3],91:[2,103],186:[2,83]},
+parseError: function parseError(str, hash) {
+    throw new Error(str);
+},
+parse: function parse(input) {
+    var self = this,
+        stack = [0],
+        vstack = [null], // semantic value stack
+        lstack = [], // location stack
+        table = this.table,
+        yytext = '',
+        yylineno = 0,
+        yyleng = 0,
+        recovering = 0,
+        TERROR = 2,
+        EOF = 1;
+
+    //this.reductionCount = this.shiftCount = 0;
+
+    this.lexer.setInput(input);
+    this.lexer.yy = this.yy;
+    this.yy.lexer = this.lexer;
+    if (typeof this.lexer.yylloc == 'undefined')
+        this.lexer.yylloc = {};
+    var yyloc = this.lexer.yylloc;
+    lstack.push(yyloc);
+
+    if (typeof this.yy.parseError === 'function')
+        this.parseError = this.yy.parseError;
+
+    function popStack (n) {
+        stack.length = stack.length - 2*n;
+        vstack.length = vstack.length - n;
+        lstack.length = lstack.length - n;
+    }
+
+    function lex() {
+        var token;
+        token = self.lexer.lex() || 1; // $end = 1
+        // if token isn't its numeric value, convert
+        if (typeof token !== 'number') {
+            token = self.symbols_[token] || token;
+        }
+        return token;
+    };
+
+    var symbol, preErrorSymbol, state, action, a, r, yyval={},p,len,newState, expected;
+    while (true) {
+        // retreive state number from top of stack
+        state = stack[stack.length-1];
+
+        // use default actions if available
+        if (this.defaultActions[state]) {
+            action = this.defaultActions[state];
+        } else {
+            if (symbol == null)
+                symbol = lex();
+            // read action for current state and first input
+            action = table[state] && table[state][symbol];
+        }
+
+        // handle parse error
+        if (typeof action === 'undefined' || !action.length || !action[0]) {
+
+            if (!recovering) {
+                // Report error
+                expected = [];
+                for (p in table[state]) if (this.terminals_[p] && p > 2) {
+                    expected.push("'"+this.terminals_[p]+"'");
+                }
+                var errStr = '';
+                if (this.lexer.showPosition) {
+                    errStr = 'Parse error on line '+(yylineno+1)+":\n"+this.lexer.showPosition()+'\nExpecting '+expected.join(', ');
+                } else {
+                    errStr = 'Parse error on line '+(yylineno+1)+": Unexpected " +
+                                  (symbol == 1 /*EOF*/ ? "end of input" :
+                                              ("'"+(this.terminals_[symbol] || symbol)+"'"));
+                }
+                this.parseError(errStr,
+                    {text: this.lexer.match, token: this.terminals_[symbol] || symbol, line: this.lexer.yylineno, loc: yyloc, expected: expected});
+            }
+
+            // just recovered from another error
+            if (recovering == 3) {
+                if (symbol == EOF) {
+                    throw new Error(errStr || 'Parsing halted.');
+                }
+
+                // discard current lookahead and grab another
+                yyleng = this.lexer.yyleng;
+                yytext = this.lexer.yytext;
+                yylineno = this.lexer.yylineno;
+                yyloc = this.lexer.yylloc;
+                symbol = lex();
+            }
+
+            // try to recover from error
+            while (1) {
+                // check for error recovery rule in this state
+                if ((TERROR.toString()) in table[state]) {
+                    break;
+                }
+                if (state == 0) {
+                    throw new Error(errStr || 'Parsing halted.');
+                }
+                popStack(1);
+                state = stack[stack.length-1];
+            }
+
+            preErrorSymbol = symbol; // save the lookahead token
+            symbol = TERROR;         // insert generic error symbol as new lookahead
+            state = stack[stack.length-1];
+            action = table[state] && table[state][TERROR];
+            recovering = 3; // allow 3 real symbols to be shifted before reporting a new error
+        }
+
+        // this shouldn't happen, unless resolve defaults are off
+        if (action[0] instanceof Array && action.length > 1) {
+            throw new Error('Parse Error: multiple actions possible at state: '+state+', token: '+symbol);
+        }
+
+        switch (action[0]) {
+
+            case 1: // shift
+                //this.shiftCount++;
+
+                stack.push(symbol);
+                vstack.push(this.lexer.yytext);
+                lstack.push(this.lexer.yylloc);
+                stack.push(action[1]); // push state
+                symbol = null;
+                if (!preErrorSymbol) { // normal execution/no error
+                    yyleng = this.lexer.yyleng;
+                    yytext = this.lexer.yytext;
+                    yylineno = this.lexer.yylineno;
+                    yyloc = this.lexer.yylloc;
+                    if (recovering > 0)
+                        recovering--;
+                } else { // error just occurred, resume old lookahead f/ before error
+                    symbol = preErrorSymbol;
+                    preErrorSymbol = null;
+                }
+                break;
+
+            case 2: // reduce
+                //this.reductionCount++;
+
+                len = this.productions_[action[1]][1];
+
+                // perform semantic action
+                yyval.$ = vstack[vstack.length-len]; // default to $$ = $1
+                // default location, uses first token for firsts, last for lasts
+                yyval._$ = {
+                    first_line: lstack[lstack.length-(len||1)].first_line,
+                    last_line: lstack[lstack.length-1].last_line,
+                    first_column: lstack[lstack.length-(len||1)].first_column,
+                    last_column: lstack[lstack.length-1].last_column
+                };
+                r = this.performAction.call(yyval, yytext, yyleng, yylineno, this.yy, action[1], vstack, lstack);
+
+                if (typeof r !== 'undefined') {
+                    return r;
+                }
+
+                // pop off stack
+                if (len) {
+                    stack = stack.slice(0,-1*len*2);
+                    vstack = vstack.slice(0, -1*len);
+                    lstack = lstack.slice(0, -1*len);
+                }
+
+                stack.push(this.productions_[action[1]][0]);    // push nonterminal (reduce)
+                vstack.push(yyval.$);
+                lstack.push(yyval._$);
+                // goto new state = table[STATE][NONTERMINAL]
+                newState = table[stack[stack.length-2]][stack[stack.length-1]];
+                stack.push(newState);
+                break;
+
+            case 3: // accept
+                return true;
+        }
+
+    }
+
+    return true;
+}};
+return parser;
+})();
+if (typeof require !== 'undefined' && typeof exports !== 'undefined') {
+exports.parser = parser;
+exports.parse = function () { return parser.parse.apply(parser, arguments); }
+exports.main = function commonjsMain(args) {
+    if (!args[1])
+        throw new Error('Usage: '+args[0]+' FILE');
+    if (typeof process !== 'undefined') {
+        var source = require('fs').readFileSync(require('path').join(process.cwd(), args[1]), "utf8");
+    } else {
+        var cwd = require("file").path(require("file").cwd());
+        var source = cwd.join(args[1]).read({charset: "utf-8"});
+    }
+    return exports.parser.parse(source);
+}
+if (typeof module !== 'undefined' && require.main === module) {
+  exports.main(typeof process !== 'undefined' ? process.argv.slice(1) : require("system").args);
+}
+}return exports;
+}());(function () {
+var exports = __MODULES['scope'] = {};
+(function() {
+  var Scope, extend, last, _ref;
+  _ref = require('./helpers'), extend = _ref.extend, last = _ref.last;
+  exports.Scope = Scope = (function() {
+    Scope.root = null;
+    function Scope(parent, expressions, method) {
+      this.parent = parent;
+      this.expressions = expressions;
+      this.method = method;
+      this.variables = [
+        {
+          name: 'arguments',
+          type: 'arguments'
+        }
+      ];
+      this.positions = {};
+      if (!this.parent) {
+        Scope.root = this;
+      }
+    }
+    Scope.prototype.add = function(name, type, immediate) {
+      var pos;
+      if (this.shared && !immediate) {
+        return this.parent.add(name, type, immediate);
+      }
+      if (typeof (pos = this.positions[name]) === 'number') {
+        return this.variables[pos].type = type;
+      } else {
+        return this.positions[name] = this.variables.push({
+          name: name,
+          type: type
+        }) - 1;
+      }
+    };
+    Scope.prototype.find = function(name, options) {
+      if (this.check(name, options)) {
+        return true;
+      }
+      this.add(name, 'var');
+      return false;
+    };
+    Scope.prototype.parameter = function(name) {
+      if (this.shared && this.parent.check(name, true)) {
+        return;
+      }
+      return this.add(name, 'param');
+    };
+    Scope.prototype.check = function(name, immediate) {
+      var found, _ref2;
+      found = !!this.type(name);
+      if (found || immediate) {
+        return found;
+      }
+      return !!((_ref2 = this.parent) != null ? _ref2.check(name) : void 0);
+    };
+    Scope.prototype.temporary = function(name, index) {
+      if (name.length > 1) {
+        return '_' + name + (index > 1 ? index : '');
+      } else {
+        return '_' + (index + parseInt(name, 36)).toString(36).replace(/\d/g, 'a');
+      }
+    };
+    Scope.prototype.type = function(name) {
+      var v, _i, _len, _ref2;
+      _ref2 = this.variables;
+      for (_i = 0, _len = _ref2.length; _i < _len; _i++) {
+        v = _ref2[_i];
+        if (v.name === name) {
+          return v.type;
+        }
+      }
+      return null;
+    };
+    Scope.prototype.freeVariable = function(type) {
+      var index, temp;
+      index = 0;
+      while (this.check((temp = this.temporary(type, index)))) {
+        index++;
+      }
+      this.add(temp, 'var', true);
+      return temp;
+    };
+    Scope.prototype.assign = function(name, value) {
+      this.add(name, {
+        value: value,
+        assigned: true
+      });
+      return this.hasAssignments = true;
+    };
+    Scope.prototype.hasDeclarations = function() {
+      return !!this.declaredVariables().length;
+    };
+    Scope.prototype.declaredVariables = function() {
+      var realVars, tempVars, v, _i, _len, _ref2;
+      realVars = [];
+      tempVars = [];
+      _ref2 = this.variables;
+      for (_i = 0, _len = _ref2.length; _i < _len; _i++) {
+        v = _ref2[_i];
+        if (v.type === 'var') {
+          (v.name.charAt(0) === '_' ? tempVars : realVars).push(v.name);
+        }
+      }
+      return realVars.sort().concat(tempVars.sort());
+    };
+    Scope.prototype.assignedVariables = function() {
+      var v, _i, _len, _ref2, _results;
+      _ref2 = this.variables;
+      _results = [];
+      for (_i = 0, _len = _ref2.length; _i < _len; _i++) {
+        v = _ref2[_i];
+        if (v.type.assigned) {
+          _results.push("" + v.name + " = " + v.type.value);
+        }
+      }
+      return _results;
+    };
+    return Scope;
+  })();
+}).call(this);
+return exports;
+}());(function () {
+var exports = __MODULES['nodes'] = {};
+(function() {
+  var Access, Arr, Assign, Base, Block, Call, Class, Closure, Code, Comment, Existence, Extends, For, IDENTIFIER, IDENTIFIER_STR, IS_STRING, If, In, Index, LEVEL_ACCESS, LEVEL_COND, LEVEL_LIST, LEVEL_OP, LEVEL_PAREN, LEVEL_TOP, Literal, METHOD_DEF, NEGATE, NO, Obj, Op, Param, Parens, Push, Range, Return, SIMPLENUM, Scope, Slice, Splat, Switch, TAB, THIS, Throw, Try, UTILITIES, Value, While, YES, compact, del, ends, extend, flatten, last, merge, multident, starts, unfoldSoak, utility, _ref;
+  var __hasProp = Object.prototype.hasOwnProperty, __extends = function(child, parent) {
+    for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; }
+    function ctor() { this.constructor = child; }
+    ctor.prototype = parent.prototype;
+    child.prototype = new ctor;
+    child.__super__ = parent.prototype;
+    return child;
+  }, __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, __indexOf = Array.prototype.indexOf || function(item) {
+    for (var i = 0, l = this.length; i < l; i++) {
+      if (this[i] === item) return i;
+    }
+    return -1;
+  };
+  Scope = require('./scope').Scope;
+  _ref = require('./helpers'), compact = _ref.compact, flatten = _ref.flatten, extend = _ref.extend, merge = _ref.merge, del = _ref.del, starts = _ref.starts, ends = _ref.ends, last = _ref.last;
+  exports.extend = extend;
+  YES = function() {
+    return true;
+  };
+  NO = function() {
+    return false;
+  };
+  THIS = function() {
+    return this;
+  };
+  NEGATE = function() {
+    this.negated = !this.negated;
+    return this;
+  };
+  exports.Base = Base = (function() {
+    function Base() {}
+    Base.prototype.compile = function(o, lvl) {
+      var node;
+      o = extend({}, o);
+      if (lvl) {
+        o.level = lvl;
+      }
+      node = this.unfoldSoak(o) || this;
+      node.tab = o.indent;
+      if (o.level === LEVEL_TOP || !node.isStatement(o)) {
+        return node.compileNode(o);
+      } else {
+        return node.compileClosure(o);
+      }
+    };
+    Base.prototype.compileClosure = function(o) {
+      if (this.jumps() || this instanceof Throw) {
+        throw SyntaxError('cannot use a pure statement in an expression.');
+      }
+      o.sharedScope = true;
+      return Closure.wrap(this).compileNode(o);
+    };
+    Base.prototype.cache = function(o, level, reused) {
+      var ref, sub;
+      if (!this.isComplex()) {
+        ref = level ? this.compile(o, level) : this;
+        return [ref, ref];
+      } else {
+        ref = new Literal(reused || o.scope.freeVariable('ref'));
+        sub = new Assign(ref, this);
+        if (level) {
+          return [sub.compile(o, level), ref.value];
+        } else {
+          return [sub, ref];
+        }
+      }
+    };
+    Base.prototype.compileLoopReference = function(o, name) {
+      var src, tmp;
+      src = tmp = this.compile(o, LEVEL_LIST);
+      if (!((-Infinity < +src && +src < Infinity) || IDENTIFIER.test(src) && o.scope.check(src, true))) {
+        src = "" + (tmp = o.scope.freeVariable(name)) + " = " + src;
+      }
+      return [src, tmp];
+    };
+    Base.prototype.makeReturn = function() {
+      return new Return(this);
+    };
+    Base.prototype.contains = function(pred) {
+      var contains;
+      contains = false;
+      this.traverseChildren(false, function(node) {
+        if (pred(node)) {
+          contains = true;
+          return false;
+        }
+      });
+      return contains;
+    };
+    Base.prototype.containsType = function(type) {
+      return this instanceof type || this.contains(function(node) {
+        return node instanceof type;
+      });
+    };
+    Base.prototype.lastNonComment = function(list) {
+      var i;
+      i = list.length;
+      while (i--) {
+        if (!(list[i] instanceof Comment)) {
+          return list[i];
+        }
+      }
+      return null;
+    };
+    Base.prototype.toString = function(idt, name) {
+      var tree;
+      if (idt == null) {
+        idt = '';
+      }
+      if (name == null) {
+        name = this.constructor.name;
+      }
+      tree = '\n' + idt + name;
+      if (this.soak) {
+        tree += '?';
+      }
+      this.eachChild(function(node) {
+        return tree += node.toString(idt + TAB);
+      });
+      return tree;
+    };
+    Base.prototype.eachChild = function(func) {
+      var attr, child, _i, _j, _len, _len2, _ref2, _ref3;
+      if (!this.children) {
+        return this;
+      }
+      _ref2 = this.children;
+      for (_i = 0, _len = _ref2.length; _i < _len; _i++) {
+        attr = _ref2[_i];
+        if (this[attr]) {
+          _ref3 = flatten([this[attr]]);
+          for (_j = 0, _len2 = _ref3.length; _j < _len2; _j++) {
+            child = _ref3[_j];
+            if (func(child) === false) {
+              return this;
+            }
+          }
+        }
+      }
+      return this;
+    };
+    Base.prototype.traverseChildren = function(crossScope, func) {
+      return this.eachChild(function(child) {
+        if (func(child) === false) {
+          return false;
+        }
+        return child.traverseChildren(crossScope, func);
+      });
+    };
+    Base.prototype.invert = function() {
+      return new Op('!', this);
+    };
+    Base.prototype.unwrapAll = function() {
+      var node;
+      node = this;
+      while (node !== (node = node.unwrap())) {
+        continue;
+      }
+      return node;
+    };
+    Base.prototype.children = [];
+    Base.prototype.isStatement = NO;
+    Base.prototype.jumps = NO;
+    Base.prototype.isComplex = YES;
+    Base.prototype.isChainable = NO;
+    Base.prototype.isAssignable = NO;
+    Base.prototype.unwrap = THIS;
+    Base.prototype.unfoldSoak = NO;
+    Base.prototype.assigns = NO;
+    return Base;
+  })();
+  exports.Block = Block = (function() {
+    __extends(Block, Base);
+    function Block(nodes) {
+      this.expressions = compact(flatten(nodes || []));
+    }
+    Block.prototype.children = ['expressions'];
+    Block.prototype.push = function(node) {
+      this.expressions.push(node);
+      return this;
+    };
+    Block.prototype.pop = function() {
+      return this.expressions.pop();
+    };
+    Block.prototype.unshift = function(node) {
+      this.expressions.unshift(node);
+      return this;
+    };
+    Block.prototype.unwrap = function() {
+      if (this.expressions.length === 1) {
+        return this.expressions[0];
+      } else {
+        return this;
+      }
+    };
+    Block.prototype.isEmpty = function() {
+      return !this.expressions.length;
+    };
+    Block.prototype.isStatement = function(o) {
+      var exp, _i, _len, _ref2;
+      _ref2 = this.expressions;
+      for (_i = 0, _len = _ref2.length; _i < _len; _i++) {
+        exp = _ref2[_i];
+        if (exp.isStatement(o)) {
+          return true;
+        }
+      }
+      return false;
+    };
+    Block.prototype.jumps = function(o) {
+      var exp, _i, _len, _ref2;
+      _ref2 = this.expressions;
+      for (_i = 0, _len = _ref2.length; _i < _len; _i++) {
+        exp = _ref2[_i];
+        if (exp.jumps(o)) {
+          return exp;
+        }
+      }
+    };
+    Block.prototype.makeReturn = function() {
+      var expr, len;
+      len = this.expressions.length;
+      while (len--) {
+        expr = this.expressions[len];
+        if (!(expr instanceof Comment)) {
+          this.expressions[len] = expr.makeReturn();
+          if (expr instanceof Return && !expr.expression) {
+            this.expressions.splice(len, 1);
+          }
+          break;
+        }
+      }
+      return this;
+    };
+    Block.prototype.compile = function(o, level) {
+      if (o == null) {
+        o = {};
+      }
+      if (o.scope) {
+        return Block.__super__.compile.call(this, o, level);
+      } else {
+        return this.compileRoot(o);
+      }
+    };
+    Block.prototype.compileNode = function(o) {
+      var code, codes, node, top, _i, _len, _ref2;
+      this.tab = o.indent;
+      top = o.level === LEVEL_TOP;
+      codes = [];
+      _ref2 = this.expressions;
+      for (_i = 0, _len = _ref2.length; _i < _len; _i++) {
+        node = _ref2[_i];
+        node = node.unwrapAll();
+        node = node.unfoldSoak(o) || node;
+        if (node instanceof Block) {
+          codes.push(node.compileNode(o));
+        } else if (top) {
+          node.front = true;
+          code = node.compile(o);
+          codes.push(node.isStatement(o) ? code : this.tab + code + ';');
+        } else {
+          codes.push(node.compile(o, LEVEL_LIST));
+        }
+      }
+      if (top) {
+        return codes.join('\n');
+      }
+      code = codes.join(', ') || 'void 0';
+      if (codes.length > 1 && o.level >= LEVEL_LIST) {
+        return "(" + code + ")";
+      } else {
+        return code;
+      }
+    };
+    Block.prototype.compileRoot = function(o) {
+      var code;
+      o.indent = this.tab = o.bare ? '' : TAB;
+      o.scope = new Scope(null, this, null);
+      o.level = LEVEL_TOP;
+      code = this.compileWithDeclarations(o);
+      if (o.bare) {
+        return code;
+      } else {
+        return "(function() {\n" + code + "\n}).call(this);\n";
+      }
+    };
+    Block.prototype.compileWithDeclarations = function(o) {
+      var assigns, code, declars, exp, i, post, rest, scope, _len, _ref2;
+      code = post = '';
+      _ref2 = this.expressions;
+      for (i = 0, _len = _ref2.length; i < _len; i++) {
+        exp = _ref2[i];
+        exp = exp.unwrap();
+        if (!(exp instanceof Comment || exp instanceof Literal)) {
+          break;
+        }
+      }
+      o = merge(o, {
+        level: LEVEL_TOP
+      });
+      if (i) {
+        rest = this.expressions.splice(i, this.expressions.length);
+        code = this.compileNode(o);
+        this.expressions = rest;
+      }
+      post = this.compileNode(o);
+      scope = o.scope;
+      if (scope.expressions === this) {
+        declars = o.scope.hasDeclarations();
+        assigns = scope.hasAssignments;
+        if ((declars || assigns) && i) {
+          code += '\n';
+        }
+        if (declars) {
+          code += "" + this.tab + "var " + (scope.declaredVariables().join(', ')) + ";\n";
+        }
+        if (assigns) {
+          code += "" + this.tab + "var " + (multident(scope.assignedVariables().join(', '), this.tab)) + ";\n";
+        }
+      }
+      return code + post;
+    };
+    Block.wrap = function(nodes) {
+      if (nodes.length === 1 && nodes[0] instanceof Block) {
+        return nodes[0];
+      }
+      return new Block(nodes);
+    };
+    return Block;
+  })();
+  exports.Literal = Literal = (function() {
+    __extends(Literal, Base);
+    function Literal(value) {
+      this.value = value;
+    }
+    Literal.prototype.makeReturn = function() {
+      if (this.isStatement()) {
+        return this;
+      } else {
+        return new Return(this);
+      }
+    };
+    Literal.prototype.isAssignable = function() {
+      return IDENTIFIER.test(this.value);
+    };
+    Literal.prototype.isStatement = function() {
+      var _ref2;
+      return (_ref2 = this.value) === 'break' || _ref2 === 'continue' || _ref2 === 'debugger';
+    };
+    Literal.prototype.isComplex = NO;
+    Literal.prototype.assigns = function(name) {
+      return name === this.value;
+    };
+    Literal.prototype.jumps = function(o) {
+      if (!this.isStatement()) {
+        return false;
+      }
+      if (!(o && (o.loop || o.block && (this.value !== 'continue')))) {
+        return this;
+      } else {
+        return false;
+      }
+    };
+    Literal.prototype.compileNode = function(o) {
+      var code;
+      code = this.isUndefined ? o.level >= LEVEL_ACCESS ? '(void 0)' : 'void 0' : this.value.reserved ? "\"" + this.value + "\"" : this.value;
+      if (this.isStatement()) {
+        return "" + this.tab + code + ";";
+      } else {
+        return code;
+      }
+    };
+    Literal.prototype.toString = function() {
+      return ' "' + this.value + '"';
+    };
+    return Literal;
+  })();
+  exports.Return = Return = (function() {
+    __extends(Return, Base);
+    function Return(expr) {
+      if (expr && !expr.unwrap().isUndefined) {
+        this.expression = expr;
+      }
+    }
+    Return.prototype.children = ['expression'];
+    Return.prototype.isStatement = YES;
+    Return.prototype.makeReturn = THIS;
+    Return.prototype.jumps = THIS;
+    Return.prototype.compile = function(o, level) {
+      var expr, _ref2;
+      expr = (_ref2 = this.expression) != null ? _ref2.makeReturn() : void 0;
+      if (expr && !(expr instanceof Return)) {
+        return expr.compile(o, level);
+      } else {
+        return Return.__super__.compile.call(this, o, level);
+      }
+    };
+    Return.prototype.compileNode = function(o) {
+      return this.tab + ("return" + (this.expression ? ' ' + this.expression.compile(o, LEVEL_PAREN) : '') + ";");
+    };
+    return Return;
+  })();
+  exports.Value = Value = (function() {
+    __extends(Value, Base);
+    function Value(base, props, tag) {
+      if (!props && base instanceof Value) {
+        return base;
+      }
+      this.base = base;
+      this.properties = props || [];
+      if (tag) {
+        this[tag] = true;
+      }
+      return this;
+    }
+    Value.prototype.children = ['base', 'properties'];
+    Value.prototype.push = function(prop) {
+      this.properties.push(prop);
+      return this;
+    };
+    Value.prototype.hasProperties = function() {
+      return !!this.properties.length;
+    };
+    Value.prototype.isArray = function() {
+      return !this.properties.length && this.base instanceof Arr;
+    };
+    Value.prototype.isComplex = function() {
+      return this.hasProperties() || this.base.isComplex();
+    };
+    Value.prototype.isAssignable = function() {
+      return this.hasProperties() || this.base.isAssignable();
+    };
+    Value.prototype.isSimpleNumber = function() {
+      return this.base instanceof Literal && SIMPLENUM.test(this.base.value);
+    };
+    Value.prototype.isAtomic = function() {
+      var node, _i, _len, _ref2;
+      _ref2 = this.properties.concat(this.base);
+      for (_i = 0, _len = _ref2.length; _i < _len; _i++) {
+        node = _ref2[_i];
+        if (node.soak || node instanceof Call) {
+          return false;
+        }
+      }
+      return true;
+    };
+    Value.prototype.isStatement = function(o) {
+      return !this.properties.length && this.base.isStatement(o);
+    };
+    Value.prototype.assigns = function(name) {
+      return !this.properties.length && this.base.assigns(name);
+    };
+    Value.prototype.jumps = function(o) {
+      return !this.properties.length && this.base.jumps(o);
+    };
+    Value.prototype.isObject = function(onlyGenerated) {
+      if (this.properties.length) {
+        return false;
+      }
+      return (this.base instanceof Obj) && (!onlyGenerated || this.base.generated);
+    };
+    Value.prototype.isSplice = function() {
+      return last(this.properties) instanceof Slice;
+    };
+    Value.prototype.makeReturn = function() {
+      if (this.properties.length) {
+        return Value.__super__.makeReturn.call(this);
+      } else {
+        return this.base.makeReturn();
+      }
+    };
+    Value.prototype.unwrap = function() {
+      if (this.properties.length) {
+        return this;
+      } else {
+        return this.base;
+      }
+    };
+    Value.prototype.cacheReference = function(o) {
+      var base, bref, name, nref;
+      name = last(this.properties);
+      if (this.properties.length < 2 && !this.base.isComplex() && !(name != null ? name.isComplex() : void 0)) {
+        return [this, this];
+      }
+      base = new Value(this.base, this.properties.slice(0, -1));
+      if (base.isComplex()) {
+        bref = new Literal(o.scope.freeVariable('base'));
+        base = new Value(new Parens(new Assign(bref, base)));
+      }
+      if (!name) {
+        return [base, bref];
+      }
+      if (name.isComplex()) {
+        nref = new Literal(o.scope.freeVariable('name'));
+        name = new Index(new Assign(nref, name.index));
+        nref = new Index(nref);
+      }
+      return [base.push(name), new Value(bref || base.base, [nref || name])];
+    };
+    Value.prototype.compileNode = function(o) {
+      var code, prop, props, _i, _len;
+      this.base.front = this.front;
+      props = this.properties;
+      code = this.base.compile(o, props.length ? LEVEL_ACCESS : null);
+      if ((this.base instanceof Parens || props.length) && SIMPLENUM.test(code)) {
+        code = "" + code + ".";
+      }
+      for (_i = 0, _len = props.length; _i < _len; _i++) {
+        prop = props[_i];
+        code += prop.compile(o);
+      }
+      return code;
+    };
+    Value.prototype.unfoldSoak = function(o) {
+      var result;
+      if (this.unfoldedSoak != null) {
+        return this.unfoldedSoak;
+      }
+      result = __bind(function() {
+        var fst, i, ifn, prop, ref, snd, _len, _ref2;
+        if (ifn = this.base.unfoldSoak(o)) {
+          Array.prototype.push.apply(ifn.body.properties, this.properties);
+          return ifn;
+        }
+        _ref2 = this.properties;
+        for (i = 0, _len = _ref2.length; i < _len; i++) {
+          prop = _ref2[i];
+          if (prop.soak) {
+            prop.soak = false;
+            fst = new Value(this.base, this.properties.slice(0, i));
+            snd = new Value(this.base, this.properties.slice(i));
+            if (fst.isComplex()) {
+              ref = new Literal(o.scope.freeVariable('ref'));
+              fst = new Parens(new Assign(ref, fst));
+              snd.base = ref;
+            }
+            return new If(new Existence(fst), snd, {
+              soak: true
+            });
+          }
+        }
+        return null;
+      }, this)();
+      return this.unfoldedSoak = result || false;
+    };
+    return Value;
+  })();
+  exports.Comment = Comment = (function() {
+    __extends(Comment, Base);
+    function Comment(comment) {
+      this.comment = comment;
+    }
+    Comment.prototype.isStatement = YES;
+    Comment.prototype.makeReturn = THIS;
+    Comment.prototype.compileNode = function(o, level) {
+      var code;
+      code = '/*' + multident(this.comment, this.tab) + '*/';
+      if ((level || o.level) === LEVEL_TOP) {
+        code = o.indent + code;
+      }
+      return code;
+    };
+    return Comment;
+  })();
+  exports.Call = Call = (function() {
+    __extends(Call, Base);
+    function Call(variable, args, soak) {
+      this.args = args != null ? args : [];
+      this.soak = soak;
+      this.isNew = false;
+      this.isSuper = variable === 'super';
+      this.variable = this.isSuper ? null : variable;
+    }
+    Call.prototype.children = ['variable', 'args'];
+    Call.prototype.newInstance = function() {
+      var base;
+      base = this.variable.base || this.variable;
+      if (base instanceof Call && !base.isNew) {
+        base.newInstance();
+      } else {
+        this.isNew = true;
+      }
+      return this;
+    };
+    Call.prototype.superReference = function(o) {
+      var method, name;
+      method = o.scope.method;
+      if (!method) {
+        throw SyntaxError('cannot call super outside of a function.');
+      }
+      name = method.name;
+      if (name == null) {
+        throw SyntaxError('cannot call super on an anonymous function.');
+      }
+      if (method.klass) {
+        return (new Value(new Literal(method.klass), [new Access(new Literal("__super__")), new Access(new Literal(name))])).compile(o);
+      } else {
+        return "" + name + ".__super__.constructor";
+      }
+    };
+    Call.prototype.unfoldSoak = function(o) {
+      var call, ifn, left, list, rite, _i, _len, _ref2, _ref3;
+      if (this.soak) {
+        if (this.variable) {
+          if (ifn = unfoldSoak(o, this, 'variable')) {
+            return ifn;
+          }
+          _ref2 = new Value(this.variable).cacheReference(o), left = _ref2[0], rite = _ref2[1];
+        } else {
+          left = new Literal(this.superReference(o));
+          rite = new Value(left);
+        }
+        rite = new Call(rite, this.args);
+        rite.isNew = this.isNew;
+        left = new Literal("typeof " + (left.compile(o)) + " === \"function\"");
+        return new If(left, new Value(rite), {
+          soak: true
+        });
+      }
+      call = this;
+      list = [];
+      while (true) {
+        if (call.variable instanceof Call) {
+          list.push(call);
+          call = call.variable;
+          continue;
+        }
+        if (!(call.variable instanceof Value)) {
+          break;
+        }
+        list.push(call);
+        if (!((call = call.variable.base) instanceof Call)) {
+          break;
+        }
+      }
+      _ref3 = list.reverse();
+      for (_i = 0, _len = _ref3.length; _i < _len; _i++) {
+        call = _ref3[_i];
+        if (ifn) {
+          if (call.variable instanceof Call) {
+            call.variable = ifn;
+          } else {
+            call.variable.base = ifn;
+          }
+        }
+        ifn = unfoldSoak(o, call, 'variable');
+      }
+      return ifn;
+    };
+    Call.prototype.filterImplicitObjects = function(list) {
+      var node, nodes, obj, prop, properties, _i, _j, _len, _len2, _ref2;
+      nodes = [];
+      for (_i = 0, _len = list.length; _i < _len; _i++) {
+        node = list[_i];
+        if (!((typeof node.isObject === "function" ? node.isObject() : void 0) && node.base.generated)) {
+          nodes.push(node);
+          continue;
+        }
+        obj = null;
+        _ref2 = node.base.properties;
+        for (_j = 0, _len2 = _ref2.length; _j < _len2; _j++) {
+          prop = _ref2[_j];
+          if (prop instanceof Assign || prop instanceof Comment) {
+            if (!obj) {
+              nodes.push(obj = new Obj(properties = [], true));
+            }
+            properties.push(prop);
+          } else {
+            nodes.push(prop);
+            obj = null;
+          }
+        }
+      }
+      return nodes;
+    };
+    Call.prototype.compileNode = function(o) {
+      var arg, args, code, _ref2;
+      if ((_ref2 = this.variable) != null) {
+        _ref2.front = this.front;
+      }
+      if (code = Splat.compileSplattedArray(o, this.args, true)) {
+        return this.compileSplat(o, code);
+      }
+      args = this.filterImplicitObjects(this.args);
+      args = ((function() {
+        var _i, _len, _results;
+        _results = [];
+        for (_i = 0, _len = args.length; _i < _len; _i++) {
+          arg = args[_i];
+          _results.push(arg.compile(o, LEVEL_LIST));
+        }
+        return _results;
+      })()).join(', ');
+      if (this.isSuper) {
+        return this.superReference(o) + (".call(this" + (args && ', ' + args) + ")");
+      } else {
+        return (this.isNew ? 'new ' : '') + this.variable.compile(o, LEVEL_ACCESS) + ("(" + args + ")");
+      }
+    };
+    Call.prototype.compileSuper = function(args, o) {
+      return "" + (this.superReference(o)) + ".call(this" + (args.length ? ', ' : '') + args + ")";
+    };
+    Call.prototype.compileSplat = function(o, splatArgs) {
+      var base, fun, idt, name, ref;
+      if (this.isSuper) {
+        return "" + (this.superReference(o)) + ".apply(this, " + splatArgs + ")";
+      }
+      if (this.isNew) {
+        idt = this.tab + TAB;
+        return "(function(func, args, ctor) {\n" + idt + "ctor.prototype = func.prototype;\n" + idt + "var child = new ctor, result = func.apply(child, args);\n" + idt + "return typeof result === \"object\" ? result : child;\n" + this.tab + "})(" + (this.variable.compile(o, LEVEL_LIST)) + ", " + splatArgs + ", function() {})";
+      }
+      base = new Value(this.variable);
+      if ((name = base.properties.pop()) && base.isComplex()) {
+        ref = o.scope.freeVariable('ref');
+        fun = "(" + ref + " = " + (base.compile(o, LEVEL_LIST)) + ")" + (name.compile(o));
+      } else {
+        fun = base.compile(o, LEVEL_ACCESS);
+        if (SIMPLENUM.test(fun)) {
+          fun = "(" + fun + ")";
+        }
+        if (name) {
+          ref = fun;
+          fun += name.compile(o);
+        } else {
+          ref = 'null';
+        }
+      }
+      return "" + fun + ".apply(" + ref + ", " + splatArgs + ")";
+    };
+    return Call;
+  })();
+  exports.Extends = Extends = (function() {
+    __extends(Extends, Base);
+    function Extends(child, parent) {
+      this.child = child;
+      this.parent = parent;
+    }
+    Extends.prototype.children = ['child', 'parent'];
+    Extends.prototype.compile = function(o) {
+      utility('hasProp');
+      return new Call(new Value(new Literal(utility('extends'))), [this.child, this.parent]).compile(o);
+    };
+    return Extends;
+  })();
+  exports.Access = Access = (function() {
+    __extends(Access, Base);
+    function Access(name, tag) {
+      this.name = name;
+      this.name.asKey = true;
+      this.proto = tag === 'proto' ? '.prototype' : '';
+      this.soak = tag === 'soak';
+    }
+    Access.prototype.children = ['name'];
+    Access.prototype.compile = function(o) {
+      var name;
+      name = this.name.compile(o);
+      return this.proto + (IDENTIFIER.test(name) ? "." + name : "[" + name + "]");
+    };
+    Access.prototype.isComplex = NO;
+    return Access;
+  })();
+  exports.Index = Index = (function() {
+    __extends(Index, Base);
+    function Index(index) {
+      this.index = index;
+    }
+    Index.prototype.children = ['index'];
+    Index.prototype.compile = function(o) {
+      return (this.proto ? '.prototype' : '') + ("[" + (this.index.compile(o, LEVEL_PAREN)) + "]");
+    };
+    Index.prototype.isComplex = function() {
+      return this.index.isComplex();
+    };
+    return Index;
+  })();
+  exports.Range = Range = (function() {
+    __extends(Range, Base);
+    Range.prototype.children = ['from', 'to'];
+    function Range(from, to, tag) {
+      this.from = from;
+      this.to = to;
+      this.exclusive = tag === 'exclusive';
+      this.equals = this.exclusive ? '' : '=';
+    }
+    Range.prototype.compileVariables = function(o) {
+      var step, _ref2, _ref3, _ref4, _ref5;
+      o = merge(o, {
+        top: true
+      });
+      _ref2 = this.from.cache(o, LEVEL_LIST), this.fromC = _ref2[0], this.fromVar = _ref2[1];
+      _ref3 = this.to.cache(o, LEVEL_LIST), this.toC = _ref3[0], this.toVar = _ref3[1];
+      if (step = del(o, 'step')) {
+        _ref4 = step.cache(o, LEVEL_LIST), this.step = _ref4[0], this.stepVar = _ref4[1];
+      }
+      _ref5 = [this.fromVar.match(SIMPLENUM), this.toVar.match(SIMPLENUM)], this.fromNum = _ref5[0], this.toNum = _ref5[1];
+      if (this.stepVar) {
+        return this.stepNum = this.stepVar.match(SIMPLENUM);
+      }
+    };
+    Range.prototype.compileNode = function(o) {
+      var cond, condPart, from, gt, idx, known, lt, stepPart, to, varPart, _ref2, _ref3;
+      if (!this.fromVar) {
+        this.compileVariables(o);
+      }
+      if (!o.index) {
+        return this.compileArray(o);
+      }
+      known = this.fromNum && this.toNum;
+      idx = del(o, 'index');
+      varPart = "" + idx + " = " + this.fromC;
+      if (this.toC !== this.toVar) {
+        varPart += ", " + this.toC;
+      }
+      if (this.step !== this.stepVar) {
+        varPart += ", " + this.step;
+      }
+      _ref2 = ["" + idx + " <" + this.equals, "" + idx + " >" + this.equals], lt = _ref2[0], gt = _ref2[1];
+      condPart = this.stepNum ? condPart = +this.stepNum > 0 ? "" + lt + " " + this.toVar : "" + gt + " " + this.toVar : known ? ((_ref3 = [+this.fromNum, +this.toNum], from = _ref3[0], to = _ref3[1], _ref3), condPart = from <= to ? "" + lt + " " + to : "" + gt + " " + to) : (cond = "" + this.fromVar + " <= " + this.toVar, condPart = "" + cond + " ? " + lt + " " + this.toVar + " : " + gt + " " + this.toVar);
+      stepPart = this.stepVar ? "" + idx + " += " + this.stepVar : known ? from <= to ? "" + idx + "++" : "" + idx + "--" : "" + cond + " ? " + idx + "++ : " + idx + "--";
+      return "" + varPart + "; " + condPart + "; " + stepPart;
+    };
+    Range.prototype.compileArray = function(o) {
+      var args, body, cond, hasArgs, i, idt, post, pre, range, result, vars, _i, _ref2, _ref3, _results;
+      if (this.fromNum && this.toNum && Math.abs(this.fromNum - this.toNum) <= 20) {
+        range = (function() {
+          _results = [];
+          for (var _i = _ref2 = +this.fromNum, _ref3 = +this.toNum; _ref2 <= _ref3 ? _i <= _ref3 : _i >= _ref3; _ref2 <= _ref3 ? _i++ : _i--){ _results.push(_i); }
+          return _results;
+        }).apply(this);
+        if (this.exclusive) {
+          range.pop();
+        }
+        return "[" + (range.join(', ')) + "]";
+      }
+      idt = this.tab + TAB;
+      i = o.scope.freeVariable('i');
+      result = o.scope.freeVariable('results');
+      pre = "\n" + idt + result + " = [];";
+      if (this.fromNum && this.toNum) {
+        o.index = i;
+        body = this.compileNode(o);
+      } else {
+        vars = ("" + i + " = " + this.fromC) + (this.toC !== this.toVar ? ", " + this.toC : '');
+        cond = "" + this.fromVar + " <= " + this.toVar;
+        body = "var " + vars + "; " + cond + " ? " + i + " <" + this.equals + " " + this.toVar + " : " + i + " >" + this.equals + " " + this.toVar + "; " + cond + " ? " + i + "++ : " + i + "--";
+      }
+      post = "{ " + result + ".push(" + i + "); }\n" + idt + "return " + result + ";\n" + o.indent;
+      hasArgs = function(node) {
+        return node != null ? node.contains(function(n) {
+          return n instanceof Literal && n.value === 'arguments' && !n.asKey;
+        }) : void 0;
+      };
+      if (hasArgs(this.from) || hasArgs(this.to)) {
+        args = ', arguments';
+      }
+      return "(function() {" + pre + "\n" + idt + "for (" + body + ")" + post + "}).apply(this" + (args != null ? args : '') + ")";
+    };
+    return Range;
+  })();
+  exports.Slice = Slice = (function() {
+    __extends(Slice, Base);
+    Slice.prototype.children = ['range'];
+    function Slice(range) {
+      this.range = range;
+      Slice.__super__.constructor.call(this);
+    }
+    Slice.prototype.compileNode = function(o) {
+      var compiled, from, fromStr, to, toStr, _ref2;
+      _ref2 = this.range, to = _ref2.to, from = _ref2.from;
+      fromStr = from && from.compile(o, LEVEL_PAREN) || '0';
+      compiled = to && to.compile(o, LEVEL_PAREN);
+      if (to && !(!this.range.exclusive && +compiled === -1)) {
+        toStr = ', ' + (this.range.exclusive ? compiled : SIMPLENUM.test(compiled) ? (+compiled + 1).toString() : "(" + compiled + " + 1) || 9e9");
+      }
+      return ".slice(" + fromStr + (toStr || '') + ")";
+    };
+    return Slice;
+  })();
+  exports.Obj = Obj = (function() {
+    __extends(Obj, Base);
+    function Obj(props, generated) {
+      this.generated = generated != null ? generated : false;
+      this.objects = this.properties = props || [];
+    }
+    Obj.prototype.children = ['properties'];
+    Obj.prototype.compileNode = function(o) {
+      var i, idt, indent, join, lastNoncom, node, obj, prop, props, _i, _len;
+      props = this.properties;
+      if (!props.length) {
+        if (this.front) {
+          return '({})';
+        } else {
+          return '{}';
+        }
+      }
+      if (this.generated) {
+        for (_i = 0, _len = props.length; _i < _len; _i++) {
+          node = props[_i];
+          if (node instanceof Value) {
+            throw new Error('cannot have an implicit value in an implicit object');
+          }
+        }
+      }
+      idt = o.indent += TAB;
+      lastNoncom = this.lastNonComment(this.properties);
+      props = (function() {
+        var _len2, _results;
+        _results = [];
+        for (i = 0, _len2 = props.length; i < _len2; i++) {
+          prop = props[i];
+          join = i === props.length - 1 ? '' : prop === lastNoncom || prop instanceof Comment ? '\n' : ',\n';
+          indent = prop instanceof Comment ? '' : idt;
+          if (prop instanceof Value && prop["this"]) {
+            prop = new Assign(prop.properties[0].name, prop, 'object');
+          }
+          if (!(prop instanceof Comment)) {
+            if (!(prop instanceof Assign)) {
+              prop = new Assign(prop, prop, 'object');
+            }
+            (prop.variable.base || prop.variable).asKey = true;
+          }
+          _results.push(indent + prop.compile(o, LEVEL_TOP) + join);
+        }
+        return _results;
+      })();
+      props = props.join('');
+      obj = "{" + (props && '\n' + props + '\n' + this.tab) + "}";
+      if (this.front) {
+        return "(" + obj + ")";
+      } else {
+        return obj;
+      }
+    };
+    Obj.prototype.assigns = function(name) {
+      var prop, _i, _len, _ref2;
+      _ref2 = this.properties;
+      for (_i = 0, _len = _ref2.length; _i < _len; _i++) {
+        prop = _ref2[_i];
+        if (prop.assigns(name)) {
+          return true;
+        }
+      }
+      return false;
+    };
+    return Obj;
+  })();
+  exports.Arr = Arr = (function() {
+    __extends(Arr, Base);
+    function Arr(objs) {
+      this.objects = objs || [];
+    }
+    Arr.prototype.children = ['objects'];
+    Arr.prototype.filterImplicitObjects = Call.prototype.filterImplicitObjects;
+    Arr.prototype.compileNode = function(o) {
+      var code, obj, objs;
+      if (!this.objects.length) {
+        return '[]';
+      }
+      o.indent += TAB;
+      objs = this.filterImplicitObjects(this.objects);
+      if (code = Splat.compileSplattedArray(o, objs)) {
+        return code;
+      }
+      code = ((function() {
+        var _i, _len, _results;
+        _results = [];
+        for (_i = 0, _len = objs.length; _i < _len; _i++) {
+          obj = objs[_i];
+          _results.push(obj.compile(o, LEVEL_LIST));
+        }
+        return _results;
+      })()).join(', ');
+      if (code.indexOf('\n') >= 0) {
+        return "[\n" + o.indent + code + "\n" + this.tab + "]";
+      } else {
+        return "[" + code + "]";
+      }
+    };
+    Arr.prototype.assigns = function(name) {
+      var obj, _i, _len, _ref2;
+      _ref2 = this.objects;
+      for (_i = 0, _len = _ref2.length; _i < _len; _i++) {
+        obj = _ref2[_i];
+        if (obj.assigns(name)) {
+          return true;
+        }
+      }
+      return false;
+    };
+    return Arr;
+  })();
+  exports.Class = Class = (function() {
+    __extends(Class, Base);
+    function Class(variable, parent, body) {
+      this.variable = variable;
+      this.parent = parent;
+      this.body = body != null ? body : new Block;
+      this.boundFuncs = [];
+      this.body.classBody = true;
+    }
+    Class.prototype.children = ['variable', 'parent', 'body'];
+    Class.prototype.determineName = function() {
+      var decl, tail;
+      if (!this.variable) {
+        return null;
+      }
+      decl = (tail = last(this.variable.properties)) ? tail instanceof Access && tail.name.value : this.variable.base.value;
+      return decl && (decl = IDENTIFIER.test(decl) && decl);
+    };
+    Class.prototype.setContext = function(name) {
+      return this.body.traverseChildren(false, function(node) {
+        if (node.classBody) {
+          return false;
+        }
+        if (node instanceof Literal && node.value === 'this') {
+          return node.value = name;
+        } else if (node instanceof Code) {
+          node.klass = name;
+          if (node.bound) {
+            return node.context = name;
+          }
+        }
+      });
+    };
+    Class.prototype.addBoundFunctions = function(o) {
+      var bvar, lhs, _i, _len, _ref2, _results;
+      if (this.boundFuncs.length) {
+        _ref2 = this.boundFuncs;
+        _results = [];
+        for (_i = 0, _len = _ref2.length; _i < _len; _i++) {
+          bvar = _ref2[_i];
+          lhs = (new Value(new Literal("this"), [new Access(bvar)])).compile(o);
+          _results.push(this.ctor.body.unshift(new Literal("" + lhs + " = " + (utility('bind')) + "(" + lhs + ", this)")));
+        }
+        return _results;
+      }
+    };
+    Class.prototype.addProperties = function(node, name, o) {
+      var assign, base, exprs, func, props;
+      props = node.base.properties.slice(0);
+      exprs = (function() {
+        var _results;
+        _results = [];
+        while (assign = props.shift()) {
+          if (assign instanceof Assign) {
+            base = assign.variable.base;
+            delete assign.context;
+            func = assign.value;
+            if (base.value === 'constructor') {
+              if (this.ctor) {
+                throw new Error('cannot define more than one constructor in a class');
+              }
+              if (func.bound) {
+                throw new Error('cannot define a constructor as a bound function');
+              }
+              if (func instanceof Code) {
+                assign = this.ctor = func;
+              } else {
+                this.externalCtor = o.scope.freeVariable('class');
+                assign = new Assign(new Literal(this.externalCtor), func);
+              }
+            } else {
+              if (!assign.variable["this"]) {
+                assign.variable = new Value(new Literal(name), [new Access(base, 'proto')]);
+              }
+              if (func instanceof Code && func.bound) {
+                this.boundFuncs.push(base);
+                func.bound = false;
+              }
+            }
+          }
+          _results.push(assign);
+        }
+        return _results;
+      }).call(this);
+      return compact(exprs);
+    };
+    Class.prototype.walkBody = function(name, o) {
+      return this.traverseChildren(false, __bind(function(child) {
+        var exps, i, node, _len, _ref2;
+        if (child instanceof Class) {
+          return false;
+        }
+        if (child instanceof Block) {
+          _ref2 = exps = child.expressions;
+          for (i = 0, _len = _ref2.length; i < _len; i++) {
+            node = _ref2[i];
+            if (node instanceof Value && node.isObject(true)) {
+              exps[i] = this.addProperties(node, name, o);
+            }
+          }
+          return child.expressions = exps = flatten(exps);
+        }
+      }, this));
+    };
+    Class.prototype.ensureConstructor = function(name) {
+      if (!this.ctor) {
+        this.ctor = new Code;
+        if (this.parent) {
+          this.ctor.body.push(new Literal("" + name + ".__super__.constructor.apply(this, arguments)"));
+        }
+        if (this.externalCtor) {
+          this.ctor.body.push(new Literal("" + this.externalCtor + ".apply(this, arguments)"));
+        }
+        this.body.expressions.unshift(this.ctor);
+      }
+      this.ctor.ctor = this.ctor.name = name;
+      this.ctor.klass = null;
+      return this.ctor.noReturn = true;
+    };
+    Class.prototype.compileNode = function(o) {
+      var decl, klass, lname, name;
+      decl = this.determineName();
+      name = decl || this.name || '_Class';
+      lname = new Literal(name);
+      this.setContext(name);
+      this.walkBody(name, o);
+      this.ensureConstructor(name);
+      if (this.parent) {
+        this.body.expressions.unshift(new Extends(lname, this.parent));
+      }
+      if (!(this.ctor instanceof Code)) {
+        this.body.expressions.unshift(this.ctor);
+      }
+      this.body.expressions.push(lname);
+      this.addBoundFunctions(o);
+      klass = new Parens(Closure.wrap(this.body), true);
+      if (this.variable) {
+        klass = new Assign(this.variable, klass);
+      }
+      return klass.compile(o);
+    };
+    return Class;
+  })();
+  exports.Assign = Assign = (function() {
+    __extends(Assign, Base);
+    function Assign(variable, value, context, options) {
+      this.variable = variable;
+      this.value = value;
+      this.context = context;
+      this.param = options && options.param;
+    }
+    Assign.prototype.children = ['variable', 'value'];
+    Assign.prototype.isStatement = function(o) {
+      return (o != null ? o.level : void 0) === LEVEL_TOP && (this.context != null) && __indexOf.call(this.context, "?") >= 0;
+    };
+    Assign.prototype.assigns = function(name) {
+      return this[this.context === 'object' ? 'value' : 'variable'].assigns(name);
+    };
+    Assign.prototype.unfoldSoak = function(o) {
+      return unfoldSoak(o, this, 'variable');
+    };
+    Assign.prototype.compileNode = function(o) {
+      var isValue, match, name, val, _ref2, _ref3, _ref4, _ref5;
+      if (isValue = this.variable instanceof Value) {
+        if (this.variable.isArray() || this.variable.isObject()) {
+          return this.compilePatternMatch(o);
+        }
+        if (this.variable.isSplice()) {
+          return this.compileSplice(o);
+        }
+        if ((_ref2 = this.context) === '||=' || _ref2 === '&&=' || _ref2 === '?=') {
+          return this.compileConditional(o);
+        }
+      }
+      name = this.variable.compile(o, LEVEL_LIST);
+      if (!(this.context || this.variable.isAssignable())) {
+        throw SyntaxError("\"" + (this.variable.compile(o)) + "\" cannot be assigned.");
+      }
+      if (!(this.context || isValue && (this.variable.namespaced || this.variable.hasProperties()))) {
+        if (this.param) {
+          o.scope.add(name, 'var');
+        } else {
+          o.scope.find(name);
+        }
+      }
+      if (this.value instanceof Code && (match = METHOD_DEF.exec(name))) {
+        if (match[1]) {
+          this.value.klass = match[1];
+        }
+        this.value.name = (_ref3 = (_ref4 = (_ref5 = match[2]) != null ? _ref5 : match[3]) != null ? _ref4 : match[4]) != null ? _ref3 : match[5];
+      }
+      val = this.value.compile(o, LEVEL_LIST);
+      if (this.context === 'object') {
+        return "" + name + ": " + val;
+      }
+      val = name + (" " + (this.context || '=') + " ") + val;
+      if (o.level <= LEVEL_LIST) {
+        return val;
+      } else {
+        return "(" + val + ")";
+      }
+    };
+    Assign.prototype.compilePatternMatch = function(o) {
+      var acc, assigns, code, i, idx, isObject, ivar, obj, objects, olen, ref, rest, splat, top, val, value, vvar, _len, _ref2, _ref3, _ref4, _ref5;
+      top = o.level === LEVEL_TOP;
+      value = this.value;
+      objects = this.variable.base.objects;
+      if (!(olen = objects.length)) {
+        code = value.compile(o);
+        if (o.level >= LEVEL_OP) {
+          return "(" + code + ")";
+        } else {
+          return code;
+        }
+      }
+      isObject = this.variable.isObject();
+      if (top && olen === 1 && !((obj = objects[0]) instanceof Splat)) {
+        if (obj instanceof Assign) {
+          _ref2 = obj, idx = _ref2.variable.base, obj = _ref2.value;
+        } else {
+          if (obj.base instanceof Parens) {
+            _ref3 = new Value(obj.unwrapAll()).cacheReference(o), obj = _ref3[0], idx = _ref3[1];
+          } else {
+            idx = isObject ? obj["this"] ? obj.properties[0].name : obj : new Literal(0);
+          }
+        }
+        acc = IDENTIFIER.test(idx.unwrap().value || 0);
+        value = new Value(value);
+        value.properties.push(new (acc ? Access : Index)(idx));
+        return new Assign(obj, value, null, {
+          param: this.param
+        }).compile(o, LEVEL_TOP);
+      }
+      vvar = value.compile(o, LEVEL_LIST);
+      assigns = [];
+      splat = false;
+      if (!IDENTIFIER.test(vvar) || this.variable.assigns(vvar)) {
+        assigns.push("" + (ref = o.scope.freeVariable('ref')) + " = " + vvar);
+        vvar = ref;
+      }
+      for (i = 0, _len = objects.length; i < _len; i++) {
+        obj = objects[i];
+        idx = i;
+        if (isObject) {
+          if (obj instanceof Assign) {
+            _ref4 = obj, idx = _ref4.variable.base, obj = _ref4.value;
+          } else {
+            if (obj.base instanceof Parens) {
+              _ref5 = new Value(obj.unwrapAll()).cacheReference(o), obj = _ref5[0], idx = _ref5[1];
+            } else {
+              idx = obj["this"] ? obj.properties[0].name : obj;
+            }
+          }
+        }
+        if (!splat && obj instanceof Splat) {
+          val = "" + olen + " <= " + vvar + ".length ? " + (utility('slice')) + ".call(" + vvar + ", " + i;
+          if (rest = olen - i - 1) {
+            ivar = o.scope.freeVariable('i');
+            val += ", " + ivar + " = " + vvar + ".length - " + rest + ") : (" + ivar + " = " + i + ", [])";
+          } else {
+            val += ") : []";
+          }
+          val = new Literal(val);
+          splat = "" + ivar + "++";
+        } else {
+          if (obj instanceof Splat) {
+            obj = obj.name.compile(o);
+            throw SyntaxError("multiple splats are disallowed in an assignment: " + obj + " ...");
+          }
+          if (typeof idx === 'number') {
+            idx = new Literal(splat || idx);
+            acc = false;
+          } else {
+            acc = isObject && IDENTIFIER.test(idx.unwrap().value || 0);
+          }
+          val = new Value(new Literal(vvar), [new (acc ? Access : Index)(idx)]);
+        }
+        assigns.push(new Assign(obj, val, null, {
+          param: this.param
+        }).compile(o, LEVEL_TOP));
+      }
+      if (!top) {
+        assigns.push(vvar);
+      }
+      code = assigns.join(', ');
+      if (o.level < LEVEL_LIST) {
+        return code;
+      } else {
+        return "(" + code + ")";
+      }
+    };
+    Assign.prototype.compileConditional = function(o) {
+      var left, rite, _ref2;
+      _ref2 = this.variable.cacheReference(o), left = _ref2[0], rite = _ref2[1];
+      if (__indexOf.call(this.context, "?") >= 0) {
+        o.isExistentialEquals = true;
+      }
+      return new Op(this.context.slice(0, -1), left, new Assign(rite, this.value, '=')).compile(o);
+    };
+    Assign.prototype.compileSplice = function(o) {
+      var code, exclusive, from, fromDecl, fromRef, name, to, valDef, valRef, _ref2, _ref3, _ref4;
+      _ref2 = this.variable.properties.pop().range, from = _ref2.from, to = _ref2.to, exclusive = _ref2.exclusive;
+      name = this.variable.compile(o);
+      _ref3 = (from != null ? from.cache(o, LEVEL_OP) : void 0) || ['0', '0'], fromDecl = _ref3[0], fromRef = _ref3[1];
+      if (to) {
+        if ((from != null ? from.isSimpleNumber() : void 0) && to.isSimpleNumber()) {
+          to = +to.compile(o) - +fromRef;
+          if (!exclusive) {
+            to += 1;
+          }
+        } else {
+          to = to.compile(o) + ' - ' + fromRef;
+          if (!exclusive) {
+            to += ' + 1';
+          }
+        }
+      } else {
+        to = "9e9";
+      }
+      _ref4 = this.value.cache(o, LEVEL_LIST), valDef = _ref4[0], valRef = _ref4[1];
+      code = "[].splice.apply(" + name + ", [" + fromDecl + ", " + to + "].concat(" + valDef + ")), " + valRef;
+      if (o.level > LEVEL_TOP) {
+        return "(" + code + ")";
+      } else {
+        return code;
+      }
+    };
+    return Assign;
+  })();
+  exports.Code = Code = (function() {
+    __extends(Code, Base);
+    function Code(params, body, tag) {
+      this.params = params || [];
+      this.body = body || new Block;
+      this.bound = tag === 'boundfunc';
+      if (this.bound) {
+        this.context = 'this';
+      }
+    }
+    Code.prototype.children = ['params', 'body'];
+    Code.prototype.isStatement = function() {
+      return !!this.ctor;
+    };
+    Code.prototype.jumps = NO;
+    Code.prototype.compileNode = function(o) {
+      var code, exprs, i, idt, lit, p, param, ref, splats, v, val, vars, wasEmpty, _i, _j, _k, _len, _len2, _len3, _len4, _ref2, _ref3, _ref4, _ref5;
+      o.scope = new Scope(o.scope, this.body, this);
+      o.scope.shared = del(o, 'sharedScope');
+      o.indent += TAB;
+      delete o.bare;
+      vars = [];
+      exprs = [];
+      _ref2 = this.params;
+      for (_i = 0, _len = _ref2.length; _i < _len; _i++) {
+        param = _ref2[_i];
+        if (param.splat) {
+          _ref3 = this.params;
+          for (_j = 0, _len2 = _ref3.length; _j < _len2; _j++) {
+            p = _ref3[_j];
+            if (p.name.value) {
+              o.scope.add(p.name.value, 'var', true);
+            }
+          }
+          splats = new Assign(new Value(new Arr((function() {
+            var _k, _len3, _ref4, _results;
+            _ref4 = this.params;
+            _results = [];
+            for (_k = 0, _len3 = _ref4.length; _k < _len3; _k++) {
+              p = _ref4[_k];
+              _results.push(p.asReference(o));
+            }
+            return _results;
+          }).call(this))), new Value(new Literal('arguments')));
+          break;
+        }
+      }
+      _ref4 = this.params;
+      for (_k = 0, _len3 = _ref4.length; _k < _len3; _k++) {
+        param = _ref4[_k];
+        if (param.isComplex()) {
+          val = ref = param.asReference(o);
+          if (param.value) {
+            val = new Op('?', ref, param.value);
+          }
+          exprs.push(new Assign(new Value(param.name), val, '=', {
+            param: true
+          }));
+        } else {
+          ref = param;
+          if (param.value) {
+            lit = new Literal(ref.name.value + ' == null');
+            val = new Assign(new Value(param.name), param.value, '=');
+            exprs.push(new If(lit, val));
+          }
+        }
+        if (!splats) {
+          vars.push(ref);
+        }
+      }
+      wasEmpty = this.body.isEmpty();
+      if (splats) {
+        exprs.unshift(splats);
+      }
+      if (exprs.length) {
+        (_ref5 = this.body.expressions).unshift.apply(_ref5, exprs);
+      }
+      if (!splats) {
+        for (i = 0, _len4 = vars.length; i < _len4; i++) {
+          v = vars[i];
+          o.scope.parameter(vars[i] = v.compile(o));
+        }
+      }
+      if (!(wasEmpty || this.noReturn)) {
+        this.body.makeReturn();
+      }
+      idt = o.indent;
+      code = 'function';
+      if (this.ctor) {
+        code += ' ' + this.name;
+      }
+      code += '(' + vars.join(', ') + ') {';
+      if (!this.body.isEmpty()) {
+        code += "\n" + (this.body.compileWithDeclarations(o)) + "\n" + this.tab;
+      }
+      code += '}';
+      if (this.ctor) {
+        return this.tab + code;
+      }
+      if (this.bound) {
+        return utility('bind') + ("(" + code + ", " + this.context + ")");
+      }
+      if (this.front || (o.level >= LEVEL_ACCESS)) {
+        return "(" + code + ")";
+      } else {
+        return code;
+      }
+    };
+    Code.prototype.traverseChildren = function(crossScope, func) {
+      if (crossScope) {
+        return Code.__super__.traverseChildren.call(this, crossScope, func);
+      }
+    };
+    return Code;
+  })();
+  exports.Param = Param = (function() {
+    __extends(Param, Base);
+    function Param(name, value, splat) {
+      this.name = name;
+      this.value = value;
+      this.splat = splat;
+    }
+    Param.prototype.children = ['name', 'value'];
+    Param.prototype.compile = function(o) {
+      return this.name.compile(o, LEVEL_LIST);
+    };
+    Param.prototype.asReference = function(o) {
+      var node;
+      if (this.reference) {
+        return this.reference;
+      }
+      node = this.name;
+      if (node["this"]) {
+        node = node.properties[0].name;
+        if (node.value.reserved) {
+          node = new Literal('_' + node.value);
+        }
+      } else if (node.isComplex()) {
+        node = new Literal(o.scope.freeVariable('arg'));
+      }
+      node = new Value(node);
+      if (this.splat) {
+        node = new Splat(node);
+      }
+      return this.reference = node;
+    };
+    Param.prototype.isComplex = function() {
+      return this.name.isComplex();
+    };
+    return Param;
+  })();
+  exports.Splat = Splat = (function() {
+    __extends(Splat, Base);
+    Splat.prototype.children = ['name'];
+    Splat.prototype.isAssignable = YES;
+    function Splat(name) {
+      this.name = name.compile ? name : new Literal(name);
+    }
+    Splat.prototype.assigns = function(name) {
+      return this.name.assigns(name);
+    };
+    Splat.prototype.compile = function(o) {
+      if (this.index != null) {
+        return this.compileParam(o);
+      } else {
+        return this.name.compile(o);
+      }
+    };
+    Splat.compileSplattedArray = function(o, list, apply) {
+      var args, base, code, i, index, node, _len;
+      index = -1;
+      while ((node = list[++index]) && !(node instanceof Splat)) {
+        continue;
+      }
+      if (index >= list.length) {
+        return '';
+      }
+      if (list.length === 1) {
+        code = list[0].compile(o, LEVEL_LIST);
+        if (apply) {
+          return code;
+        }
+        return "" + (utility('slice')) + ".call(" + code + ")";
+      }
+      args = list.slice(index);
+      for (i = 0, _len = args.length; i < _len; i++) {
+        node = args[i];
+        code = node.compile(o, LEVEL_LIST);
+        args[i] = node instanceof Splat ? "" + (utility('slice')) + ".call(" + code + ")" : "[" + code + "]";
+      }
+      if (index === 0) {
+        return args[0] + (".concat(" + (args.slice(1).join(', ')) + ")");
+      }
+      base = (function() {
+        var _i, _len2, _ref2, _results;
+        _ref2 = list.slice(0, index);
+        _results = [];
+        for (_i = 0, _len2 = _ref2.length; _i < _len2; _i++) {
+          node = _ref2[_i];
+          _results.push(node.compile(o, LEVEL_LIST));
+        }
+        return _results;
+      })();
+      return "[" + (base.join(', ')) + "].concat(" + (args.join(', ')) + ")";
+    };
+    return Splat;
+  })();
+  exports.While = While = (function() {
+    __extends(While, Base);
+    function While(condition, options) {
+      this.condition = (options != null ? options.invert : void 0) ? condition.invert() : condition;
+      this.guard = options != null ? options.guard : void 0;
+    }
+    While.prototype.children = ['condition', 'guard', 'body'];
+    While.prototype.isStatement = YES;
+    While.prototype.makeReturn = function() {
+      this.returns = true;
+      return this;
+    };
+    While.prototype.addBody = function(body) {
+      this.body = body;
+      return this;
+    };
+    While.prototype.jumps = function() {
+      var expressions, node, _i, _len;
+      expressions = this.body.expressions;
+      if (!expressions.length) {
+        return false;
+      }
+      for (_i = 0, _len = expressions.length; _i < _len; _i++) {
+        node = expressions[_i];
+        if (node.jumps({
+          loop: true
+        })) {
+          return node;
+        }
+      }
+      return false;
+    };
+    While.prototype.compileNode = function(o) {
+      var body, code, rvar, set;
+      o.indent += TAB;
+      set = '';
+      body = this.body;
+      if (body.isEmpty()) {
+        body = '';
+      } else {
+        if (o.level > LEVEL_TOP || this.returns) {
+          rvar = o.scope.freeVariable('results');
+          set = "" + this.tab + rvar + " = [];\n";
+          if (body) {
+            body = Push.wrap(rvar, body);
+          }
+        }
+        if (this.guard) {
+          body = Block.wrap([new If(this.guard, body)]);
+        }
+        body = "\n" + (body.compile(o, LEVEL_TOP)) + "\n" + this.tab;
+      }
+      code = set + this.tab + ("while (" + (this.condition.compile(o, LEVEL_PAREN)) + ") {" + body + "}");
+      if (this.returns) {
+        code += "\n" + this.tab + "return " + rvar + ";";
+      }
+      return code;
+    };
+    return While;
+  })();
+  exports.Op = Op = (function() {
+    var CONVERSIONS, INVERSIONS;
+    __extends(Op, Base);
+    function Op(op, first, second, flip) {
+      var call;
+      if (op === 'in') {
+        return new In(first, second);
+      }
+      if (op === 'do') {
+        call = new Call(first, first.params || []);
+        call["do"] = true;
+        return call;
+      }
+      if (op === 'new') {
+        if (first instanceof Call && !first["do"] && !first.isNew) {
+          return first.newInstance();
+        }
+        if (first instanceof Code && first.bound || first["do"]) {
+          first = new Parens(first);
+        }
+      }
+      this.operator = CONVERSIONS[op] || op;
+      this.first = first;
+      this.second = second;
+      this.flip = !!flip;
+      return this;
+    }
+    CONVERSIONS = {
+      '==': '===',
+      '!=': '!==',
+      'of': 'in'
+    };
+    INVERSIONS = {
+      '!==': '===',
+      '===': '!=='
+    };
+    Op.prototype.children = ['first', 'second'];
+    Op.prototype.isSimpleNumber = NO;
+    Op.prototype.isUnary = function() {
+      return !this.second;
+    };
+    Op.prototype.isComplex = function() {
+      var _ref2;
+      return !(this.isUnary() && ((_ref2 = this.operator) === '+' || _ref2 === '-')) || this.first.isComplex();
+    };
+    Op.prototype.isChainable = function() {
+      var _ref2;
+      return (_ref2 = this.operator) === '<' || _ref2 === '>' || _ref2 === '>=' || _ref2 === '<=' || _ref2 === '===' || _ref2 === '!==';
+    };
+    Op.prototype.invert = function() {
+      var allInvertable, curr, fst, op, _ref2;
+      if (this.isChainable() && this.first.isChainable()) {
+        allInvertable = true;
+        curr = this;
+        while (curr && curr.operator) {
+          allInvertable && (allInvertable = curr.operator in INVERSIONS);
+          curr = curr.first;
+        }
+        if (!allInvertable) {
+          return new Parens(this).invert();
+        }
+        curr = this;
+        while (curr && curr.operator) {
+          curr.invert = !curr.invert;
+          curr.operator = INVERSIONS[curr.operator];
+          curr = curr.first;
+        }
+        return this;
+      } else if (op = INVERSIONS[this.operator]) {
+        this.operator = op;
+        if (this.first.unwrap() instanceof Op) {
+          this.first.invert();
+        }
+        return this;
+      } else if (this.second) {
+        return new Parens(this).invert();
+      } else if (this.operator === '!' && (fst = this.first.unwrap()) instanceof Op && ((_ref2 = fst.operator) === '!' || _ref2 === 'in' || _ref2 === 'instanceof')) {
+        return fst;
+      } else {
+        return new Op('!', this);
+      }
+    };
+    Op.prototype.unfoldSoak = function(o) {
+      var _ref2;
+      return ((_ref2 = this.operator) === '++' || _ref2 === '--' || _ref2 === 'delete') && unfoldSoak(o, this, 'first');
+    };
+    Op.prototype.compileNode = function(o) {
+      var code;
+      if (this.isUnary()) {
+        return this.compileUnary(o);
+      }
+      if (this.isChainable() && this.first.isChainable()) {
+        return this.compileChain(o);
+      }
+      if (this.operator === '?') {
+        return this.compileExistence(o);
+      }
+      this.first.front = this.front;
+      code = this.first.compile(o, LEVEL_OP) + ' ' + this.operator + ' ' + this.second.compile(o, LEVEL_OP);
+      if (o.level <= LEVEL_OP) {
+        return code;
+      } else {
+        return "(" + code + ")";
+      }
+    };
+    Op.prototype.compileChain = function(o) {
+      var code, fst, shared, _ref2;
+      _ref2 = this.first.second.cache(o), this.first.second = _ref2[0], shared = _ref2[1];
+      fst = this.first.compile(o, LEVEL_OP);
+      code = "" + fst + " " + (this.invert ? '&&' : '||') + " " + (shared.compile(o)) + " " + this.operator + " " + (this.second.compile(o, LEVEL_OP));
+      return "(" + code + ")";
+    };
+    Op.prototype.compileExistence = function(o) {
+      var fst, ref;
+      if (this.first.isComplex()) {
+        ref = new Literal(o.scope.freeVariable('ref'));
+        fst = new Parens(new Assign(ref, this.first));
+      } else {
+        fst = this.first;
+        ref = fst;
+      }
+      return new If(new Existence(fst), ref, {
+        type: 'if'
+      }).addElse(this.second).compile(o);
+    };
+    Op.prototype.compileUnary = function(o) {
+      var op, parts;
+      parts = [op = this.operator];
+      if ((op === 'new' || op === 'typeof' || op === 'delete') || (op === '+' || op === '-') && this.first instanceof Op && this.first.operator === op) {
+        parts.push(' ');
+      }
+      if (op === 'new' && this.first.isStatement(o)) {
+        this.first = new Parens(this.first);
+      }
+      parts.push(this.first.compile(o, LEVEL_OP));
+      if (this.flip) {
+        parts.reverse();
+      }
+      return parts.join('');
+    };
+    Op.prototype.toString = function(idt) {
+      return Op.__super__.toString.call(this, idt, this.constructor.name + ' ' + this.operator);
+    };
+    return Op;
+  })();
+  exports.In = In = (function() {
+    __extends(In, Base);
+    function In(object, array) {
+      this.object = object;
+      this.array = array;
+    }
+    In.prototype.children = ['object', 'array'];
+    In.prototype.invert = NEGATE;
+    In.prototype.compileNode = function(o) {
+      var hasSplat, obj, _i, _len, _ref2;
+      if (this.array instanceof Value && this.array.isArray()) {
+        _ref2 = this.array.base.objects;
+        for (_i = 0, _len = _ref2.length; _i < _len; _i++) {
+          obj = _ref2[_i];
+          if (obj instanceof Splat) {
+            hasSplat = true;
+            break;
+          }
+        }
+        if (!hasSplat) {
+          return this.compileOrTest(o);
+        }
+      }
+      return this.compileLoopTest(o);
+    };
+    In.prototype.compileOrTest = function(o) {
+      var cmp, cnj, i, item, ref, sub, tests, _ref2, _ref3;
+      _ref2 = this.object.cache(o, LEVEL_OP), sub = _ref2[0], ref = _ref2[1];
+      _ref3 = this.negated ? [' !== ', ' && '] : [' === ', ' || '], cmp = _ref3[0], cnj = _ref3[1];
+      tests = (function() {
+        var _len, _ref4, _results;
+        _ref4 = this.array.base.objects;
+        _results = [];
+        for (i = 0, _len = _ref4.length; i < _len; i++) {
+          item = _ref4[i];
+          _results.push((i ? ref : sub) + cmp + item.compile(o, LEVEL_OP));
+        }
+        return _results;
+      }).call(this);
+      if (tests.length === 0) {
+        return 'false';
+      }
+      tests = tests.join(cnj);
+      if (o.level < LEVEL_OP) {
+        return tests;
+      } else {
+        return "(" + tests + ")";
+      }
+    };
+    In.prototype.compileLoopTest = function(o) {
+      var code, ref, sub, _ref2;
+      _ref2 = this.object.cache(o, LEVEL_LIST), sub = _ref2[0], ref = _ref2[1];
+      code = utility('indexOf') + (".call(" + (this.array.compile(o, LEVEL_LIST)) + ", " + ref + ") ") + (this.negated ? '< 0' : '>= 0');
+      if (sub === ref) {
+        return code;
+      }
+      code = sub + ', ' + code;
+      if (o.level < LEVEL_LIST) {
+        return code;
+      } else {
+        return "(" + code + ")";
+      }
+    };
+    In.prototype.toString = function(idt) {
+      return In.__super__.toString.call(this, idt, this.constructor.name + (this.negated ? '!' : ''));
+    };
+    return In;
+  })();
+  exports.Try = Try = (function() {
+    __extends(Try, Base);
+    function Try(attempt, error, recovery, ensure) {
+      this.attempt = attempt;
+      this.error = error;
+      this.recovery = recovery;
+      this.ensure = ensure;
+    }
+    Try.prototype.children = ['attempt', 'recovery', 'ensure'];
+    Try.prototype.isStatement = YES;
+    Try.prototype.jumps = function(o) {
+      var _ref2;
+      return this.attempt.jumps(o) || ((_ref2 = this.recovery) != null ? _ref2.jumps(o) : void 0);
+    };
+    Try.prototype.makeReturn = function() {
+      if (this.attempt) {
+        this.attempt = this.attempt.makeReturn();
+      }
+      if (this.recovery) {
+        this.recovery = this.recovery.makeReturn();
+      }
+      return this;
+    };
+    Try.prototype.compileNode = function(o) {
+      var catchPart, errorPart;
+      o.indent += TAB;
+      errorPart = this.error ? " (" + (this.error.compile(o)) + ") " : ' ';
+      catchPart = this.recovery ? (o.scope.add(this.error.value, 'param'), " catch" + errorPart + "{\n" + (this.recovery.compile(o, LEVEL_TOP)) + "\n" + this.tab + "}") : !(this.ensure || this.recovery) ? ' catch (_e) {}' : void 0;
+      return ("" + this.tab + "try {\n" + (this.attempt.compile(o, LEVEL_TOP)) + "\n" + this.tab + "}" + (catchPart || '')) + (this.ensure ? " finally {\n" + (this.ensure.compile(o, LEVEL_TOP)) + "\n" + this.tab + "}" : '');
+    };
+    return Try;
+  })();
+  exports.Throw = Throw = (function() {
+    __extends(Throw, Base);
+    function Throw(expression) {
+      this.expression = expression;
+    }
+    Throw.prototype.children = ['expression'];
+    Throw.prototype.isStatement = YES;
+    Throw.prototype.jumps = NO;
+    Throw.prototype.makeReturn = THIS;
+    Throw.prototype.compileNode = function(o) {
+      return this.tab + ("throw " + (this.expression.compile(o)) + ";");
+    };
+    return Throw;
+  })();
+  exports.Existence = Existence = (function() {
+    __extends(Existence, Base);
+    function Existence(expression) {
+      this.expression = expression;
+    }
+    Existence.prototype.children = ['expression'];
+    Existence.prototype.invert = NEGATE;
+    Existence.prototype.compileNode = function(o) {
+      var cmp, cnj, code, _ref2;
+      code = this.expression.compile(o, LEVEL_OP);
+      code = IDENTIFIER.test(code) && !o.scope.check(code) ? ((_ref2 = this.negated ? ['===', '||'] : ['!==', '&&'], cmp = _ref2[0], cnj = _ref2[1], _ref2), "typeof " + code + " " + cmp + " \"undefined\" " + cnj + " " + code + " " + cmp + " null") : "" + code + " " + (this.negated ? '==' : '!=') + " null";
+      if (o.level <= LEVEL_COND) {
+        return code;
+      } else {
+        return "(" + code + ")";
+      }
+    };
+    return Existence;
+  })();
+  exports.Parens = Parens = (function() {
+    __extends(Parens, Base);
+    function Parens(body) {
+      this.body = body;
+    }
+    Parens.prototype.children = ['body'];
+    Parens.prototype.unwrap = function() {
+      return this.body;
+    };
+    Parens.prototype.isComplex = function() {
+      return this.body.isComplex();
+    };
+    Parens.prototype.makeReturn = function() {
+      return this.body.makeReturn();
+    };
+    Parens.prototype.compileNode = function(o) {
+      var bare, code, expr;
+      expr = this.body.unwrap();
+      if (expr instanceof Value && expr.isAtomic()) {
+        expr.front = this.front;
+        return expr.compile(o);
+      }
+      code = expr.compile(o, LEVEL_PAREN);
+      bare = o.level < LEVEL_OP && (expr instanceof Op || expr instanceof Call || (expr instanceof For && expr.returns));
+      if (bare) {
+        return code;
+      } else {
+        return "(" + code + ")";
+      }
+    };
+    return Parens;
+  })();
+  exports.For = For = (function() {
+    __extends(For, Base);
+    function For(body, source) {
+      var _ref2;
+      this.source = source.source, this.guard = source.guard, this.step = source.step, this.name = source.name, this.index = source.index;
+      this.body = Block.wrap([body]);
+      this.own = !!source.own;
+      this.object = !!source.object;
+      if (this.object) {
+        _ref2 = [this.index, this.name], this.name = _ref2[0], this.index = _ref2[1];
+      }
+      if (this.index instanceof Value) {
+        throw SyntaxError('index cannot be a pattern matching expression');
+      }
+      this.range = this.source instanceof Value && this.source.base instanceof Range && !this.source.properties.length;
+      this.pattern = this.name instanceof Value;
+      if (this.range && this.index) {
+        throw SyntaxError('indexes do not apply to range loops');
+      }
+      if (this.range && this.pattern) {
+        throw SyntaxError('cannot pattern match over range loops');
+      }
+      this.returns = false;
+    }
+    For.prototype.children = ['body', 'source', 'guard', 'step'];
+    For.prototype.isStatement = YES;
+    For.prototype.jumps = While.prototype.jumps;
+    For.prototype.makeReturn = function() {
+      this.returns = true;
+      return this;
+    };
+    For.prototype.compileNode = function(o) {
+      var body, defPart, forPart, forVarPart, guardPart, idt1, index, ivar, lastJumps, lvar, name, namePart, ref, resultPart, returnResult, rvar, scope, source, stepPart, stepvar, svar, varPart, _ref2;
+      body = Block.wrap([this.body]);
+      lastJumps = (_ref2 = last(body.expressions)) != null ? _ref2.jumps() : void 0;
+      if (lastJumps && lastJumps instanceof Return) {
+        this.returns = false;
+      }
+      source = this.range ? this.source.base : this.source;
+      scope = o.scope;
+      name = this.name && this.name.compile(o, LEVEL_LIST);
+      index = this.index && this.index.compile(o, LEVEL_LIST);
+      if (name && !this.pattern) {
+        scope.find(name, {
+          immediate: true
+        });
+      }
+      if (index) {
+        scope.find(index, {
+          immediate: true
+        });
+      }
+      if (this.returns) {
+        rvar = scope.freeVariable('results');
+      }
+      ivar = (this.range ? name : index) || scope.freeVariable('i');
+      if (this.step && !this.range) {
+        stepvar = scope.freeVariable("step");
+      }
+      if (this.pattern) {
+        name = ivar;
+      }
+      varPart = '';
+      guardPart = '';
+      defPart = '';
+      idt1 = this.tab + TAB;
+      if (this.range) {
+        forPart = source.compile(merge(o, {
+          index: ivar,
+          step: this.step
+        }));
+      } else {
+        svar = this.source.compile(o, LEVEL_LIST);
+        if ((name || this.own) && !IDENTIFIER.test(svar)) {
+          defPart = "" + this.tab + (ref = scope.freeVariable('ref')) + " = " + svar + ";\n";
+          svar = ref;
+        }
+        if (name && !this.pattern) {
+          namePart = "" + name + " = " + svar + "[" + ivar + "]";
+        }
+        if (!this.object) {
+          lvar = scope.freeVariable('len');
+          forVarPart = ("" + ivar + " = 0, " + lvar + " = " + svar + ".length") + (this.step ? ", " + stepvar + " = " + (this.step.compile(o, LEVEL_OP)) : '');
+          stepPart = this.step ? "" + ivar + " += " + stepvar : "" + ivar + "++";
+          forPart = "" + forVarPart + "; " + ivar + " < " + lvar + "; " + stepPart;
+        }
+      }
+      if (this.returns) {
+        resultPart = "" + this.tab + rvar + " = [];\n";
+        returnResult = "\n" + this.tab + "return " + rvar + ";";
+        body = Push.wrap(rvar, body);
+      }
+      if (this.guard) {
+        body = Block.wrap([new If(this.guard, body)]);
+      }
+      if (this.pattern) {
+        body.expressions.unshift(new Assign(this.name, new Literal("" + svar + "[" + ivar + "]")));
+      }
+      defPart += this.pluckDirectCall(o, body);
+      if (namePart) {
+        varPart = "\n" + idt1 + namePart + ";";
+      }
+      if (this.object) {
+        forPart = "" + ivar + " in " + svar;
+        if (this.own) {
+          guardPart = "\n" + idt1 + "if (!" + (utility('hasProp')) + ".call(" + svar + ", " + ivar + ")) continue;";
+        }
+      }
+      body = body.compile(merge(o, {
+        indent: idt1
+      }), LEVEL_TOP);
+      if (body) {
+        body = '\n' + body + '\n';
+      }
+      return "" + defPart + (resultPart || '') + this.tab + "for (" + forPart + ") {" + guardPart + varPart + body + this.tab + "}" + (returnResult || '');
+    };
+    For.prototype.pluckDirectCall = function(o, body) {
+      var base, defs, expr, fn, idx, ref, val, _len, _ref2, _ref3, _ref4, _ref5, _ref6, _ref7;
+      defs = '';
+      _ref2 = body.expressions;
+      for (idx = 0, _len = _ref2.length; idx < _len; idx++) {
+        expr = _ref2[idx];
+        expr = expr.unwrapAll();
+        if (!(expr instanceof Call)) {
+          continue;
+        }
+        val = expr.variable.unwrapAll();
+        if (!((val instanceof Code) || (val instanceof Value && ((_ref3 = val.base) != null ? _ref3.unwrapAll() : void 0) instanceof Code && val.properties.length === 1 && ((_ref4 = (_ref5 = val.properties[0].name) != null ? _ref5.value : void 0) === 'call' || _ref4 === 'apply')))) {
+          continue;
+        }
+        fn = ((_ref6 = val.base) != null ? _ref6.unwrapAll() : void 0) || val;
+        ref = new Literal(o.scope.freeVariable('fn'));
+        base = new Value(ref);
+        if (val.base) {
+          _ref7 = [base, val], val.base = _ref7[0], base = _ref7[1];
+        }
+        body.expressions[idx] = new Call(base, expr.args);
+        defs += this.tab + new Assign(ref, fn).compile(o, LEVEL_TOP) + ';\n';
+      }
+      return defs;
+    };
+    return For;
+  })();
+  exports.Switch = Switch = (function() {
+    __extends(Switch, Base);
+    function Switch(subject, cases, otherwise) {
+      this.subject = subject;
+      this.cases = cases;
+      this.otherwise = otherwise;
+    }
+    Switch.prototype.children = ['subject', 'cases', 'otherwise'];
+    Switch.prototype.isStatement = YES;
+    Switch.prototype.jumps = function(o) {
+      var block, conds, _i, _len, _ref2, _ref3, _ref4;
+      if (o == null) {
+        o = {
+          block: true
+        };
+      }
+      _ref2 = this.cases;
+      for (_i = 0, _len = _ref2.length; _i < _len; _i++) {
+        _ref3 = _ref2[_i], conds = _ref3[0], block = _ref3[1];
+        if (block.jumps(o)) {
+          return block;
+        }
+      }
+      return (_ref4 = this.otherwise) != null ? _ref4.jumps(o) : void 0;
+    };
+    Switch.prototype.makeReturn = function() {
+      var pair, _i, _len, _ref2, _ref3;
+      _ref2 = this.cases;
+      for (_i = 0, _len = _ref2.length; _i < _len; _i++) {
+        pair = _ref2[_i];
+        pair[1].makeReturn();
+      }
+      if ((_ref3 = this.otherwise) != null) {
+        _ref3.makeReturn();
+      }
+      return this;
+    };
+    Switch.prototype.compileNode = function(o) {
+      var block, body, code, cond, conditions, expr, i, idt1, idt2, _i, _len, _len2, _ref2, _ref3, _ref4, _ref5;
+      idt1 = o.indent + TAB;
+      idt2 = o.indent = idt1 + TAB;
+      code = this.tab + ("switch (" + (((_ref2 = this.subject) != null ? _ref2.compile(o, LEVEL_PAREN) : void 0) || false) + ") {\n");
+      _ref3 = this.cases;
+      for (i = 0, _len = _ref3.length; i < _len; i++) {
+        _ref4 = _ref3[i], conditions = _ref4[0], block = _ref4[1];
+        _ref5 = flatten([conditions]);
+        for (_i = 0, _len2 = _ref5.length; _i < _len2; _i++) {
+          cond = _ref5[_i];
+          if (!this.subject) {
+            cond = cond.invert();
+          }
+          code += idt1 + ("case " + (cond.compile(o, LEVEL_PAREN)) + ":\n");
+        }
+        if (body = block.compile(o, LEVEL_TOP)) {
+          code += body + '\n';
+        }
+        if (i === this.cases.length - 1 && !this.otherwise) {
+          break;
+        }
+        expr = this.lastNonComment(block.expressions);
+        if (expr instanceof Return || (expr instanceof Literal && expr.jumps() && expr.value !== 'debugger')) {
+          continue;
+        }
+        code += idt2 + 'break;\n';
+      }
+      if (this.otherwise && this.otherwise.expressions.length) {
+        code += idt1 + ("default:\n" + (this.otherwise.compile(o, LEVEL_TOP)) + "\n");
+      }
+      return code + this.tab + '}';
+    };
+    return Switch;
+  })();
+  exports.If = If = (function() {
+    __extends(If, Base);
+    function If(condition, body, options) {
+      this.body = body;
+      if (options == null) {
+        options = {};
+      }
+      this.condition = options.type === 'unless' ? condition.invert() : condition;
+      this.elseBody = null;
+      this.isChain = false;
+      this.soak = options.soak;
+    }
+    If.prototype.children = ['condition', 'body', 'elseBody'];
+    If.prototype.bodyNode = function() {
+      var _ref2;
+      return (_ref2 = this.body) != null ? _ref2.unwrap() : void 0;
+    };
+    If.prototype.elseBodyNode = function() {
+      var _ref2;
+      return (_ref2 = this.elseBody) != null ? _ref2.unwrap() : void 0;
+    };
+    If.prototype.addElse = function(elseBody) {
+      if (this.isChain) {
+        this.elseBodyNode().addElse(elseBody);
+      } else {
+        this.isChain = elseBody instanceof If;
+        this.elseBody = this.ensureBlock(elseBody);
+      }
+      return this;
+    };
+    If.prototype.isStatement = function(o) {
+      var _ref2;
+      return (o != null ? o.level : void 0) === LEVEL_TOP || this.bodyNode().isStatement(o) || ((_ref2 = this.elseBodyNode()) != null ? _ref2.isStatement(o) : void 0);
+    };
+    If.prototype.jumps = function(o) {
+      var _ref2;
+      return this.body.jumps(o) || ((_ref2 = this.elseBody) != null ? _ref2.jumps(o) : void 0);
+    };
+    If.prototype.compileNode = function(o) {
+      if (this.isStatement(o)) {
+        return this.compileStatement(o);
+      } else {
+        return this.compileExpression(o);
+      }
+    };
+    If.prototype.makeReturn = function() {
+      this.body && (this.body = new Block([this.body.makeReturn()]));
+      this.elseBody && (this.elseBody = new Block([this.elseBody.makeReturn()]));
+      return this;
+    };
+    If.prototype.ensureBlock = function(node) {
+      if (node instanceof Block) {
+        return node;
+      } else {
+        return new Block([node]);
+      }
+    };
+    If.prototype.compileStatement = function(o) {
+      var body, child, cond, exeq, ifPart;
+      child = del(o, 'chainChild');
+      exeq = del(o, 'isExistentialEquals');
+      if (exeq) {
+        return new If(this.condition.invert(), this.elseBodyNode(), {
+          type: 'if'
+        }).compile(o);
+      }
+      cond = this.condition.compile(o, LEVEL_PAREN);
+      o.indent += TAB;
+      body = this.ensureBlock(this.body).compile(o);
+      if (body) {
+        body = "\n" + body + "\n" + this.tab;
+      }
+      ifPart = "if (" + cond + ") {" + body + "}";
+      if (!child) {
+        ifPart = this.tab + ifPart;
+      }
+      if (!this.elseBody) {
+        return ifPart;
+      }
+      return ifPart + ' else ' + (this.isChain ? (o.indent = this.tab, o.chainChild = true, this.elseBody.unwrap().compile(o, LEVEL_TOP)) : "{\n" + (this.elseBody.compile(o, LEVEL_TOP)) + "\n" + this.tab + "}");
+    };
+    If.prototype.compileExpression = function(o) {
+      var alt, body, code, cond;
+      cond = this.condition.compile(o, LEVEL_COND);
+      body = this.bodyNode().compile(o, LEVEL_LIST);
+      alt = this.elseBodyNode() ? this.elseBodyNode().compile(o, LEVEL_LIST) : 'void 0';
+      code = "" + cond + " ? " + body + " : " + alt;
+      if (o.level >= LEVEL_COND) {
+        return "(" + code + ")";
+      } else {
+        return code;
+      }
+    };
+    If.prototype.unfoldSoak = function() {
+      return this.soak && this;
+    };
+    return If;
+  })();
+  Push = {
+    wrap: function(name, exps) {
+      if (exps.isEmpty() || last(exps.expressions).jumps()) {
+        return exps;
+      }
+      return exps.push(new Call(new Value(new Literal(name), [new Access(new Literal('push'))]), [exps.pop()]));
+    }
+  };
+  Closure = {
+    wrap: function(expressions, statement, noReturn) {
+      var args, call, func, mentionsArgs, meth;
+      if (expressions.jumps()) {
+        return expressions;
+      }
+      func = new Code([], Block.wrap([expressions]));
+      args = [];
+      if ((mentionsArgs = expressions.contains(this.literalArgs)) || expressions.contains(this.literalThis)) {
+        meth = new Literal(mentionsArgs ? 'apply' : 'call');
+        args = [new Literal('this')];
+        if (mentionsArgs) {
+          args.push(new Literal('arguments'));
+        }
+        func = new Value(func, [new Access(meth)]);
+      }
+      func.noReturn = noReturn;
+      call = new Call(func, args);
+      if (statement) {
+        return Block.wrap([call]);
+      } else {
+        return call;
+      }
+    },
+    literalArgs: function(node) {
+      return node instanceof Literal && node.value === 'arguments' && !node.asKey;
+    },
+    literalThis: function(node) {
+      return (node instanceof Literal && node.value === 'this' && !node.asKey) || (node instanceof Code && node.bound);
+    }
+  };
+  unfoldSoak = function(o, parent, name) {
+    var ifn;
+    if (!(ifn = parent[name].unfoldSoak(o))) {
+      return;
+    }
+    parent[name] = ifn.body;
+    ifn.body = new Value(parent);
+    return ifn;
+  };
+  UTILITIES = {
+    "extends": 'function(child, parent) {\n  for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; }\n  function ctor() { this.constructor = child; }\n  ctor.prototype = parent.prototype;\n  child.prototype = new ctor;\n  child.__super__ = parent.prototype;\n  return child;\n}',
+    bind: 'function(fn, me){ return function(){ return fn.apply(me, arguments); }; }',
+    indexOf: 'Array.prototype.indexOf || function(item) {\n  for (var i = 0, l = this.length; i < l; i++) {\n    if (this[i] === item) return i;\n  }\n  return -1;\n}',
+    hasProp: 'Object.prototype.hasOwnProperty',
+    slice: 'Array.prototype.slice'
+  };
+  LEVEL_TOP = 1;
+  LEVEL_PAREN = 2;
+  LEVEL_LIST = 3;
+  LEVEL_COND = 4;
+  LEVEL_OP = 5;
+  LEVEL_ACCESS = 6;
+  TAB = '  ';
+  IDENTIFIER_STR = "[$A-Za-z_\\x7f-\\uffff][$\\w\\x7f-\\uffff]*";
+  IDENTIFIER = RegExp("^" + IDENTIFIER_STR + "$");
+  SIMPLENUM = /^[+-]?\d+$/;
+  METHOD_DEF = RegExp("^(?:(" + IDENTIFIER_STR + ")\\.prototype(?:\\.(" + IDENTIFIER_STR + ")|\\[(\"(?:[^\\\\\"\\r\\n]|\\\\.)*\"|'(?:[^\\\\'\\r\\n]|\\\\.)*')\\]|\\[(0x[\\da-fA-F]+|\\d*\\.?\\d+(?:[eE][+-]?\\d+)?)\\]))|(" + IDENTIFIER_STR + ")$");
+  IS_STRING = /^['"]/;
+  utility = function(name) {
+    var ref;
+    ref = "__" + name;
+    Scope.root.assign(ref, UTILITIES[name]);
+    return ref;
+  };
+  multident = function(code, tab) {
+    return code.replace(/\n/g, '$&' + tab);
+  };
+}).call(this);
+return exports;
+}());(function () {
+var exports = __MODULES['coffee-script'] = {};
+(function() {
+  var Lexer, RESERVED, compile, fs, lexer, parser, path, _ref;
+  var __hasProp = Object.prototype.hasOwnProperty;
+  fs = require('fs');
+  path = require('path');
+  _ref = require('./lexer'), Lexer = _ref.Lexer, RESERVED = _ref.RESERVED;
+  parser = require('./parser').parser;
+  if (require.extensions) {
+    require.extensions['.coffee'] = function(module, filename) {
+      var content;
+      content = compile(fs.readFileSync(filename, 'utf8'), {
+        filename: filename
+      });
+      return module._compile(content, filename);
+    };
+  } else if (require.registerExtension) {
+    require.registerExtension('.coffee', function(content) {
+      return compile(content);
+    });
+  }
+  exports.VERSION = '1.1.2';
+  exports.RESERVED = RESERVED;
+  exports.helpers = require('./helpers');
+  exports.compile = compile = function(code, options) {
+    if (options == null) {
+      options = {};
+    }
+    try {
+      return (parser.parse(lexer.tokenize(code))).compile(options);
+    } catch (err) {
+      if (options.filename) {
+        err.message = "In " + options.filename + ", " + err.message;
+      }
+      throw err;
+    }
+  };
+  exports.tokens = function(code, options) {
+    return lexer.tokenize(code, options);
+  };
+  exports.nodes = function(source, options) {
+    if (typeof source === 'string') {
+      return parser.parse(lexer.tokenize(source, options));
+    } else {
+      return parser.parse(source);
+    }
+  };
+  exports.run = function(code, options) {
+    var Module, mainModule;
+    mainModule = require.main;
+    mainModule.filename = process.argv[1] = options.filename ? fs.realpathSync(options.filename) : '.';
+    mainModule.moduleCache && (mainModule.moduleCache = {});
+    if (process.binding('natives').module) {
+      Module = require('module').Module;
+      mainModule.paths = Module._nodeModulePaths(path.dirname(options.filename));
+    }
+    if (path.extname(mainModule.filename) !== '.coffee' || require.extensions) {
+      return mainModule._compile(compile(code, options), mainModule.filename);
+    } else {
+      return mainModule._compile(code, mainModule.filename);
+    }
+  };
+  exports.eval = function(code, options) {
+    var Module, Script, js, k, o, r, sandbox, v, _i, _len, _module, _ref2, _ref3, _ref4, _require;
+    if (options == null) {
+      options = {};
+    }
+    if (!(code = code.trim())) {
+      return;
+    }
+    if (_ref2 = require('vm'), Script = _ref2.Script, _ref2) {
+      sandbox = Script.createContext();
+      sandbox.global = sandbox.root = sandbox.GLOBAL = sandbox;
+      if (options.sandbox != null) {
+        if (options.sandbox instanceof sandbox.constructor) {
+          sandbox = options.sandbox;
+        } else {
+          _ref3 = options.sandbox;
+          for (k in _ref3) {
+            if (!__hasProp.call(_ref3, k)) continue;
+            v = _ref3[k];
+            sandbox[k] = v;
+          }
+        }
+      }
+      sandbox.__filename = options.filename || 'eval';
+      sandbox.__dirname = path.dirname(sandbox.__filename);
+      if (!(sandbox.module || sandbox.require)) {
+        Module = require('module');
+        sandbox.module = _module = new Module(options.modulename || 'eval');
+        sandbox.require = _require = function(path) {
+          return Module._load(path, _module);
+        };
+        _module.filename = sandbox.__filename;
+        _ref4 = Object.getOwnPropertyNames(require);
+        for (_i = 0, _len = _ref4.length; _i < _len; _i++) {
+          r = _ref4[_i];
+          _require[r] = require[r];
+        }
+        _require.paths = _module.paths = Module._nodeModulePaths(process.cwd());
+        _require.resolve = function(request) {
+          return Module._resolveFilename(request, _module);
+        };
+      }
+    }
+    o = {};
+    for (k in options) {
+      if (!__hasProp.call(options, k)) continue;
+      v = options[k];
+      o[k] = v;
+    }
+    o.bare = true;
+    js = compile(code, o);
+    if (Script) {
+      return Script.runInContext(js, sandbox);
+    } else {
+      return eval(js);
+    }
+  };
+  lexer = new Lexer;
+  parser.lexer = {
+    lex: function() {
+      var tag, _ref2;
+      _ref2 = this.tokens[this.pos++] || [''], tag = _ref2[0], this.yytext = _ref2[1], this.yylineno = _ref2[2];
+      return tag;
+    },
+    setInput: function(tokens) {
+      this.tokens = tokens;
+      return this.pos = 0;
+    },
+    upcomingInput: function() {
+      return "";
+    }
+  };
+  parser.yy = require('./nodes');
+}).call(this);
+return exports;
+}());
+return __MODULES['coffee-script'];
+
+}());
+//END COFFEESCRIPT
+
+    if (typeof window !== "undefined" && window.navigator && window.document) {
+        // Browser action
+        getXhr = function () {
+            //Would love to dump the ActiveX crap in here. Need IE 6 to die first.
+            var xhr, i, progId;
+            if (typeof XMLHttpRequest !== "undefined") {
+                return new XMLHttpRequest();
+            } else {
+                for (i = 0; i < 3; i++) {
+                    progId = progIds[i];
+                    try {
+                        xhr = new ActiveXObject(progId);
+                    } catch (e) {}
+
+                    if (xhr) {
+                        progIds = [progId];  // so faster next time
+                        break;
+                    }
+                }
+            }
+
+            if (!xhr) {
+                throw new Error("getXhr(): XMLHttpRequest not available");
+            }
+
+            return xhr;
+        };
+
+        fetchText = function (url, callback) {
+            var xhr = getXhr();
+            xhr.open('GET', url, true);
+            xhr.onreadystatechange = function (evt) {
+                //Do not explicitly handle errors, those should be
+                //visible via console output in the browser.
+                if (xhr.readyState === 4) {
+                    callback(xhr.responseText);
+                }
+            };
+            xhr.send(null);
+        };
+
+        //Some overrides for the browser env, taken from the
+        //browser.js in the CoffeeScript source.
+        CoffeeScript.eval = function(code, options) {
+            return eval(CoffeeScript.compile(code, options));
+        };
+        CoffeeScript.run = function(code, options) {
+            if (options == null) {
+                options = {};
+            }
+          options.bare = true;
+          return Function(CoffeeScript.compile(code, options))();
+        };
+        // end browser.js adapters
+    } else if (typeof process !== "undefined" &&
+               process.versions &&
+               !!process.versions.node) {
+        //Using special require.nodeRequire, something added by r.js.
+        fs = (require.nodeRequire || require)('fs');
+        fetchText = function (path, callback) {
+            callback(fs.readFileSync(path, 'utf8'));
+        };
+    } else if (typeof Packages !== 'undefined') {
+        //Why Java, why is this so awkward?
+        fetchText = function (path, callback) {
+            var encoding = "utf-8",
+                file = new java.io.File(path),
+                lineSeparator = java.lang.System.getProperty("line.separator"),
+                input = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream(file), encoding)),
+                stringBuffer, line,
+                content = '';
+            try {
+                stringBuffer = new java.lang.StringBuffer();
+                line = input.readLine();
+
+                // Byte Order Mark (BOM) - The Unicode Standard, version 3.0, page 324
+                // http://www.unicode.org/faq/utf_bom.html
+
+                // Note that when we use utf-8, the BOM should appear as "EF BB BF", but it doesn't due to this bug in the JDK:
+                // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4508058
+                if (line && line.length() && line.charAt(0) === 0xfeff) {
+                    // Eat the BOM, since we've already found the encoding on this file,
+                    // and we plan to concatenating this buffer with others; the BOM should
+                    // only appear at the top of a file.
+                    line = line.substring(1);
+                }
+
+                stringBuffer.append(line);
+
+                while ((line = input.readLine()) !== null) {
+                    stringBuffer.append(lineSeparator);
+                    stringBuffer.append(line);
+                }
+                //Make sure we return a JavaScript string and not a Java string.
+                content = String(stringBuffer.toString()); //String
+            } finally {
+                input.close();
+            }
+            callback(content);
+        };
+    }
+//>>excludeEnd('excludeCoffeeScript')
+
+    define({
+
+        //>>excludeStart('excludeCoffeeScript', pragmas.excludeCoffeeScript)
+        get: function () {
+            return CoffeeScript;
+        },
+
+        write: function (pluginName, name, write) {
+            if (name in buildMap) {
+                var text = buildMap[name];
+                write.asModule(pluginName + "!" + name, text);
+            }
+        },
+        //>>excludeEnd('excludeCoffeeScript')
+
+        version: '0.3.1',
+
+        load: function (name, parentRequire, load, config) {
+            //>>excludeStart('excludeCoffeeScript', pragmas.excludeCoffeeScript)
+            var path = parentRequire.toUrl(name + '.coffee');
+            fetchText(path, function (text) {
+
+                //Do CoffeeScript transform.
+                text = CoffeeScript.compile(text, config.CoffeeScript);
+
+                //Hold on to the transformed text if a build.
+                if (config.isBuild) {
+                    buildMap[name] = text;
+                }
+
+                //IE with conditional comments on cannot handle the
+                //sourceURL trick, so skip it if enabled.
+                /*@if (@_jscript) @else @*/
+                if (!config.isBuild) {
+                    text += "\r\n//@ sourceURL=" + path;
+                }
+                /*@end@*/
+
+                load.fromText(name, text);
+
+                //Give result to load. Need to wait until the module
+                //is fully parse, which will happen after this
+                //execution.
+                parentRequire([name], function (value) {
+                    load(value);
+                });
+            });
+            //>>excludeEnd('excludeCoffeeScript')
+        }
+    });
+
+}());
\ No newline at end of file
diff --git a/tests/plugins/coffeescript/csmain.coffee b/tests/plugins/coffeescript/csmain.coffee
new file mode 100644
index 0000000..d509dff
--- /dev/null
+++ b/tests/plugins/coffeescript/csmain.coffee
@@ -0,0 +1,13 @@
+if typeof define isnt 'function'
+  define = (require('../../../amdefine'))(module)
+
+define [
+  'cs!.controller'
+  'cs!./views/view'
+  './views/regular'
+], (controller, view, regular) ->
+  return {
+    controller: controller,
+    regular: regular,
+    view: view
+  }
\ No newline at end of file
diff --git a/tests/plugins/coffeescript/main.js b/tests/plugins/coffeescript/main.js
new file mode 100644
index 0000000..b9b0138
--- /dev/null
+++ b/tests/plugins/coffeescript/main.js
@@ -0,0 +1,6 @@
+if (typeof define !== 'function') { var define = (require('../../../amdefine'))(module); }
+
+//Just testing a plain exports case.
+define(function (require) {
+    return require('./cs!csmain');
+});
diff --git a/tests/plugins/coffeescript/views/regular.js b/tests/plugins/coffeescript/views/regular.js
new file mode 100644
index 0000000..1f85af8
--- /dev/null
+++ b/tests/plugins/coffeescript/views/regular.js
@@ -0,0 +1,6 @@
+if (typeof define !== 'function') {var define = (require('../../../../amdefine'))(module);}
+
+//Just a regular JavaScript module.
+define({
+    name: 'regular'
+});
diff --git a/tests/plugins/coffeescript/views/view.coffee b/tests/plugins/coffeescript/views/view.coffee
new file mode 100644
index 0000000..34b43c2
--- /dev/null
+++ b/tests/plugins/coffeescript/views/view.coffee
@@ -0,0 +1,6 @@
+if typeof define isnt 'function'
+  define = (require('../../../amdefine'))(module)
+
+define ->
+  render: () ->
+    return 'render'
diff --git a/tests/plugins/relative/multicall.js b/tests/plugins/relative/multicall.js
new file mode 100644
index 0000000..e69de29
diff --git a/tests/plugins/relative/relative-tests.js b/tests/plugins/relative/relative-tests.js
new file mode 100644
index 0000000..076311f
--- /dev/null
+++ b/tests/plugins/relative/relative-tests.js
@@ -0,0 +1,20 @@
+doh.register(
+    "pluginsRelative",
+    [
+        function pluginsRelative(t){
+            var branch = require('./sub/branch'),
+                fs = require('fs'),
+                path = require('path'),
+                baseName = path.dirname(module.filename),
+                twoText = fs.readFileSync(path.normalize(path.join(baseName, './sub/templates/two.txt')), 'utf8');
+
+            t.is('branch', branch.name);
+            t.is('leaf', branch.leaf.name);
+            t.is(fs.readFileSync(path.normalize(path.join(baseName, './sub/templates/one.txt')), 'utf8'), branch.one);
+            t.is(twoText, branch.two);
+            t.is(twoText, branch.leaf.two);
+        }
+    ]
+);
+
+doh.run();
diff --git a/tests/plugins/relative/sub/another/leaf.js b/tests/plugins/relative/sub/another/leaf.js
new file mode 100644
index 0000000..0f6d53e
--- /dev/null
+++ b/tests/plugins/relative/sub/another/leaf.js
@@ -0,0 +1,8 @@
+if (typeof define !== 'function') { var define = (require('../../../../../amdefine'))(module); }
+
+define(function (require) {
+    return {
+        name: 'leaf',
+        two: require('../../text!../templates/two.txt')
+    };
+});
diff --git a/tests/plugins/relative/sub/branch.js b/tests/plugins/relative/sub/branch.js
new file mode 100644
index 0000000..06b265d
--- /dev/null
+++ b/tests/plugins/relative/sub/branch.js
@@ -0,0 +1,14 @@
+if (typeof define !== 'function') { var define = (require('../../../../amdefine'))(module); }
+
+define(function (require) {
+    var leaf = require('./another/leaf'),
+        oneTemplate = require('../text!./templates/one.txt'),
+        twoTemplate = require('../text!./templates/two.txt');
+
+    return {
+        name: 'branch',
+        leaf: leaf,
+        one: oneTemplate,
+        two: twoTemplate
+    };
+});
diff --git a/tests/plugins/relative/sub/templates/one.txt b/tests/plugins/relative/sub/templates/one.txt
new file mode 100644
index 0000000..2c4d572
--- /dev/null
+++ b/tests/plugins/relative/sub/templates/one.txt
@@ -0,0 +1 @@
+This is one
\ No newline at end of file
diff --git a/tests/plugins/relative/sub/templates/two.txt b/tests/plugins/relative/sub/templates/two.txt
new file mode 100644
index 0000000..abef554
--- /dev/null
+++ b/tests/plugins/relative/sub/templates/two.txt
@@ -0,0 +1,3 @@
+<h1>This is two</h1>
+
+<h2>OK</h2>
diff --git a/tests/plugins/relative/text.js b/tests/plugins/relative/text.js
new file mode 100644
index 0000000..5198ef5
--- /dev/null
+++ b/tests/plugins/relative/text.js
@@ -0,0 +1,285 @@
+if (typeof define !== 'function') { var define = (require('../../../amdefine'))(module); }
+
+/**
+ * @license RequireJS text 1.0.2 Copyright (c) 2010-2011, The Dojo Foundation All Rights Reserved.
+ * Available via the MIT or new BSD license.
+ * see: http://github.com/jrburke/requirejs for details
+ */
+/*jslint regexp: false, nomen: false, plusplus: false, strict: false */
+/*global require: false, XMLHttpRequest: false, ActiveXObject: false,
+  define: false, window: false, process: false, Packages: false,
+  java: false, location: false */
+
+(function () {
+    var progIds = ['Msxml2.XMLHTTP', 'Microsoft.XMLHTTP', 'Msxml2.XMLHTTP.4.0'],
+        xmlRegExp = /^\s*<\?xml(\s)+version=[\'\"](\d)*.(\d)*[\'\"](\s)*\?>/im,
+        bodyRegExp = /<body[^>]*>\s*([\s\S]+)\s*<\/body>/im,
+        hasLocation = typeof location !== 'undefined' && location.href,
+        defaultProtocol = hasLocation && location.protocol && location.protocol.replace(/\:/, ''),
+        defaultHostName = hasLocation && location.hostname,
+        defaultPort = hasLocation && (location.port || undefined),
+        buildMap = [];
+
+    define(function () {
+        var text, get, fs;
+
+        if (typeof window !== "undefined" && window.navigator && window.document) {
+            get = function (url, callback) {
+                var xhr = text.createXhr();
+                xhr.open('GET', url, true);
+                xhr.onreadystatechange = function (evt) {
+                    //Do not explicitly handle errors, those should be
+                    //visible via console output in the browser.
+                    if (xhr.readyState === 4) {
+                        callback(xhr.responseText);
+                    }
+                };
+                xhr.send(null);
+            };
+        } else if (typeof process !== "undefined" &&
+                 process.versions &&
+                 !!process.versions.node) {
+            //Using special require.nodeRequire, something added by r.js.
+            fs = (require.nodeRequire || require)('fs');
+
+            get = function (url, callback) {
+                callback(fs.readFileSync(url, 'utf8'));
+            };
+        } else if (typeof Packages !== 'undefined') {
+            //Why Java, why is this so awkward?
+            get = function (url, callback) {
+                var encoding = "utf-8",
+                    file = new java.io.File(url),
+                    lineSeparator = java.lang.System.getProperty("line.separator"),
+                    input = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream(file), encoding)),
+                    stringBuffer, line,
+                    content = '';
+                try {
+                    stringBuffer = new java.lang.StringBuffer();
+                    line = input.readLine();
+
+                    // Byte Order Mark (BOM) - The Unicode Standard, version 3.0, page 324
+                    // http://www.unicode.org/faq/utf_bom.html
+
+                    // Note that when we use utf-8, the BOM should appear as "EF BB BF", but it doesn't due to this bug in the JDK:
+                    // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4508058
+                    if (line && line.length() && line.charAt(0) === 0xfeff) {
+                        // Eat the BOM, since we've already found the encoding on this file,
+                        // and we plan to concatenating this buffer with others; the BOM should
+                        // only appear at the top of a file.
+                        line = line.substring(1);
+                    }
+
+                    stringBuffer.append(line);
+
+                    while ((line = input.readLine()) !== null) {
+                        stringBuffer.append(lineSeparator);
+                        stringBuffer.append(line);
+                    }
+                    //Make sure we return a JavaScript string and not a Java string.
+                    content = String(stringBuffer.toString()); //String
+                } finally {
+                    input.close();
+                }
+                callback(content);
+            };
+        }
+
+        text = {
+            version: '1.0.2',
+
+            strip: function (content) {
+                //Strips <?xml ...?> declarations so that external SVG and XML
+                //documents can be added to a document without worry. Also, if the string
+                //is an HTML document, only the part inside the body tag is returned.
+                if (content) {
+                    content = content.replace(xmlRegExp, "");
+                    var matches = content.match(bodyRegExp);
+                    if (matches) {
+                        content = matches[1];
+                    }
+                } else {
+                    content = "";
+                }
+                return content;
+            },
+
+            jsEscape: function (content) {
+                return content.replace(/(['\\])/g, '\\$1')
+                    .replace(/[\f]/g, "\\f")
+                    .replace(/[\b]/g, "\\b")
+                    .replace(/[\n]/g, "\\n")
+                    .replace(/[\t]/g, "\\t")
+                    .replace(/[\r]/g, "\\r");
+            },
+
+            createXhr: function () {
+                //Would love to dump the ActiveX crap in here. Need IE 6 to die first.
+                var xhr, i, progId;
+                if (typeof XMLHttpRequest !== "undefined") {
+                    return new XMLHttpRequest();
+                } else {
+                    for (i = 0; i < 3; i++) {
+                        progId = progIds[i];
+                        try {
+                            xhr = new ActiveXObject(progId);
+                        } catch (e) {}
+
+                        if (xhr) {
+                            progIds = [progId];  // so faster next time
+                            break;
+                        }
+                    }
+                }
+
+                if (!xhr) {
+                    throw new Error("createXhr(): XMLHttpRequest not available");
+                }
+
+                return xhr;
+            },
+
+            get: get,
+
+            /**
+             * Parses a resource name into its component parts. Resource names
+             * look like: module/name.ext!strip, where the !strip part is
+             * optional.
+             * @param {String} name the resource name
+             * @returns {Object} with properties "moduleName", "ext" and "strip"
+             * where strip is a boolean.
+             */
+            parseName: function (name) {
+                var strip = false, index = name.indexOf("."),
+                    modName = name.substring(0, index),
+                    ext = name.substring(index + 1, name.length);
+
+                index = ext.indexOf("!");
+                if (index !== -1) {
+                    //Pull off the strip arg.
+                    strip = ext.substring(index + 1, ext.length);
+                    strip = strip === "strip";
+                    ext = ext.substring(0, index);
+                }
+
+                return {
+                    moduleName: modName,
+                    ext: ext,
+                    strip: strip
+                };
+            },
+
+            xdRegExp: /^((\w+)\:)?\/\/([^\/\\]+)/,
+
+            /**
+             * Is an URL on another domain. Only works for browser use, returns
+             * false in non-browser environments. Only used to know if an
+             * optimized .js version of a text resource should be loaded
+             * instead.
+             * @param {String} url
+             * @returns Boolean
+             */
+            useXhr: function (url, protocol, hostname, port) {
+                var match = text.xdRegExp.exec(url),
+                    uProtocol, uHostName, uPort;
+                if (!match) {
+                    return true;
+                }
+                uProtocol = match[2];
+                uHostName = match[3];
+
+                uHostName = uHostName.split(':');
+                uPort = uHostName[1];
+                uHostName = uHostName[0];
+
+                return (!uProtocol || uProtocol === protocol) &&
+                       (!uHostName || uHostName === hostname) &&
+                       ((!uPort && !uHostName) || uPort === port);
+            },
+
+            finishLoad: function (name, strip, content, onLoad, config) {
+                content = strip ? text.strip(content) : content;
+                if (config.isBuild) {
+                    buildMap[name] = content;
+                }
+                onLoad(content);
+            },
+
+            load: function (name, req, onLoad, config) {
+                //Name has format: some.module.filext!strip
+                //The strip part is optional.
+                //if strip is present, then that means only get the string contents
+                //inside a body tag in an HTML string. For XML/SVG content it means
+                //removing the <?xml ...?> declarations so the content can be inserted
+                //into the current doc without problems.
+
+                // Do not bother with the work if a build and text will
+                // not be inlined.
+                if (config.isBuild && !config.inlineText) {
+                    onLoad();
+                    return;
+                }
+
+                var parsed = text.parseName(name),
+                    nonStripName = parsed.moduleName + '.' + parsed.ext,
+                    url = req.toUrl(nonStripName),
+                    useXhr = (config && config.text && config.text.useXhr) ||
+                             text.useXhr;
+
+                //Load the text. Use XHR if possible and in a browser.
+                if (!hasLocation || useXhr(url, defaultProtocol, defaultHostName, defaultPort)) {
+                    text.get(url, function (content) {
+                        text.finishLoad(name, parsed.strip, content, onLoad, config);
+                    });
+                } else {
+                    //Need to fetch the resource across domains. Assume
+                    //the resource has been optimized into a JS module. Fetch
+                    //by the module name + extension, but do not include the
+                    //!strip part to avoid file system issues.
+                    req([nonStripName], function (content) {
+                        text.finishLoad(parsed.moduleName + '.' + parsed.ext,
+                                        parsed.strip, content, onLoad, config);
+                    });
+                }
+            },
+
+            write: function (pluginName, moduleName, write, config) {
+                if (moduleName in buildMap) {
+                    var content = text.jsEscape(buildMap[moduleName]);
+                    write.asModule(pluginName + "!" + moduleName,
+                                   "define(function () { return '" +
+                                       content +
+                                   "';});\n");
+                }
+            },
+
+            writeFile: function (pluginName, moduleName, req, write, config) {
+                var parsed = text.parseName(moduleName),
+                    nonStripName = parsed.moduleName + '.' + parsed.ext,
+                    //Use a '.js' file name so that it indicates it is a
+                    //script that can be loaded across domains.
+                    fileName = req.toUrl(parsed.moduleName + '.' +
+                                         parsed.ext) + '.js';
+
+                //Leverage own load() method to load plugin value, but only
+                //write out values that do not have the strip argument,
+                //to avoid any potential issues with ! in file names.
+                text.load(nonStripName, req, function (value) {
+                    //Use own write() method to construct full module value.
+                    //But need to create shell that translates writeFile's
+                    //write() to the right interface.
+                    var textWrite = function (contents) {
+                        return write(fileName, contents);
+                    };
+                    textWrite.asModule = function (moduleName, contents) {
+                        return write.asModule(moduleName, fileName, contents);
+                    };
+
+                    text.write(pluginName, nonStripName, textWrite, config);
+                }, config);
+            }
+        };
+
+        return text;
+    });
+}());
diff --git a/tests/require/addTwo.js b/tests/require/addTwo.js
new file mode 100644
index 0000000..e5bc310
--- /dev/null
+++ b/tests/require/addTwo.js
@@ -0,0 +1,3 @@
+module.exports = function () {
+    return 2;
+};
diff --git a/tests/require/require-tests.js b/tests/require/require-tests.js
new file mode 100644
index 0000000..bd62bb0
--- /dev/null
+++ b/tests/require/require-tests.js
@@ -0,0 +1,14 @@
+doh.register(
+    "requireTests",
+    [
+        function requireTests(t){
+            var dynamic = require('./sub/dynamic');
+
+            t.is(0, dynamic.count);
+            dynamic.action();
+            t.is(1, dynamic.count);
+        }
+    ]
+);
+
+doh.run();
diff --git a/tests/require/sub/dynamic.js b/tests/require/sub/dynamic.js
new file mode 100644
index 0000000..035ba64
--- /dev/null
+++ b/tests/require/sub/dynamic.js
@@ -0,0 +1,20 @@
+if (typeof define !== 'function') { var define = (require('../../../amdefine'))(module, require); }
+
+//Just testing a plain exports case.
+define(function (require) {
+    var dynamic = {
+        count: 0,
+        action: function () {
+            dynamic.count += 1;
+
+            //Test that dynamic require is not synchronous. If it was, this
+            //would add two to the counter, instead of just one.
+            require(['../addTwo'], function (addTwo) {
+                console.log('dynamic require should fire after TEST SUMMARY is shown.');
+                dynamic.count += addTwo();
+            });
+        }
+    };
+
+    return dynamic;
+});

-- 
Alioth's /usr/local/bin/git-commit-notice on /srv/git.debian.org/git/pkg-javascript/node-amdefine.git



More information about the Pkg-javascript-commits mailing list