From d3da6a6f3cb267b9842348e8920471f2d4e930a0 Mon Sep 17 00:00:00 2001 From: Luca Antiga Date: Tue, 17 Jun 2014 22:36:00 +0200 Subject: [PATCH 01/51] Replaced bind(this)() with call(this), resulting in a 2x speedup for grunt test. --- macros/index.js | 32 ++++++++++++++++---------------- package.json | 2 +- src/ki.sjs | 32 ++++++++++++++++---------------- 3 files changed, 33 insertions(+), 33 deletions(-) diff --git a/macros/index.js b/macros/index.js index 873bd36..8c396d9 100644 --- a/macros/index.js +++ b/macros/index.js @@ -114,7 +114,7 @@ macro _letv { rule { ([$k $v $rest ...] $sexprs ...) } => { return (function ($k) { _letv ([$rest ...] $sexprs ...) - }.bind(this)(_sexpr $v)); + }.call(this,_sexpr $v)); } rule { ([] $sexprs ...) } => { _return_sexprs ($sexprs ...) @@ -226,7 +226,7 @@ macro _sexpr { var f = fnmap[arguments.length] || fnmap[null]; return f.apply(this,arguments); } - }.bind(this)()) + }.call(this)) } rule { (if $cond $sthen $selse) } => { @@ -235,7 +235,7 @@ macro _sexpr { return _sexpr $sthen; } return _sexpr $selse; - }.bind(this)()) + }.call(this)) } rule { (if_not $cond $sthen $selse) } => { @@ -248,7 +248,7 @@ macro _sexpr { return _sexpr $sthen; } return; - }.bind(this)()) + }.call(this)) } rule { (when_not $cond $sthen) } => { @@ -261,7 +261,7 @@ macro _sexpr { return _sexpr $body1; } return _sexpr (cond $rest ...); - }.bind(this)()) + }.call(this)) } rule { (cond) } => { undefined @@ -284,7 +284,7 @@ macro _sexpr { rule { (letv [$bindings ...] $sexprs ...) } => { (function () { _letv ([$bindings ...] $sexprs ...) - }.bind(this)()) + }.call(this)) } rule { (letc [$bindings ...] $sexprs ...) } => { @@ -294,7 +294,7 @@ macro _sexpr { rule { (do $sexprs ...) } => { (function () { _return_sexprs ($sexprs ...) - }.bind(this)()) + }.call(this)) } rule { (while $cond $sexpr) } => { @@ -302,7 +302,7 @@ macro _sexpr { while (_sexpr (truthy $cond)) { _sexpr $sexpr; } - }.bind(this)()) + }.call(this)) } rule { (loop [$bindings ...] $sexprs ...) } => { @@ -315,7 +315,7 @@ macro _sexpr { } while ((res || 0)._ki_recur); return res; - }.bind(this)()) + }.call(this)) } rule { (recur $args ...) } => { @@ -407,7 +407,7 @@ macro _sexpr { (function () { _doto ($obj $rest ...) return $obj; - }.bind(this)()) + }.call(this)) } rule { (atom $val) } => { @@ -438,7 +438,7 @@ macro _sexpr { ref._ki_wcb(val, prev_val); } return val; - }.bind(this)()) + }.call(this)) } rule { (swap $ref $fn $args ...) } => { @@ -446,7 +446,7 @@ macro _sexpr { var ref = _sexpr $ref; var val = ref._ki_val; return _sexpr (reset ref ($fn val $args ...)) - }.bind(this)()) + }.call(this)) } rule { (deref $ref) } => { @@ -456,7 +456,7 @@ macro _sexpr { ref._ki_rcb(ref._ki_val); } return ref._ki_val; - }.bind(this)()) + }.call(this)) } rule { (try $body (catch $e $catch_expr)) } => { @@ -467,7 +467,7 @@ macro _sexpr { catch ($e) { _sexpr $catch_expr } - }.bind(this)()) + }.call(this)) } rule { (try $body (catch $e $catch_expr) (finally $finally_expr)) } => { @@ -483,13 +483,13 @@ macro _sexpr { _sexpr $finally_expr; } return ret; - }.bind(this)()) + }.call(this)) } rule { (throw $x) } => { (function () { throw(_sexpr $x); - }.bind(this)()) + }.call(this)) } rule { ($fn $args ...) } => { diff --git a/package.json b/package.json index 656bc09..b99b984 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "ki", - "version": "0.1.21", + "version": "0.1.22", "description": "lisp + mori, sweet.js", "repository": { "type": "git", diff --git a/src/ki.sjs b/src/ki.sjs index 873bd36..8c396d9 100644 --- a/src/ki.sjs +++ b/src/ki.sjs @@ -114,7 +114,7 @@ macro _letv { rule { ([$k $v $rest ...] $sexprs ...) } => { return (function ($k) { _letv ([$rest ...] $sexprs ...) - }.bind(this)(_sexpr $v)); + }.call(this,_sexpr $v)); } rule { ([] $sexprs ...) } => { _return_sexprs ($sexprs ...) @@ -226,7 +226,7 @@ macro _sexpr { var f = fnmap[arguments.length] || fnmap[null]; return f.apply(this,arguments); } - }.bind(this)()) + }.call(this)) } rule { (if $cond $sthen $selse) } => { @@ -235,7 +235,7 @@ macro _sexpr { return _sexpr $sthen; } return _sexpr $selse; - }.bind(this)()) + }.call(this)) } rule { (if_not $cond $sthen $selse) } => { @@ -248,7 +248,7 @@ macro _sexpr { return _sexpr $sthen; } return; - }.bind(this)()) + }.call(this)) } rule { (when_not $cond $sthen) } => { @@ -261,7 +261,7 @@ macro _sexpr { return _sexpr $body1; } return _sexpr (cond $rest ...); - }.bind(this)()) + }.call(this)) } rule { (cond) } => { undefined @@ -284,7 +284,7 @@ macro _sexpr { rule { (letv [$bindings ...] $sexprs ...) } => { (function () { _letv ([$bindings ...] $sexprs ...) - }.bind(this)()) + }.call(this)) } rule { (letc [$bindings ...] $sexprs ...) } => { @@ -294,7 +294,7 @@ macro _sexpr { rule { (do $sexprs ...) } => { (function () { _return_sexprs ($sexprs ...) - }.bind(this)()) + }.call(this)) } rule { (while $cond $sexpr) } => { @@ -302,7 +302,7 @@ macro _sexpr { while (_sexpr (truthy $cond)) { _sexpr $sexpr; } - }.bind(this)()) + }.call(this)) } rule { (loop [$bindings ...] $sexprs ...) } => { @@ -315,7 +315,7 @@ macro _sexpr { } while ((res || 0)._ki_recur); return res; - }.bind(this)()) + }.call(this)) } rule { (recur $args ...) } => { @@ -407,7 +407,7 @@ macro _sexpr { (function () { _doto ($obj $rest ...) return $obj; - }.bind(this)()) + }.call(this)) } rule { (atom $val) } => { @@ -438,7 +438,7 @@ macro _sexpr { ref._ki_wcb(val, prev_val); } return val; - }.bind(this)()) + }.call(this)) } rule { (swap $ref $fn $args ...) } => { @@ -446,7 +446,7 @@ macro _sexpr { var ref = _sexpr $ref; var val = ref._ki_val; return _sexpr (reset ref ($fn val $args ...)) - }.bind(this)()) + }.call(this)) } rule { (deref $ref) } => { @@ -456,7 +456,7 @@ macro _sexpr { ref._ki_rcb(ref._ki_val); } return ref._ki_val; - }.bind(this)()) + }.call(this)) } rule { (try $body (catch $e $catch_expr)) } => { @@ -467,7 +467,7 @@ macro _sexpr { catch ($e) { _sexpr $catch_expr } - }.bind(this)()) + }.call(this)) } rule { (try $body (catch $e $catch_expr) (finally $finally_expr)) } => { @@ -483,13 +483,13 @@ macro _sexpr { _sexpr $finally_expr; } return ret; - }.bind(this)()) + }.call(this)) } rule { (throw $x) } => { (function () { throw(_sexpr $x); - }.bind(this)()) + }.call(this)) } rule { ($fn $args ...) } => { From 624e6450f88557bdf6f7943b06024bf53e6c50af Mon Sep 17 00:00:00 2001 From: Luca Antiga Date: Sat, 21 Jun 2014 17:32:59 +0200 Subject: [PATCH 02/51] Changed letv to let to eliminate confusion wrt Clojure, thanks to sweet.js $[]. --- README.md | 2 +- TODO.md | 114 ------------------------------------------------ macros/index.js | 14 +++--- package.json | 2 +- src/ki.sjs | 14 +++--- test/core.js | 26 +++++------ 6 files changed, 29 insertions(+), 143 deletions(-) delete mode 100644 TODO.md diff --git a/README.md b/README.md index afb32e3..3cae458 100644 --- a/README.md +++ b/README.md @@ -22,7 +22,7 @@ The following list of functions / special forms ``` [] {} [$ ] {$ } add and apply atom bind catch chain cond def defmethod defmulti defn deref div do doto eq falsey finally fn fnth geq gt if if_not js leq letc -letv lt loop mod mul neq nil not ns or prn recur reset str sub swap threadf +let lt loop mod mul neq nil not ns or prn recur reset str sub swap threadf threadl truthy try use when when_not while ``` diff --git a/TODO.md b/TODO.md deleted file mode 100644 index 4050636..0000000 --- a/TODO.md +++ /dev/null @@ -1,114 +0,0 @@ - -# ki roadmap - -## 0.2.0 Make it a viable language - -* **DONE** enclose every ki call in (function() {})(), if this doesn't break hygiene tricks -* **DONE** allow property access without (js ), e.g. (bar.dostuff 1 this.props) instead of - ((js bar.dostuff) 1 (js this.props)) -* **DONE** implement ki require to make it practical to use node modules -* **DONE** if when -* **DONE** cond -* **DONE** and or -* **DONE** not -* **DONE** eq neq -* **DONE** letv -* **DONE** do -* **DONE** def defn -* **DONE** nil -* **DONE** define truthiness (in line with ClojureScript and Mori) -* **DONE** ns: every ki () form should introduce a namespace, either anonymous - (no ns form) or named, ki (ns foobar (def ...)) - Every def (and defn) should define a var as well as place the value in - the _ki object, so that it can be used/interned in other ki blocks with different - namespaces (or other ki blocks with the same namespace). -* **DONE** fully qualified identifiers foo/bar -* **DONE** use: intern all functions of a module (TODO: warn on aliasing) -* **DONE** support js object creation with js new, or just decide to leave it as - (js new Date) I like this option better (we should document it and that's it) -* **DONE** data literals -* **DONE** loop, recur, while -* **DONE** multiple arities -* **DONE** threading macros -* **DONE** chaining, doto -* **DONE** add sub mul div mod -* **DONE** lt gt leq geq -* **DONE** letc (backcalls style continuations) -* **DONE** apply -* **DONE** bind -* **DONE** keywords **NOTE** keywords do not evaluate to themselves and do not extract values from collections. We could add a reader macro for this (**TODO**). -* **DONE** multimethods -* **DONE** atoms -* **DONE** exceptions -* **DONE** allow generated scripts to run in browser (avoid require) -* **DONE** fnth (fn bound to this) -* **DONE** be consistent in binding to this - -* **DONE** testing - -* example with node -* **DONE** example with React - -## 0.3.0 Add the nice to have - -* destructuring -* multiline strings -* consider integrating cspjs -* CPS modeled after tame.js - In tame we would have something like - (await (setTimeout (defer) 100)) - (prn "Hello!") - which would require exploring the AST. It could become something like - (with_defers [a] - (await (setTimeout a 100)) - (prn "Hello!")) - or even more explicitly - (with_defers [a] - (await a (setTimeout a 100)) - (prn "Hello!")) - which could also be used as - (with_defers [a] - (setTimeout a 100) - (await a) - (prn "Hello!")) - Or just limit defers to last argument as in letc. The advantage over letc is - easier parallelism of e.g. multiple requests to server. -* named parameters and defaults -* optional arguments to functions (catpured in a vector) -* regular expressions -* implement a REPL -* additional functions/forms - * condp case - * for (comprehension) -* "application/ki" script type and in-browser expansion (browserify?) -* create something like http://kanaka.github.io/clojurescript/web/synonym.html - -## 0.4.0 Make it a real lisp - -* implement macros in pure ki - Workflow: ki script reads the input file, identifies forms with ki macro foo, - or (defmacro foo ...) inside ki forms (we'll have to choose), builds a string - of code to execute in ki (i.e. complied through sweet.js as a library and - executed in node), that defines macros as functions and calls a macroexpand - function that takes in input the input file and returns a string in which all - invocations of (foo ...) are replaced with their expanded version. - The result is then compiled in sweet.js and written in output. -* have a ki script replace the sjs script for handling the double pass - Also informative: https://github.com/swannodette/hello-cljsc/blob/master/src/hello-cljsc/core.clj -* browserify the ki script -* make LightTable plugin - -## 0.5.0 Add support for libraries - -### Browser - -* React.js -* jQuery -* D3 -* KnockoutJS - -### Node - -* Plain node -* Express - diff --git a/macros/index.js b/macros/index.js index 8c396d9..c0c0129 100644 --- a/macros/index.js +++ b/macros/index.js @@ -110,10 +110,10 @@ macro _fnmap { } } -macro _letv { +macro _let { rule { ([$k $v $rest ...] $sexprs ...) } => { return (function ($k) { - _letv ([$rest ...] $sexprs ...) + _let ([$rest ...] $sexprs ...) }.call(this,_sexpr $v)); } rule { ([] $sexprs ...) } => { @@ -138,10 +138,10 @@ macro _letc { } } -macro _loop_letv { +macro _loop_let { rule { ([$k $v $rest ...] $i $vals $sexprs ...) } => { return (function ($k) { - _loop_letv ([$rest ...] ($i+1) $vals $sexprs ...) + _loop_let ([$rest ...] ($i+1) $vals $sexprs ...) }($vals === undefined ? _sexpr $v : $vals[$i])); } rule { ([] $i $vals $sexprs ...) } => { @@ -281,9 +281,9 @@ macro _sexpr { _sexpr (truthy $sexpr) || _sexpr (or $sexprs ...) } - rule { (letv [$bindings ...] $sexprs ...) } => { + rule { ($[let] [$bindings ...] $sexprs ...) } => { (function () { - _letv ([$bindings ...] $sexprs ...) + _let ([$bindings ...] $sexprs ...) }.call(this)) } @@ -310,7 +310,7 @@ macro _sexpr { var res = {}; do { res = (function () { - _loop_letv ([$bindings ...] 0 (res._ki_vals) $sexprs ...); + _loop_let ([$bindings ...] 0 (res._ki_vals) $sexprs ...); }()); } while ((res || 0)._ki_recur); diff --git a/package.json b/package.json index b99b984..a1a359f 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "ki", - "version": "0.1.22", + "version": "0.1.23", "description": "lisp + mori, sweet.js", "repository": { "type": "git", diff --git a/src/ki.sjs b/src/ki.sjs index 8c396d9..c0c0129 100644 --- a/src/ki.sjs +++ b/src/ki.sjs @@ -110,10 +110,10 @@ macro _fnmap { } } -macro _letv { +macro _let { rule { ([$k $v $rest ...] $sexprs ...) } => { return (function ($k) { - _letv ([$rest ...] $sexprs ...) + _let ([$rest ...] $sexprs ...) }.call(this,_sexpr $v)); } rule { ([] $sexprs ...) } => { @@ -138,10 +138,10 @@ macro _letc { } } -macro _loop_letv { +macro _loop_let { rule { ([$k $v $rest ...] $i $vals $sexprs ...) } => { return (function ($k) { - _loop_letv ([$rest ...] ($i+1) $vals $sexprs ...) + _loop_let ([$rest ...] ($i+1) $vals $sexprs ...) }($vals === undefined ? _sexpr $v : $vals[$i])); } rule { ([] $i $vals $sexprs ...) } => { @@ -281,9 +281,9 @@ macro _sexpr { _sexpr (truthy $sexpr) || _sexpr (or $sexprs ...) } - rule { (letv [$bindings ...] $sexprs ...) } => { + rule { ($[let] [$bindings ...] $sexprs ...) } => { (function () { - _letv ([$bindings ...] $sexprs ...) + _let ([$bindings ...] $sexprs ...) }.call(this)) } @@ -310,7 +310,7 @@ macro _sexpr { var res = {}; do { res = (function () { - _loop_letv ([$bindings ...] 0 (res._ki_vals) $sexprs ...); + _loop_let ([$bindings ...] 0 (res._ki_vals) $sexprs ...); }()); } while ((res || 0)._ki_recur); diff --git a/test/core.js b/test/core.js index b27cac1..e1a2b90 100644 --- a/test/core.js +++ b/test/core.js @@ -100,28 +100,28 @@ describe("interoperability", function() { describe("local bindings and lexical scope", function() { - it("should allow to define local bindings in a letv form and ensure proper lexical scope", function() { + it("should allow to define local bindings in a let form and ensure proper lexical scope", function() { ki require core expect( ki (clj_to_js - (letv [a 1 + (let [a 1 b 2] (vector a b))) ).to.eql([1,2]); expect( ki (clj_to_js - (letv [a 0] - (letv [a (inc a) + (let [a 0] + (let [a (inc a) b (inc a)] (vector a b)))) ).to.eql([1,2]); var c = {d: 1}; var mori = _ki.modules.mori; expect( - ki (letv [a c.d + ki (let [a c.d b (inc a) e :e] - (letv [a (inc a) + (let [a (inc a) b (inc b)] a) (vector a b e)) @@ -574,14 +574,14 @@ describe("atoms", function() { ki require core ki (do - (letv [r (atom 1 (fn [n o] (js expect(n).to.eql(2); expect(o).to.eql(1))) - (fn [x] (js expect(x).to.eql(2))))] + (let [r (atom 1 (fn [n o] (js expect(n).to.eql(2); expect(o).to.eql(1))) + (fn [x] (js expect(x).to.eql(2))))] (reset r 2) (deref r))); ki (do - (letv [r (atom 1 (fn [n o] (js expect(n).to.eql(2); expect(o).to.eql(1))) - (fn [x] (js expect(x).to.eql(2))))] + (let [r (atom 1 (fn [n o] (js expect(n).to.eql(2); expect(o).to.eql(1))) + (fn [x] (js expect(x).to.eql(2))))] (swap r inc) (js expect(ki (deref r)).to.eql(2)))); @@ -619,7 +619,7 @@ describe("this and fnth", function() { ki require core - ki (defn somefn [] (letv [a 1] this.someprop)); + ki (defn somefn [] (let [a 1] this.someprop)); var bar = {someprop: 1}; var baz = {}; @@ -636,8 +636,8 @@ describe("this and fnth", function() { var fn1, fn2; ki (do (js this.jee = 1) - (letv [a (fn [] this.jee) - b (fnth [] this.jee)] + (let [a (fn [] this.jee) + b (fnth [] this.jee)] (js fn1 = a) (js fn2 = b))); From 004e2599ec691aa8914dfda26902b5a1496645b4 Mon Sep 17 00:00:00 2001 From: Luca Antiga Date: Sat, 21 Jun 2014 23:27:17 +0200 Subject: [PATCH 03/51] Changed error message. --- src/ki.sjs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/ki.sjs b/src/ki.sjs index c0c0129..5d038e8 100644 --- a/src/ki.sjs +++ b/src/ki.sjs @@ -53,10 +53,10 @@ macro _args { macro _x { case { $ctx null } => { - throwSyntaxError('ki',' is not a valid identifier, use nil',#{$ctx}) + throwSyntaxError('ki',' is not a valid literal, use nil',#{$ctx}) } case { $ctx undefined } => { - throwSyntaxError('ki',' is not a valid identifier, use nil',#{$ctx}) + throwSyntaxError('ki',' is not a valid literal, use nil',#{$ctx}) } case { _ nil } => { return #{null} From f289a7dfe710a68c11c0f90e80e162fed3247e08 Mon Sep 17 00:00:00 2001 From: Luca Antiga Date: Sun, 22 Jun 2014 00:52:56 +0200 Subject: [PATCH 04/51] Reorganizing ki.js --- bin/ki | 2 +- lib/ki.js | 248 +++++++++++++++++++----------------------------------- 2 files changed, 86 insertions(+), 164 deletions(-) diff --git a/bin/ki b/bin/ki index cf3e0d2..ccaf800 100755 --- a/bin/ki +++ b/bin/ki @@ -4,5 +4,5 @@ var path = require('path'); var fs = require('fs'); var lib = path.join(path.dirname(fs.realpathSync(__filename)),'../lib'); -require(lib + '/ki').run() +require(lib + '/kic').run() diff --git a/lib/ki.js b/lib/ki.js index 63f3e35..7ba3b83 100644 --- a/lib/ki.js +++ b/lib/ki.js @@ -1,182 +1,104 @@ -var fs = require('fs'); -var path = require('path'); -var sweet = require('sweet.js'); -var uglify = require('uglify-js'); - -// TODO: add option to build a version of ki macros that includes modules - -var argv = require("optimist") - .usage("Usage: ki [options] path/to/file.js") - .alias('o', 'output') - .describe('o', 'output file path') - .alias('i', 'include') - .describe('i', 'include code from file (relative path or npm package)') - .alias('w', 'watch') - .describe('w', 'watch a file') - .boolean('watch') - .alias('s', 'sourcemap') - .describe('s', 'generate a sourcemap') - .boolean('sourcemap') - .alias('u', 'minify') - .describe('u', 'minify output code using UglifyJS2') - .boolean('minify') - .alias('c', 'compress') - .describe('c', 'compress and optimize during minify (default true if minify)') - .boolean('compress') - .argv; - -exports.run = function() { - var infile = argv._[0]; - var outfile = argv.output; - var watch = argv.watch; - var sourcemap = argv.sourcemap; - var minify = argv.minify; - var compress = argv.compress; - compress = compress ? {} : false; - - var file; - if (infile) { - file = fs.readFileSync(infile, 'utf8'); - } - else if (argv._.length === 0) { - console.log(require("optimist").help()); - return; +(function (root, factory) { + if (typeof exports === 'object') { + factory(exports); + } + else if (typeof define === 'function' && define.amd) { + define(['exports' + ], factory); } - var ki_core = fs.readFileSync(path.join(path.dirname(fs.realpathSync(__filename)),'../macros/index.js'), 'utf8'); +}(this, function(exports) { + + var getNSExprs = function(s,n) { + var nesting = 0; + var sexpr = ""; + var res = {matches: [], end: -1}; + for (var i = 0; i < s.length; ++i) + { + c = s[i]; + switch (c) { + case '(': + nesting++; + break; + case ')': + nesting--; + if (nesting < 0) { + return null; + } + if (nesting == 0) { + res.matches.push(sexpr + c); + sexpr = ""; + } + if (res.matches.length == n) { + res.end = i+1; + return res; + } + break; + } + if (nesting > 0) { + sexpr += c; + } + } + return null; + } - var includes = typeof argv.include === 'string' ? [argv.include] : argv.include; - var includeFiles = (includes || []).map(function(path) { - return fs.readFileSync(path, 'utf8'); - }); - - var rules = includeFiles.map(function(includeFile) { - return parseMacros(includeFile); - }); - rules.push(parseMacros(file)); - - var module = ki_core.replace('/*__macros__*/',rules.join('\n')); + var parseMacros = function(code) { + var re = /ki *macro/ + + var current = code; + var start = current.search(re); + var ret; + var macros = []; + while (start != -1) { + current = current.substr(start); + ret = getNSExprs(current,2); + macros.push(ret.matches); + current = current.substr(ret.end); + start = current.search(re); + } + + var rules = macros.map(function(macro) { + return 'rule { ' + macro[0] + ' } => { _sexpr ' + macro[1] + ' }' + }); + + return rules.join('\n'); + } - var options = { - filename: infile, - modules: [sweet.loadModule(module)] - }; + var joinModule = function(src, ki_core, additionalRules) { + rules = additionalRules || []; + rules.push(parseMacros(src)); + return ki_core.replace('/*__macros__*/',rules.join('\n')); + } - var compile = function(file) { - var file = includeFiles.join('\n') + file; - if (sourcemap && outfile) { - options.sourceMap = true; - var result = sweet.compile(file, options); - var mapfile = path.basename(outfile) + '.map'; - var code = result.code + '\n//# sourceMappingURL=' + mapfile; + var compile = function(src, options) { + var result = sweet.compile(src, options); + if (options.sourceMap) { + var code = result.code + '\n//# sourceMappingURL=' + options.mapfile; var sourceMap = result.sourceMap; - var mapfile = outfile + '.map'; - var tmpfile = outfile + '.tmp'; - if (minify) { + var tmpfile = options.mapfile + ".tmp"; + if (options.minify && fs) { fs.writeFileSync(tmpfile, sourceMap, 'utf8'); result = uglify.minify(code, { fromString: true, inSourceMap: tmpfile, - outSourceMap: mapfile, - compress: compress + outSourceMap: options.mapfile, + compress: options.compress }); - code = result.code; - sourceMap = result.map; fs.unlinkSync(tmpfile); + return { code: result.code, sourceMap: result.map }; } - fs.writeFileSync(outfile, code, 'utf8'); - fs.writeFileSync(mapfile, sourceMap, 'utf8'); - } - else if (outfile) { - var code = sweet.compile(file, options).code; - if (minify) { - code = uglify.minify(code, {fromString: true, compress: compress}).code; - } - fs.writeFileSync(outfile, code, 'utf8'); + return { code: code, sourceMap: sourceMap }; } - else { - var code = sweet.compile(file, options).code; - if (minify) { - code = uglify.minify(code, {fromString: true, compress: compress}).code; - } - console.log(code); + else if (options.minify) { + var result = uglify.minify(code, {fromString: true, compress: compress}); + return { code: result.code }; } + return { code: result.code }; } - try { - compile(file); - } - catch (e) { - console.log(e); - } - - if (watch) { - fs.watchFile(infile, {interval: 1000}, function() { - file = fs.readFileSync(infile, 'utf8'); - try { - compile(file); - } - catch (e) { - console.log(e); - } - console.log('Compiled',infile); - }); - } -} - -var getNSExprs = function(s,n) { - var nesting = 0; - var sexpr = ""; - var res = {matches: [], end: -1}; - for (var i = 0; i < s.length; ++i) - { - c = s[i]; - switch (c) { - case '(': - nesting++; - break; - case ')': - nesting--; - if (nesting < 0) { - return null; - } - if (nesting == 0) { - res.matches.push(sexpr + c); - sexpr = ""; - } - if (res.matches.length == n) { - res.end = i+1; - return res; - } - break; - } - if (nesting > 0) { - sexpr += c; - } - } - return null; -} - -var parseMacros = function(code) { - var re = /ki *macro/ - - var current = code; - var start = current.search(re); - var ret; - var macros = []; - while (start != -1) { - current = current.substr(start); - ret = getNSExprs(current,2); - macros.push(ret.matches); - current = current.substr(ret.end); - start = current.search(re); - } - - var rules = macros.map(function(macro) { - return 'rule { ' + macro[0] + ' } => { _sexpr ' + macro[1] + ' }' - }); - - return rules.join('\n'); -} + exports.compile = compile; + exports.parseMacros = parseMacros; + exports.joinModule = joinModule; +})) From f2e070d184e55b6f35cfac358a48d085d8d12c0b Mon Sep 17 00:00:00 2001 From: Luca Antiga Date: Sun, 22 Jun 2014 00:53:48 +0200 Subject: [PATCH 05/51] Added kirun file --- bin/ki | 2 +- lib/kirun.js | 93 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 94 insertions(+), 1 deletion(-) create mode 100644 lib/kirun.js diff --git a/bin/ki b/bin/ki index ccaf800..4149c89 100755 --- a/bin/ki +++ b/bin/ki @@ -4,5 +4,5 @@ var path = require('path'); var fs = require('fs'); var lib = path.join(path.dirname(fs.realpathSync(__filename)),'../lib'); -require(lib + '/kic').run() +require(lib + '/kirun').run() diff --git a/lib/kirun.js b/lib/kirun.js new file mode 100644 index 0000000..d84845c --- /dev/null +++ b/lib/kirun.js @@ -0,0 +1,93 @@ + +var fs = require('fs'); +var path = require('path'); +var sweet = require('sweet.js'); +var uglify = require('uglify-js'); +var ki = require('./ki.js'); + +// TODO: add option to build a version of ki macros that includes modules + +var argv = require("optimist") + .usage("Usage: ki [options] path/to/file.js") + .alias('o', 'output') + .describe('o', 'output file path') + .alias('i', 'include') + .describe('i', 'include code from file (relative path or npm package)') + .alias('w', 'watch') + .describe('w', 'watch a file') + .boolean('watch') + .alias('s', 'sourceMap') + .describe('s', 'generate a sourceMap') + .boolean('sourceMap') + .alias('u', 'minify') + .describe('u', 'minify output code using UglifyJS2') + .boolean('minify') + .alias('c', 'compress') + .describe('c', 'compress and optimize during minify (default true if minify)') + .boolean('compress') + .argv; + +exports.run = function() { + var infile = argv._[0]; + var outfile = argv.output; + var watch = argv.watch; + var sourceMap = argv.sourceMap; + var minify = argv.minify; + var compress = argv.compress; + compress = compress ? {} : false; + + var file; + if (infile) { + file = fs.readFileSync(infile, 'utf8'); + } + else if (argv._.length === 0) { + console.log(require("optimist").help()); + return; + } + + var ki_core = fs.readFileSync(path.join(path.dirname(fs.realpathSync(__filename)),'../macros/index.js'), 'utf8'); + + var includes = typeof argv.include === 'string' ? [argv.include] : argv.include; + var includeFiles = (includes || []).map(function(path) { + return fs.readFileSync(path, 'utf8'); + }); + + var rules = includeFiles.map(function(includeFile) { + return ki.parseMacros(includeFile); + }); + + var module = ki.joinModule(file,ki_core,rules); + + var mapfile = path.basename(outfile) + '.map'; + + var options = { + filename: infile, + modules: [sweet.loadModule(module)], + sourceMap: sourceMap, + mapfile: mapfile, + minify: minify, + compress: compress, + rules: rules + }; + + try { + ki.compile(file,options); + } + catch (e) { + console.log(e); + } + + if (watch) { + fs.watchFile(infile, {interval: 1000}, function() { + file = fs.readFileSync(infile, 'utf8'); + try { + compile(file); + } + catch (e) { + console.log(e); + } + console.log('Compiled',infile); + }); + } +} + From 4ad2c2148fe11d684be8e36300b4a8ff0e1a0842 Mon Sep 17 00:00:00 2001 From: Luca Antiga Date: Thu, 26 Jun 2014 23:16:34 +0200 Subject: [PATCH 06/51] Separated ki.js library and invocation. --- lib/ki.js | 12 +++++++----- lib/kirun.js | 25 +++++++++++++++++++------ macros/index.js | 4 ++-- 3 files changed, 28 insertions(+), 13 deletions(-) diff --git a/lib/ki.js b/lib/ki.js index 7ba3b83..d328bbe 100644 --- a/lib/ki.js +++ b/lib/ki.js @@ -1,14 +1,16 @@ (function (root, factory) { if (typeof exports === 'object') { - factory(exports); + factory(exports, require('sweet.js')); } else if (typeof define === 'function' && define.amd) { - define(['exports' + define([ + 'exports', + 'sweet' ], factory); } -}(this, function(exports) { +}(this, function(exports, sweet) { var getNSExprs = function(s,n) { var nesting = 0; @@ -71,7 +73,7 @@ return ki_core.replace('/*__macros__*/',rules.join('\n')); } - var compile = function(src, options) { + var compile = function(src, options, uglify, fs) { var result = sweet.compile(src, options); if (options.sourceMap) { var code = result.code + '\n//# sourceMappingURL=' + options.mapfile; @@ -91,7 +93,7 @@ return { code: code, sourceMap: sourceMap }; } else if (options.minify) { - var result = uglify.minify(code, {fromString: true, compress: compress}); + var result = uglify.minify(result.code, {fromString: true, compress: options.compress}); return { code: result.code }; } return { code: result.code }; diff --git a/lib/kirun.js b/lib/kirun.js index d84845c..0a566ab 100644 --- a/lib/kirun.js +++ b/lib/kirun.js @@ -70,18 +70,31 @@ exports.run = function() { rules: rules }; - try { - ki.compile(file,options); - } - catch (e) { - console.log(e); + var compile = function() { + try { + var result = ki.compile(file,options,uglify,fs); + if (outfile) { + fs.writeFileSync(outfile,result.code,'utf8'); + if (sourceMap) { + fs.writeFileSync(mapfile,result.sourceMap,'utf8'); + } + } + else { + console.log(result.code); + } + } + catch (e) { + console.log(e); + } } + compile(); + if (watch) { fs.watchFile(infile, {interval: 1000}, function() { file = fs.readFileSync(infile, 'utf8'); try { - compile(file); + compile(); } catch (e) { console.log(e); diff --git a/macros/index.js b/macros/index.js index c0c0129..5d038e8 100644 --- a/macros/index.js +++ b/macros/index.js @@ -53,10 +53,10 @@ macro _args { macro _x { case { $ctx null } => { - throwSyntaxError('ki',' is not a valid identifier, use nil',#{$ctx}) + throwSyntaxError('ki',' is not a valid literal, use nil',#{$ctx}) } case { $ctx undefined } => { - throwSyntaxError('ki',' is not a valid identifier, use nil',#{$ctx}) + throwSyntaxError('ki',' is not a valid literal, use nil',#{$ctx}) } case { _ nil } => { return #{null} From 896690a5d7814aaedac5d7c9520d79e425a5a6e1 Mon Sep 17 00:00:00 2001 From: Luca Antiga Date: Fri, 27 Jun 2014 00:34:13 +0200 Subject: [PATCH 07/51] ki now works in browser with AMD. Added basic editor infrastructure. --- bin/ki | 2 +- editor/index.html | 7 + editor/scripts/editor.js | 98 + editor/scripts/escodegen.js | 3902 +++++++++++++++ editor/scripts/escope.js | 1117 +++++ editor/scripts/estraverse.js | 688 +++ editor/scripts/expander.js | 2528 ++++++++++ editor/scripts/jquery.js | 8829 ++++++++++++++++++++++++++++++++++ editor/scripts/ki.js | 107 + editor/scripts/ki.sjs | 824 ++++ editor/scripts/main.js | 19 + editor/scripts/mori.js | 331 ++ editor/scripts/parser.js | 5010 +++++++++++++++++++ editor/scripts/patterns.js | 896 ++++ editor/scripts/require.js | 36 + editor/scripts/scopedEval.js | 20 + editor/scripts/stxcase.js | 963 ++++ editor/scripts/sweet.js | 240 + editor/scripts/syntax.js | 420 ++ editor/scripts/text.js | 386 ++ editor/scripts/underscore.js | 1201 +++++ lib/ki.js | 5 +- lib/{kirun.js => ki_run.js} | 6 +- package.json | 2 +- 24 files changed, 27629 insertions(+), 8 deletions(-) create mode 100644 editor/index.html create mode 100644 editor/scripts/editor.js create mode 100644 editor/scripts/escodegen.js create mode 100644 editor/scripts/escope.js create mode 100644 editor/scripts/estraverse.js create mode 100644 editor/scripts/expander.js create mode 100644 editor/scripts/jquery.js create mode 100644 editor/scripts/ki.js create mode 100644 editor/scripts/ki.sjs create mode 100644 editor/scripts/main.js create mode 100644 editor/scripts/mori.js create mode 100644 editor/scripts/parser.js create mode 100644 editor/scripts/patterns.js create mode 100644 editor/scripts/require.js create mode 100644 editor/scripts/scopedEval.js create mode 100644 editor/scripts/stxcase.js create mode 100644 editor/scripts/sweet.js create mode 100644 editor/scripts/syntax.js create mode 100644 editor/scripts/text.js create mode 100644 editor/scripts/underscore.js rename lib/{kirun.js => ki_run.js} (94%) diff --git a/bin/ki b/bin/ki index 4149c89..19371e6 100755 --- a/bin/ki +++ b/bin/ki @@ -4,5 +4,5 @@ var path = require('path'); var fs = require('fs'); var lib = path.join(path.dirname(fs.realpathSync(__filename)),'../lib'); -require(lib + '/kirun').run() +require(lib + '/ki_run').run() diff --git a/editor/index.html b/editor/index.html new file mode 100644 index 0000000..e391c36 --- /dev/null +++ b/editor/index.html @@ -0,0 +1,7 @@ + + + + + + + diff --git a/editor/scripts/editor.js b/editor/scripts/editor.js new file mode 100644 index 0000000..1d1b48e --- /dev/null +++ b/editor/scripts/editor.js @@ -0,0 +1,98 @@ +requirejs.config({ + shim: { + 'underscore': { + exports: '_' + } + } +}); + +require(["./sweet", "./syntax"], function(sweet, syn) { + var storage_code = 'editor_code'; + var storage_mode = 'editor_mode'; + + var starting_code = $("#editor").text(); + var compileWithSourcemap = $("body").attr("data-sourcemap") === "true"; + + var editor = CodeMirror.fromTextArea($('#editor')[0], { + lineNumbers: true, + smartIndent: false, + indentWithTabs: true, + tabSize: 4, + autofocus: true, + theme: 'solarized dark' + }); + + var currentStep = 1; + + if (window.location.hash) { + editor.setValue(decodeURI(window.location.hash.slice(1))); + } else { + editor.setValue(localStorage[storage_code] ? localStorage[storage_code] : starting_code); + } + if(localStorage[storage_mode]) { + editor.setOption("keyMap", localStorage[storage_mode]); + } + + var output = CodeMirror.fromTextArea($('#output')[0], { + lineNumbers: true, + theme: 'solarized dark', + readOnly: true + }); + + $('#btn-vim').click(function() { + editor.setOption('keyMap', 'vim'); + editor.focus(); + localStorage[storage_mode] = "vim"; + }); + $('#btn-emacs').click(function() { + editor.setOption('keyMap', 'emacs'); + editor.focus(); + localStorage[storage_mode] = "emacs"; + }); + + $('#btn-step').click(function() { + var unparsedString = syn.prettyPrint( + sweet.expand(editor.getValue(), + undefined, + currentStep++), + $("#ck-hygiene").prop("checked")); + $("#lab-step").text(currentStep); + output.setValue(unparsedString); + }); + + var updateTimeout; + editor.on("change", function(e) { + clearTimeout(updateTimeout); + updateTimeout = setTimeout(updateExpand, 200); + }); + + function updateExpand() { + var code = editor.getValue(); + var expanded, compiled, res; + window.location = "editor.html#" + encodeURI(code); + localStorage[storage_code] = code; + try { + if (compileWithSourcemap) { + res = sweet.compile(code, { + sourceMap: true, + filename: "test.js", + readableNames: true + }); + } else { + res = sweet.compile(code, { + sourceMap: false, + readableNames: true + }); + } + compiled = res.code; + output.setValue(compiled); + + $('#errors').text(''); + $('#errors').hide(); + } catch (e) { + $('#errors').text(e); + $('#errors').show(); + } + } + updateExpand(); +}); diff --git a/editor/scripts/escodegen.js b/editor/scripts/escodegen.js new file mode 100644 index 0000000..f568c0c --- /dev/null +++ b/editor/scripts/escodegen.js @@ -0,0 +1,3902 @@ +// Generated by CommonJS Everywhere 0.8.1 +(function (global) { + function require(file, parentModule) { + if ({}.hasOwnProperty.call(require.cache, file)) + return require.cache[file]; + var resolved = require.resolve(file); + if (!resolved) + throw new Error('Failed to resolve module ' + file); + var module$ = { + id: file, + require: require, + filename: file, + exports: {}, + loaded: false, + parent: parentModule, + children: [] + }; + if (parentModule) + parentModule.children.push(module$); + var dirname = file.slice(0, file.lastIndexOf('/') + 1); + require.cache[file] = module$.exports; + resolved.call(module$.exports, module$, module$.exports, dirname, file); + module$.loaded = true; + return require.cache[file] = module$.exports; + } + require.modules = {}; + require.cache = {}; + require.resolve = function (file) { + return {}.hasOwnProperty.call(require.modules, file) ? require.modules[file] : void 0; + }; + require.define = function (file, fn) { + require.modules[file] = fn; + }; + var process = function () { + var cwd = '/'; + return { + title: 'browser', + version: 'v0.10.24', + browser: true, + env: {}, + argv: [], + nextTick: global.setImmediate || function (fn) { + setTimeout(fn, 0); + }, + cwd: function () { + return cwd; + }, + chdir: function (dir) { + cwd = dir; + } + }; + }(); + require.define('/tools/entry-point.js', function (module, exports, __dirname, __filename) { + (function () { + 'use strict'; + global.escodegen = require('/escodegen.js', module); + escodegen.browser = true; + }()); + }); + require.define('/escodegen.js', function (module, exports, __dirname, __filename) { + (function () { + 'use strict'; + var Syntax, Precedence, BinaryPrecedence, SourceNode, estraverse, esutils, isArray, base, indent, json, renumber, hexadecimal, quotes, escapeless, newline, space, parentheses, semicolons, safeConcatenation, directive, extra, parse, sourceMap, FORMAT_MINIFY, FORMAT_DEFAULTS; + estraverse = require('/node_modules/estraverse/estraverse.js', module); + esutils = require('/node_modules/esutils/lib/utils.js', module); + Syntax = { + AssignmentExpression: 'AssignmentExpression', + ArrayExpression: 'ArrayExpression', + ArrayPattern: 'ArrayPattern', + ArrowFunctionExpression: 'ArrowFunctionExpression', + BlockStatement: 'BlockStatement', + BinaryExpression: 'BinaryExpression', + BreakStatement: 'BreakStatement', + CallExpression: 'CallExpression', + CatchClause: 'CatchClause', + ComprehensionBlock: 'ComprehensionBlock', + ComprehensionExpression: 'ComprehensionExpression', + ConditionalExpression: 'ConditionalExpression', + ContinueStatement: 'ContinueStatement', + DirectiveStatement: 'DirectiveStatement', + DoWhileStatement: 'DoWhileStatement', + DebuggerStatement: 'DebuggerStatement', + EmptyStatement: 'EmptyStatement', + ExportDeclaration: 'ExportDeclaration', + ExpressionStatement: 'ExpressionStatement', + ForStatement: 'ForStatement', + ForInStatement: 'ForInStatement', + FunctionDeclaration: 'FunctionDeclaration', + FunctionExpression: 'FunctionExpression', + GeneratorExpression: 'GeneratorExpression', + Identifier: 'Identifier', + IfStatement: 'IfStatement', + Literal: 'Literal', + LabeledStatement: 'LabeledStatement', + LogicalExpression: 'LogicalExpression', + MemberExpression: 'MemberExpression', + NewExpression: 'NewExpression', + ObjectExpression: 'ObjectExpression', + ObjectPattern: 'ObjectPattern', + Program: 'Program', + Property: 'Property', + ReturnStatement: 'ReturnStatement', + SequenceExpression: 'SequenceExpression', + SwitchStatement: 'SwitchStatement', + SwitchCase: 'SwitchCase', + ThisExpression: 'ThisExpression', + ThrowStatement: 'ThrowStatement', + TryStatement: 'TryStatement', + UnaryExpression: 'UnaryExpression', + UpdateExpression: 'UpdateExpression', + VariableDeclaration: 'VariableDeclaration', + VariableDeclarator: 'VariableDeclarator', + WhileStatement: 'WhileStatement', + WithStatement: 'WithStatement', + YieldExpression: 'YieldExpression' + }; + Precedence = { + Sequence: 0, + Yield: 1, + Assignment: 1, + Conditional: 2, + ArrowFunction: 2, + LogicalOR: 3, + LogicalAND: 4, + BitwiseOR: 5, + BitwiseXOR: 6, + BitwiseAND: 7, + Equality: 8, + Relational: 9, + BitwiseSHIFT: 10, + Additive: 11, + Multiplicative: 12, + Unary: 13, + Postfix: 14, + Call: 15, + New: 16, + Member: 17, + Primary: 18 + }; + BinaryPrecedence = { + '||': Precedence.LogicalOR, + '&&': Precedence.LogicalAND, + '|': Precedence.BitwiseOR, + '^': Precedence.BitwiseXOR, + '&': Precedence.BitwiseAND, + '==': Precedence.Equality, + '!=': Precedence.Equality, + '===': Precedence.Equality, + '!==': Precedence.Equality, + 'is': Precedence.Equality, + 'isnt': Precedence.Equality, + '<': Precedence.Relational, + '>': Precedence.Relational, + '<=': Precedence.Relational, + '>=': Precedence.Relational, + 'in': Precedence.Relational, + 'instanceof': Precedence.Relational, + '<<': Precedence.BitwiseSHIFT, + '>>': Precedence.BitwiseSHIFT, + '>>>': Precedence.BitwiseSHIFT, + '+': Precedence.Additive, + '-': Precedence.Additive, + '*': Precedence.Multiplicative, + '%': Precedence.Multiplicative, + '/': Precedence.Multiplicative + }; + function getDefaultOptions() { + return { + indent: null, + base: null, + parse: null, + comment: false, + format: { + indent: { + style: ' ', + base: 0, + adjustMultilineComment: false + }, + newline: '\n', + space: ' ', + json: false, + renumber: false, + hexadecimal: false, + quotes: 'single', + escapeless: false, + compact: false, + parentheses: true, + semicolons: true, + safeConcatenation: false + }, + moz: { + comprehensionExpressionStartsWithAssignment: false, + starlessGenerator: false, + parenthesizedComprehensionBlock: false + }, + sourceMap: null, + sourceMapRoot: null, + sourceMapWithCode: false, + directive: false, + verbatim: null + }; + } + function stringRepeat(str, num) { + var result = ''; + for (num |= 0; num > 0; num >>>= 1, str += str) { + if (num & 1) { + result += str; + } + } + return result; + } + isArray = Array.isArray; + if (!isArray) { + isArray = function isArray(array) { + return Object.prototype.toString.call(array) === '[object Array]'; + }; + } + function hasLineTerminator(str) { + return /[\r\n]/g.test(str); + } + function endsWithLineTerminator(str) { + var len = str.length; + return len && esutils.code.isLineTerminator(str.charCodeAt(len - 1)); + } + function updateDeeply(target, override) { + var key, val; + function isHashObject(target) { + return typeof target === 'object' && target instanceof Object && !(target instanceof RegExp); + } + for (key in override) { + if (override.hasOwnProperty(key)) { + val = override[key]; + if (isHashObject(val)) { + if (isHashObject(target[key])) { + updateDeeply(target[key], val); + } else { + target[key] = updateDeeply({}, val); + } + } else { + target[key] = val; + } + } + } + return target; + } + function generateNumber(value) { + var result, point, temp, exponent, pos; + if (value !== value) { + throw new Error('Numeric literal whose value is NaN'); + } + if (value < 0 || value === 0 && 1 / value < 0) { + throw new Error('Numeric literal whose value is negative'); + } + if (value === 1 / 0) { + return json ? 'null' : renumber ? '1e400' : '1e+400'; + } + result = '' + value; + if (!renumber || result.length < 3) { + return result; + } + point = result.indexOf('.'); + if (!json && result.charCodeAt(0) === 48 && point === 1) { + point = 0; + result = result.slice(1); + } + temp = result; + result = result.replace('e+', 'e'); + exponent = 0; + if ((pos = temp.indexOf('e')) > 0) { + exponent = +temp.slice(pos + 1); + temp = temp.slice(0, pos); + } + if (point >= 0) { + exponent -= temp.length - point - 1; + temp = +(temp.slice(0, point) + temp.slice(point + 1)) + ''; + } + pos = 0; + while (temp.charCodeAt(temp.length + pos - 1) === 48) { + --pos; + } + if (pos !== 0) { + exponent -= pos; + temp = temp.slice(0, pos); + } + if (exponent !== 0) { + temp += 'e' + exponent; + } + if ((temp.length < result.length || hexadecimal && value > 1e12 && Math.floor(value) === value && (temp = '0x' + value.toString(16)).length < result.length) && +temp === value) { + result = temp; + } + return result; + } + function escapeRegExpCharacter(ch, previousIsBackslash) { + if ((ch & ~1) === 8232) { + return (previousIsBackslash ? 'u' : '\\u') + (ch === 8232 ? '2028' : '2029'); + } else if (ch === 10 || ch === 13) { + return (previousIsBackslash ? '' : '\\') + (ch === 10 ? 'n' : 'r'); + } + return String.fromCharCode(ch); + } + function generateRegExp(reg) { + var match, result, flags, i, iz, ch, characterInBrack, previousIsBackslash; + result = reg.toString(); + if (reg.source) { + match = result.match(/\/([^/]*)$/); + if (!match) { + return result; + } + flags = match[1]; + result = ''; + characterInBrack = false; + previousIsBackslash = false; + for (i = 0, iz = reg.source.length; i < iz; ++i) { + ch = reg.source.charCodeAt(i); + if (!previousIsBackslash) { + if (characterInBrack) { + if (ch === 93) { + characterInBrack = false; + } + } else { + if (ch === 47) { + result += '\\'; + } else if (ch === 91) { + characterInBrack = true; + } + } + result += escapeRegExpCharacter(ch, previousIsBackslash); + previousIsBackslash = ch === 92; + } else { + result += escapeRegExpCharacter(ch, previousIsBackslash); + previousIsBackslash = false; + } + } + return '/' + result + '/' + flags; + } + return result; + } + function escapeAllowedCharacter(code, next) { + var hex, result = '\\'; + switch (code) { + case 8: + result += 'b'; + break; + case 12: + result += 'f'; + break; + case 9: + result += 't'; + break; + default: + hex = code.toString(16).toUpperCase(); + if (json || code > 255) { + result += 'u' + '0000'.slice(hex.length) + hex; + } else if (code === 0 && !esutils.code.isDecimalDigit(next)) { + result += '0'; + } else if (code === 11) { + result += 'x0B'; + } else { + result += 'x' + '00'.slice(hex.length) + hex; + } + break; + } + return result; + } + function escapeDisallowedCharacter(code) { + var result = '\\'; + switch (code) { + case 92: + result += '\\'; + break; + case 10: + result += 'n'; + break; + case 13: + result += 'r'; + break; + case 8232: + result += 'u2028'; + break; + case 8233: + result += 'u2029'; + break; + default: + throw new Error('Incorrectly classified character'); + } + return result; + } + function escapeDirective(str) { + var i, iz, code, quote; + quote = quotes === 'double' ? '"' : "'"; + for (i = 0, iz = str.length; i < iz; ++i) { + code = str.charCodeAt(i); + if (code === 39) { + quote = '"'; + break; + } else if (code === 34) { + quote = "'"; + break; + } else if (code === 92) { + ++i; + } + } + return quote + str + quote; + } + function escapeString(str) { + var result = '', i, len, code, singleQuotes = 0, doubleQuotes = 0, single, quote; + for (i = 0, len = str.length; i < len; ++i) { + code = str.charCodeAt(i); + if (code === 39) { + ++singleQuotes; + } else if (code === 34) { + ++doubleQuotes; + } else if (code === 47 && json) { + result += '\\'; + } else if (esutils.code.isLineTerminator(code) || code === 92) { + result += escapeDisallowedCharacter(code); + continue; + } else if (json && code < 32 || !(json || escapeless || code >= 32 && code <= 126)) { + result += escapeAllowedCharacter(code, str.charCodeAt(i + 1)); + continue; + } + result += String.fromCharCode(code); + } + single = !(quotes === 'double' || quotes === 'auto' && doubleQuotes < singleQuotes); + quote = single ? "'" : '"'; + if (!(single ? singleQuotes : doubleQuotes)) { + return quote + result + quote; + } + str = result; + result = quote; + for (i = 0, len = str.length; i < len; ++i) { + code = str.charCodeAt(i); + if (code === 39 && single || code === 34 && !single) { + result += '\\'; + } + result += String.fromCharCode(code); + } + return result + quote; + } + function flattenToString(arr) { + var i, iz, elem, result = ''; + for (i = 0, iz = arr.length; i < iz; ++i) { + elem = arr[i]; + result += isArray(elem) ? flattenToString(elem) : elem; + } + return result; + } + function toSourceNodeWhenNeeded(generated, node) { + if (!sourceMap) { + if (isArray(generated)) { + return flattenToString(generated); + } else { + return generated; + } + } + if (node == null) { + if (generated instanceof SourceNode) { + return generated; + } else { + node = {}; + } + } + if (node.loc == null) { + return new SourceNode(null, null, sourceMap, generated, node.name || null); + } + return new SourceNode(node.loc.start.line, node.loc.start.column, sourceMap === true ? node.loc.source || null : sourceMap, generated, node.name || null); + } + function noEmptySpace() { + return space ? space : ' '; + } + function join(left, right) { + var leftSource = toSourceNodeWhenNeeded(left).toString(), rightSource = toSourceNodeWhenNeeded(right).toString(), leftCharCode = leftSource.charCodeAt(leftSource.length - 1), rightCharCode = rightSource.charCodeAt(0); + if ((leftCharCode === 43 || leftCharCode === 45) && leftCharCode === rightCharCode || esutils.code.isIdentifierPart(leftCharCode) && esutils.code.isIdentifierPart(rightCharCode) || leftCharCode === 47 && rightCharCode === 105) { + return [ + left, + noEmptySpace(), + right + ]; + } else if (esutils.code.isWhiteSpace(leftCharCode) || esutils.code.isLineTerminator(leftCharCode) || esutils.code.isWhiteSpace(rightCharCode) || esutils.code.isLineTerminator(rightCharCode)) { + return [ + left, + right + ]; + } + return [ + left, + space, + right + ]; + } + function addIndent(stmt) { + return [ + base, + stmt + ]; + } + function withIndent(fn) { + var previousBase, result; + previousBase = base; + base += indent; + result = fn.call(this, base); + base = previousBase; + return result; + } + function calculateSpaces(str) { + var i; + for (i = str.length - 1; i >= 0; --i) { + if (esutils.code.isLineTerminator(str.charCodeAt(i))) { + break; + } + } + return str.length - 1 - i; + } + function adjustMultilineComment(value, specialBase) { + var array, i, len, line, j, spaces, previousBase, sn; + array = value.split(/\r\n|[\r\n]/); + spaces = Number.MAX_VALUE; + for (i = 1, len = array.length; i < len; ++i) { + line = array[i]; + j = 0; + while (j < line.length && esutils.code.isWhiteSpace(line.charCodeAt(j))) { + ++j; + } + if (spaces > j) { + spaces = j; + } + } + if (typeof specialBase !== 'undefined') { + previousBase = base; + if (array[1][spaces] === '*') { + specialBase += ' '; + } + base = specialBase; + } else { + if (spaces & 1) { + --spaces; + } + previousBase = base; + } + for (i = 1, len = array.length; i < len; ++i) { + sn = toSourceNodeWhenNeeded(addIndent(array[i].slice(spaces))); + array[i] = sourceMap ? sn.join('') : sn; + } + base = previousBase; + return array.join('\n'); + } + function generateComment(comment, specialBase) { + if (comment.type === 'Line') { + if (endsWithLineTerminator(comment.value)) { + return '//' + comment.value; + } else { + return '//' + comment.value + '\n'; + } + } + if (extra.format.indent.adjustMultilineComment && /[\n\r]/.test(comment.value)) { + return adjustMultilineComment('/*' + comment.value + '*/', specialBase); + } + return '/*' + comment.value + '*/'; + } + function addCommentsToStatement(stmt, result) { + var i, len, comment, save, tailingToStatement, specialBase, fragment; + if (stmt.leadingComments && stmt.leadingComments.length > 0) { + save = result; + comment = stmt.leadingComments[0]; + result = []; + if (safeConcatenation && stmt.type === Syntax.Program && stmt.body.length === 0) { + result.push('\n'); + } + result.push(generateComment(comment)); + if (!endsWithLineTerminator(toSourceNodeWhenNeeded(result).toString())) { + result.push('\n'); + } + for (i = 1, len = stmt.leadingComments.length; i < len; ++i) { + comment = stmt.leadingComments[i]; + fragment = [generateComment(comment)]; + if (!endsWithLineTerminator(toSourceNodeWhenNeeded(fragment).toString())) { + fragment.push('\n'); + } + result.push(addIndent(fragment)); + } + result.push(addIndent(save)); + } + if (stmt.trailingComments) { + tailingToStatement = !endsWithLineTerminator(toSourceNodeWhenNeeded(result).toString()); + specialBase = stringRepeat(' ', calculateSpaces(toSourceNodeWhenNeeded([ + base, + result, + indent + ]).toString())); + for (i = 0, len = stmt.trailingComments.length; i < len; ++i) { + comment = stmt.trailingComments[i]; + if (tailingToStatement) { + if (i === 0) { + result = [ + result, + indent + ]; + } else { + result = [ + result, + specialBase + ]; + } + result.push(generateComment(comment, specialBase)); + } else { + result = [ + result, + addIndent(generateComment(comment)) + ]; + } + if (i !== len - 1 && !endsWithLineTerminator(toSourceNodeWhenNeeded(result).toString())) { + result = [ + result, + '\n' + ]; + } + } + } + return result; + } + function parenthesize(text, current, should) { + if (current < should) { + return [ + '(', + text, + ')' + ]; + } + return text; + } + function maybeBlock(stmt, semicolonOptional, functionBody) { + var result, noLeadingComment; + noLeadingComment = !extra.comment || !stmt.leadingComments; + if (stmt.type === Syntax.BlockStatement && noLeadingComment) { + return [ + space, + generateStatement(stmt, { functionBody: functionBody }) + ]; + } + if (stmt.type === Syntax.EmptyStatement && noLeadingComment) { + return ';'; + } + withIndent(function () { + result = [ + newline, + addIndent(generateStatement(stmt, { + semicolonOptional: semicolonOptional, + functionBody: functionBody + })) + ]; + }); + return result; + } + function maybeBlockSuffix(stmt, result) { + var ends = endsWithLineTerminator(toSourceNodeWhenNeeded(result).toString()); + if (stmt.type === Syntax.BlockStatement && (!extra.comment || !stmt.leadingComments) && !ends) { + return [ + result, + space + ]; + } + if (ends) { + return [ + result, + base + ]; + } + return [ + result, + newline, + base + ]; + } + function generateVerbatim(expr, option) { + var i, result; + result = expr[extra.verbatim].split(/\r\n|\n/); + for (i = 1; i < result.length; i++) { + result[i] = newline + base + result[i]; + } + result = parenthesize(result, Precedence.Sequence, option.precedence); + return toSourceNodeWhenNeeded(result, expr); + } + function generateIdentifier(node) { + return toSourceNodeWhenNeeded(node.name, node); + } + function generatePattern(node, options) { + var result; + if (node.type === Syntax.Identifier) { + result = generateIdentifier(node); + } else { + result = generateExpression(node, { + precedence: options.precedence, + allowIn: options.allowIn, + allowCall: true + }); + } + return result; + } + function generateFunctionBody(node) { + var result, i, len, expr, arrow; + arrow = node.type === Syntax.ArrowFunctionExpression; + if (arrow && node.params.length === 1 && node.params[0].type === Syntax.Identifier) { + result = [generateIdentifier(node.params[0])]; + } else { + result = ['(']; + for (i = 0, len = node.params.length; i < len; ++i) { + result.push(generatePattern(node.params[i], { + precedence: Precedence.Assignment, + allowIn: true + })); + if (i + 1 < len) { + result.push(',' + space); + } + } + result.push(')'); + } + if (arrow) { + result.push(space, '=>'); + } + if (node.expression) { + result.push(space); + expr = generateExpression(node.body, { + precedence: Precedence.Assignment, + allowIn: true, + allowCall: true + }); + if (expr.toString().charAt(0) === '{') { + expr = [ + '(', + expr, + ')' + ]; + } + result.push(expr); + } else { + result.push(maybeBlock(node.body, false, true)); + } + return result; + } + function generateExpression(expr, option) { + var result, precedence, type, currentPrecedence, i, len, raw, fragment, multiline, leftCharCode, leftSource, rightCharCode, allowIn, allowCall, allowUnparenthesizedNew, property, isGenerator; + precedence = option.precedence; + allowIn = option.allowIn; + allowCall = option.allowCall; + type = expr.type || option.type; + if (extra.verbatim && expr.hasOwnProperty(extra.verbatim)) { + return generateVerbatim(expr, option); + } + switch (type) { + case Syntax.SequenceExpression: + result = []; + allowIn |= Precedence.Sequence < precedence; + for (i = 0, len = expr.expressions.length; i < len; ++i) { + result.push(generateExpression(expr.expressions[i], { + precedence: Precedence.Assignment, + allowIn: allowIn, + allowCall: true + })); + if (i + 1 < len) { + result.push(',' + space); + } + } + result = parenthesize(result, Precedence.Sequence, precedence); + break; + case Syntax.AssignmentExpression: + allowIn |= Precedence.Assignment < precedence; + result = parenthesize([ + generateExpression(expr.left, { + precedence: Precedence.Call, + allowIn: allowIn, + allowCall: true + }), + space + expr.operator + space, + generateExpression(expr.right, { + precedence: Precedence.Assignment, + allowIn: allowIn, + allowCall: true + }) + ], Precedence.Assignment, precedence); + break; + case Syntax.ArrowFunctionExpression: + allowIn |= Precedence.ArrowFunction < precedence; + result = parenthesize(generateFunctionBody(expr), Precedence.ArrowFunction, precedence); + break; + case Syntax.ConditionalExpression: + allowIn |= Precedence.Conditional < precedence; + result = parenthesize([ + generateExpression(expr.test, { + precedence: Precedence.LogicalOR, + allowIn: allowIn, + allowCall: true + }), + space + '?' + space, + generateExpression(expr.consequent, { + precedence: Precedence.Assignment, + allowIn: allowIn, + allowCall: true + }), + space + ':' + space, + generateExpression(expr.alternate, { + precedence: Precedence.Assignment, + allowIn: allowIn, + allowCall: true + }) + ], Precedence.Conditional, precedence); + break; + case Syntax.LogicalExpression: + case Syntax.BinaryExpression: + currentPrecedence = BinaryPrecedence[expr.operator]; + allowIn |= currentPrecedence < precedence; + fragment = generateExpression(expr.left, { + precedence: currentPrecedence, + allowIn: allowIn, + allowCall: true + }); + leftSource = fragment.toString(); + if (leftSource.charCodeAt(leftSource.length - 1) === 47 && esutils.code.isIdentifierPart(expr.operator.charCodeAt(0))) { + result = [ + fragment, + noEmptySpace(), + expr.operator + ]; + } else { + result = join(fragment, expr.operator); + } + fragment = generateExpression(expr.right, { + precedence: currentPrecedence + 1, + allowIn: allowIn, + allowCall: true + }); + if (expr.operator === '/' && fragment.toString().charAt(0) === '/' || expr.operator.slice(-1) === '<' && fragment.toString().slice(0, 3) === '!--') { + result.push(noEmptySpace(), fragment); + } else { + result = join(result, fragment); + } + if (expr.operator === 'in' && !allowIn) { + result = [ + '(', + result, + ')' + ]; + } else { + result = parenthesize(result, currentPrecedence, precedence); + } + break; + case Syntax.CallExpression: + result = [generateExpression(expr.callee, { + precedence: Precedence.Call, + allowIn: true, + allowCall: true, + allowUnparenthesizedNew: false + })]; + result.push('('); + for (i = 0, len = expr['arguments'].length; i < len; ++i) { + result.push(generateExpression(expr['arguments'][i], { + precedence: Precedence.Assignment, + allowIn: true, + allowCall: true + })); + if (i + 1 < len) { + result.push(',' + space); + } + } + result.push(')'); + if (!allowCall) { + result = [ + '(', + result, + ')' + ]; + } else { + result = parenthesize(result, Precedence.Call, precedence); + } + break; + case Syntax.NewExpression: + len = expr['arguments'].length; + allowUnparenthesizedNew = option.allowUnparenthesizedNew === undefined || option.allowUnparenthesizedNew; + result = join('new', generateExpression(expr.callee, { + precedence: Precedence.New, + allowIn: true, + allowCall: false, + allowUnparenthesizedNew: allowUnparenthesizedNew && !parentheses && len === 0 + })); + if (!allowUnparenthesizedNew || parentheses || len > 0) { + result.push('('); + for (i = 0; i < len; ++i) { + result.push(generateExpression(expr['arguments'][i], { + precedence: Precedence.Assignment, + allowIn: true, + allowCall: true + })); + if (i + 1 < len) { + result.push(',' + space); + } + } + result.push(')'); + } + result = parenthesize(result, Precedence.New, precedence); + break; + case Syntax.MemberExpression: + result = [generateExpression(expr.object, { + precedence: Precedence.Call, + allowIn: true, + allowCall: allowCall, + allowUnparenthesizedNew: false + })]; + if (expr.computed) { + result.push('[', generateExpression(expr.property, { + precedence: Precedence.Sequence, + allowIn: true, + allowCall: allowCall + }), ']'); + } else { + if (expr.object.type === Syntax.Literal && typeof expr.object.value === 'number') { + fragment = toSourceNodeWhenNeeded(result).toString(); + if (fragment.indexOf('.') < 0 && !/[eExX]/.test(fragment) && esutils.code.isDecimalDigit(fragment.charCodeAt(fragment.length - 1)) && !(fragment.length >= 2 && fragment.charCodeAt(0) === 48)) { + result.push('.'); + } + } + result.push('.', generateIdentifier(expr.property)); + } + result = parenthesize(result, Precedence.Member, precedence); + break; + case Syntax.UnaryExpression: + fragment = generateExpression(expr.argument, { + precedence: Precedence.Unary, + allowIn: true, + allowCall: true + }); + if (space === '') { + result = join(expr.operator, fragment); + } else { + result = [expr.operator]; + if (expr.operator.length > 2) { + result = join(result, fragment); + } else { + leftSource = toSourceNodeWhenNeeded(result).toString(); + leftCharCode = leftSource.charCodeAt(leftSource.length - 1); + rightCharCode = fragment.toString().charCodeAt(0); + if ((leftCharCode === 43 || leftCharCode === 45) && leftCharCode === rightCharCode || esutils.code.isIdentifierPart(leftCharCode) && esutils.code.isIdentifierPart(rightCharCode)) { + result.push(noEmptySpace(), fragment); + } else { + result.push(fragment); + } + } + } + result = parenthesize(result, Precedence.Unary, precedence); + break; + case Syntax.YieldExpression: + if (expr.delegate) { + result = 'yield*'; + } else { + result = 'yield'; + } + if (expr.argument) { + result = join(result, generateExpression(expr.argument, { + precedence: Precedence.Yield, + allowIn: true, + allowCall: true + })); + } + result = parenthesize(result, Precedence.Yield, precedence); + break; + case Syntax.UpdateExpression: + if (expr.prefix) { + result = parenthesize([ + expr.operator, + generateExpression(expr.argument, { + precedence: Precedence.Unary, + allowIn: true, + allowCall: true + }) + ], Precedence.Unary, precedence); + } else { + result = parenthesize([ + generateExpression(expr.argument, { + precedence: Precedence.Postfix, + allowIn: true, + allowCall: true + }), + expr.operator + ], Precedence.Postfix, precedence); + } + break; + case Syntax.FunctionExpression: + isGenerator = expr.generator && !extra.moz.starlessGenerator; + result = isGenerator ? 'function*' : 'function'; + if (expr.id) { + result = [ + result, + isGenerator ? space : noEmptySpace(), + generateIdentifier(expr.id), + generateFunctionBody(expr) + ]; + } else { + result = [ + result + space, + generateFunctionBody(expr) + ]; + } + break; + case Syntax.ArrayPattern: + case Syntax.ArrayExpression: + if (!expr.elements.length) { + result = '[]'; + break; + } + multiline = expr.elements.length > 1; + result = [ + '[', + multiline ? newline : '' + ]; + withIndent(function (indent) { + for (i = 0, len = expr.elements.length; i < len; ++i) { + if (!expr.elements[i]) { + if (multiline) { + result.push(indent); + } + if (i + 1 === len) { + result.push(','); + } + } else { + result.push(multiline ? indent : '', generateExpression(expr.elements[i], { + precedence: Precedence.Assignment, + allowIn: true, + allowCall: true + })); + } + if (i + 1 < len) { + result.push(',' + (multiline ? newline : space)); + } + } + }); + if (multiline && !endsWithLineTerminator(toSourceNodeWhenNeeded(result).toString())) { + result.push(newline); + } + result.push(multiline ? base : '', ']'); + break; + case Syntax.Property: + if (expr.kind === 'get' || expr.kind === 'set') { + result = [ + expr.kind, + noEmptySpace(), + generateExpression(expr.key, { + precedence: Precedence.Sequence, + allowIn: true, + allowCall: true + }), + generateFunctionBody(expr.value) + ]; + } else { + if (expr.shorthand) { + result = generateExpression(expr.key, { + precedence: Precedence.Sequence, + allowIn: true, + allowCall: true + }); + } else if (expr.method) { + result = []; + if (expr.value.generator) { + result.push('*'); + } + result.push(generateExpression(expr.key, { + precedence: Precedence.Sequence, + allowIn: true, + allowCall: true + }), generateFunctionBody(expr.value)); + } else { + result = [ + generateExpression(expr.key, { + precedence: Precedence.Sequence, + allowIn: true, + allowCall: true + }), + ':' + space, + generateExpression(expr.value, { + precedence: Precedence.Assignment, + allowIn: true, + allowCall: true + }) + ]; + } + } + break; + case Syntax.ObjectExpression: + if (!expr.properties.length) { + result = '{}'; + break; + } + multiline = expr.properties.length > 1; + withIndent(function () { + fragment = generateExpression(expr.properties[0], { + precedence: Precedence.Sequence, + allowIn: true, + allowCall: true, + type: Syntax.Property + }); + }); + if (!multiline) { + if (!hasLineTerminator(toSourceNodeWhenNeeded(fragment).toString())) { + result = [ + '{', + space, + fragment, + space, + '}' + ]; + break; + } + } + withIndent(function (indent) { + result = [ + '{', + newline, + indent, + fragment + ]; + if (multiline) { + result.push(',' + newline); + for (i = 1, len = expr.properties.length; i < len; ++i) { + result.push(indent, generateExpression(expr.properties[i], { + precedence: Precedence.Sequence, + allowIn: true, + allowCall: true, + type: Syntax.Property + })); + if (i + 1 < len) { + result.push(',' + newline); + } + } + } + }); + if (!endsWithLineTerminator(toSourceNodeWhenNeeded(result).toString())) { + result.push(newline); + } + result.push(base, '}'); + break; + case Syntax.ObjectPattern: + if (!expr.properties.length) { + result = '{}'; + break; + } + multiline = false; + if (expr.properties.length === 1) { + property = expr.properties[0]; + if (property.value.type !== Syntax.Identifier) { + multiline = true; + } + } else { + for (i = 0, len = expr.properties.length; i < len; ++i) { + property = expr.properties[i]; + if (!property.shorthand) { + multiline = true; + break; + } + } + } + result = [ + '{', + multiline ? newline : '' + ]; + withIndent(function (indent) { + for (i = 0, len = expr.properties.length; i < len; ++i) { + result.push(multiline ? indent : '', generateExpression(expr.properties[i], { + precedence: Precedence.Sequence, + allowIn: true, + allowCall: true + })); + if (i + 1 < len) { + result.push(',' + (multiline ? newline : space)); + } + } + }); + if (multiline && !endsWithLineTerminator(toSourceNodeWhenNeeded(result).toString())) { + result.push(newline); + } + result.push(multiline ? base : '', '}'); + break; + case Syntax.ThisExpression: + result = 'this'; + break; + case Syntax.Identifier: + result = generateIdentifier(expr); + break; + case Syntax.Literal: + if (expr.hasOwnProperty('raw') && parse) { + try { + raw = parse(expr.raw).body[0].expression; + if (raw.type === Syntax.Literal) { + if (raw.value === expr.value) { + result = expr.raw; + break; + } + } + } catch (e) { + } + } + if (expr.value === null) { + result = 'null'; + break; + } + if (typeof expr.value === 'string') { + result = escapeString(expr.value); + break; + } + if (typeof expr.value === 'number') { + result = generateNumber(expr.value); + break; + } + if (typeof expr.value === 'boolean') { + result = expr.value ? 'true' : 'false'; + break; + } + result = generateRegExp(expr.value); + break; + case Syntax.GeneratorExpression: + case Syntax.ComprehensionExpression: + result = type === Syntax.GeneratorExpression ? ['('] : ['[']; + if (extra.moz.comprehensionExpressionStartsWithAssignment) { + fragment = generateExpression(expr.body, { + precedence: Precedence.Assignment, + allowIn: true, + allowCall: true + }); + result.push(fragment); + } + if (expr.blocks) { + withIndent(function () { + for (i = 0, len = expr.blocks.length; i < len; ++i) { + fragment = generateExpression(expr.blocks[i], { + precedence: Precedence.Sequence, + allowIn: true, + allowCall: true + }); + if (i > 0 || extra.moz.comprehensionExpressionStartsWithAssignment) { + result = join(result, fragment); + } else { + result.push(fragment); + } + } + }); + } + if (expr.filter) { + result = join(result, 'if' + space); + fragment = generateExpression(expr.filter, { + precedence: Precedence.Sequence, + allowIn: true, + allowCall: true + }); + if (extra.moz.parenthesizedComprehensionBlock) { + result = join(result, [ + '(', + fragment, + ')' + ]); + } else { + result = join(result, fragment); + } + } + if (!extra.moz.comprehensionExpressionStartsWithAssignment) { + fragment = generateExpression(expr.body, { + precedence: Precedence.Assignment, + allowIn: true, + allowCall: true + }); + result = join(result, fragment); + } + result.push(type === Syntax.GeneratorExpression ? ')' : ']'); + break; + case Syntax.ComprehensionBlock: + if (expr.left.type === Syntax.VariableDeclaration) { + fragment = [ + expr.left.kind, + noEmptySpace(), + generateStatement(expr.left.declarations[0], { allowIn: false }) + ]; + } else { + fragment = generateExpression(expr.left, { + precedence: Precedence.Call, + allowIn: true, + allowCall: true + }); + } + fragment = join(fragment, expr.of ? 'of' : 'in'); + fragment = join(fragment, generateExpression(expr.right, { + precedence: Precedence.Sequence, + allowIn: true, + allowCall: true + })); + if (extra.moz.parenthesizedComprehensionBlock) { + result = [ + 'for' + space + '(', + fragment, + ')' + ]; + } else { + result = join('for' + space, fragment); + } + break; + default: + throw new Error('Unknown expression type: ' + expr.type); + } + return toSourceNodeWhenNeeded(result, expr); + } + function generateStatement(stmt, option) { + var i, len, result, node, allowIn, functionBody, directiveContext, fragment, semicolon, isGenerator; + allowIn = true; + semicolon = ';'; + functionBody = false; + directiveContext = false; + if (option) { + allowIn = option.allowIn === undefined || option.allowIn; + if (!semicolons && option.semicolonOptional === true) { + semicolon = ''; + } + functionBody = option.functionBody; + directiveContext = option.directiveContext; + } + switch (stmt.type) { + case Syntax.BlockStatement: + result = [ + '{', + newline + ]; + withIndent(function () { + for (i = 0, len = stmt.body.length; i < len; ++i) { + fragment = addIndent(generateStatement(stmt.body[i], { + semicolonOptional: i === len - 1, + directiveContext: functionBody + })); + result.push(fragment); + if (!endsWithLineTerminator(toSourceNodeWhenNeeded(fragment).toString())) { + result.push(newline); + } + } + }); + result.push(addIndent('}')); + break; + case Syntax.BreakStatement: + if (stmt.label) { + result = 'break ' + stmt.label.name + semicolon; + } else { + result = 'break' + semicolon; + } + break; + case Syntax.ContinueStatement: + if (stmt.label) { + result = 'continue ' + stmt.label.name + semicolon; + } else { + result = 'continue' + semicolon; + } + break; + case Syntax.DirectiveStatement: + if (stmt.raw) { + result = stmt.raw + semicolon; + } else { + result = escapeDirective(stmt.directive) + semicolon; + } + break; + case Syntax.DoWhileStatement: + result = join('do', maybeBlock(stmt.body)); + result = maybeBlockSuffix(stmt.body, result); + result = join(result, [ + 'while' + space + '(', + generateExpression(stmt.test, { + precedence: Precedence.Sequence, + allowIn: true, + allowCall: true + }), + ')' + semicolon + ]); + break; + case Syntax.CatchClause: + withIndent(function () { + var guard; + result = [ + 'catch' + space + '(', + generateExpression(stmt.param, { + precedence: Precedence.Sequence, + allowIn: true, + allowCall: true + }), + ')' + ]; + if (stmt.guard) { + guard = generateExpression(stmt.guard, { + precedence: Precedence.Sequence, + allowIn: true, + allowCall: true + }); + result.splice(2, 0, ' if ', guard); + } + }); + result.push(maybeBlock(stmt.body)); + break; + case Syntax.DebuggerStatement: + result = 'debugger' + semicolon; + break; + case Syntax.EmptyStatement: + result = ';'; + break; + case Syntax.ExportDeclaration: + result = 'export '; + if (stmt.declaration) { + result = [ + result, + generateStatement(stmt.declaration, { semicolonOptional: semicolon === '' }) + ]; + break; + } + break; + case Syntax.ExpressionStatement: + result = [generateExpression(stmt.expression, { + precedence: Precedence.Sequence, + allowIn: true, + allowCall: true + })]; + fragment = toSourceNodeWhenNeeded(result).toString(); + if (fragment.charAt(0) === '{' || fragment.slice(0, 8) === 'function' && '* ('.indexOf(fragment.charAt(8)) >= 0 || directive && directiveContext && stmt.expression.type === Syntax.Literal && typeof stmt.expression.value === 'string') { + result = [ + '(', + result, + ')' + semicolon + ]; + } else { + result.push(semicolon); + } + break; + case Syntax.VariableDeclarator: + if (stmt.init) { + result = [ + generateExpression(stmt.id, { + precedence: Precedence.Assignment, + allowIn: allowIn, + allowCall: true + }), + space, + '=', + space, + generateExpression(stmt.init, { + precedence: Precedence.Assignment, + allowIn: allowIn, + allowCall: true + }) + ]; + } else { + result = generatePattern(stmt.id, { + precedence: Precedence.Assignment, + allowIn: allowIn + }); + } + break; + case Syntax.VariableDeclaration: + result = [stmt.kind]; + if (stmt.declarations.length === 1 && stmt.declarations[0].init && stmt.declarations[0].init.type === Syntax.FunctionExpression) { + result.push(noEmptySpace(), generateStatement(stmt.declarations[0], { allowIn: allowIn })); + } else { + withIndent(function () { + node = stmt.declarations[0]; + if (extra.comment && node.leadingComments) { + result.push('\n', addIndent(generateStatement(node, { allowIn: allowIn }))); + } else { + result.push(noEmptySpace(), generateStatement(node, { allowIn: allowIn })); + } + for (i = 1, len = stmt.declarations.length; i < len; ++i) { + node = stmt.declarations[i]; + if (extra.comment && node.leadingComments) { + result.push(',' + newline, addIndent(generateStatement(node, { allowIn: allowIn }))); + } else { + result.push(',' + space, generateStatement(node, { allowIn: allowIn })); + } + } + }); + } + result.push(semicolon); + break; + case Syntax.ThrowStatement: + result = [ + join('throw', generateExpression(stmt.argument, { + precedence: Precedence.Sequence, + allowIn: true, + allowCall: true + })), + semicolon + ]; + break; + case Syntax.TryStatement: + result = [ + 'try', + maybeBlock(stmt.block) + ]; + result = maybeBlockSuffix(stmt.block, result); + if (stmt.handlers) { + for (i = 0, len = stmt.handlers.length; i < len; ++i) { + result = join(result, generateStatement(stmt.handlers[i])); + if (stmt.finalizer || i + 1 !== len) { + result = maybeBlockSuffix(stmt.handlers[i].body, result); + } + } + } else { + stmt.guardedHandlers = stmt.guardedHandlers || []; + for (i = 0, len = stmt.guardedHandlers.length; i < len; ++i) { + result = join(result, generateStatement(stmt.guardedHandlers[i])); + if (stmt.finalizer || i + 1 !== len) { + result = maybeBlockSuffix(stmt.guardedHandlers[i].body, result); + } + } + if (stmt.handler) { + if (isArray(stmt.handler)) { + for (i = 0, len = stmt.handler.length; i < len; ++i) { + result = join(result, generateStatement(stmt.handler[i])); + if (stmt.finalizer || i + 1 !== len) { + result = maybeBlockSuffix(stmt.handler[i].body, result); + } + } + } else { + result = join(result, generateStatement(stmt.handler)); + if (stmt.finalizer) { + result = maybeBlockSuffix(stmt.handler.body, result); + } + } + } + } + if (stmt.finalizer) { + result = join(result, [ + 'finally', + maybeBlock(stmt.finalizer) + ]); + } + break; + case Syntax.SwitchStatement: + withIndent(function () { + result = [ + 'switch' + space + '(', + generateExpression(stmt.discriminant, { + precedence: Precedence.Sequence, + allowIn: true, + allowCall: true + }), + ')' + space + '{' + newline + ]; + }); + if (stmt.cases) { + for (i = 0, len = stmt.cases.length; i < len; ++i) { + fragment = addIndent(generateStatement(stmt.cases[i], { semicolonOptional: i === len - 1 })); + result.push(fragment); + if (!endsWithLineTerminator(toSourceNodeWhenNeeded(fragment).toString())) { + result.push(newline); + } + } + } + result.push(addIndent('}')); + break; + case Syntax.SwitchCase: + withIndent(function () { + if (stmt.test) { + result = [ + join('case', generateExpression(stmt.test, { + precedence: Precedence.Sequence, + allowIn: true, + allowCall: true + })), + ':' + ]; + } else { + result = ['default:']; + } + i = 0; + len = stmt.consequent.length; + if (len && stmt.consequent[0].type === Syntax.BlockStatement) { + fragment = maybeBlock(stmt.consequent[0]); + result.push(fragment); + i = 1; + } + if (i !== len && !endsWithLineTerminator(toSourceNodeWhenNeeded(result).toString())) { + result.push(newline); + } + for (; i < len; ++i) { + fragment = addIndent(generateStatement(stmt.consequent[i], { semicolonOptional: i === len - 1 && semicolon === '' })); + result.push(fragment); + if (i + 1 !== len && !endsWithLineTerminator(toSourceNodeWhenNeeded(fragment).toString())) { + result.push(newline); + } + } + }); + break; + case Syntax.IfStatement: + withIndent(function () { + result = [ + 'if' + space + '(', + generateExpression(stmt.test, { + precedence: Precedence.Sequence, + allowIn: true, + allowCall: true + }), + ')' + ]; + }); + if (stmt.alternate) { + result.push(maybeBlock(stmt.consequent)); + result = maybeBlockSuffix(stmt.consequent, result); + if (stmt.alternate.type === Syntax.IfStatement) { + result = join(result, [ + 'else ', + generateStatement(stmt.alternate, { semicolonOptional: semicolon === '' }) + ]); + } else { + result = join(result, join('else', maybeBlock(stmt.alternate, semicolon === ''))); + } + } else { + result.push(maybeBlock(stmt.consequent, semicolon === '')); + } + break; + case Syntax.ForStatement: + withIndent(function () { + result = ['for' + space + '(']; + if (stmt.init) { + if (stmt.init.type === Syntax.VariableDeclaration) { + result.push(generateStatement(stmt.init, { allowIn: false })); + } else { + result.push(generateExpression(stmt.init, { + precedence: Precedence.Sequence, + allowIn: false, + allowCall: true + }), ';'); + } + } else { + result.push(';'); + } + if (stmt.test) { + result.push(space, generateExpression(stmt.test, { + precedence: Precedence.Sequence, + allowIn: true, + allowCall: true + }), ';'); + } else { + result.push(';'); + } + if (stmt.update) { + result.push(space, generateExpression(stmt.update, { + precedence: Precedence.Sequence, + allowIn: true, + allowCall: true + }), ')'); + } else { + result.push(')'); + } + }); + result.push(maybeBlock(stmt.body, semicolon === '')); + break; + case Syntax.ForInStatement: + result = ['for' + space + '(']; + withIndent(function () { + if (stmt.left.type === Syntax.VariableDeclaration) { + withIndent(function () { + result.push(stmt.left.kind + noEmptySpace(), generateStatement(stmt.left.declarations[0], { allowIn: false })); + }); + } else { + result.push(generateExpression(stmt.left, { + precedence: Precedence.Call, + allowIn: true, + allowCall: true + })); + } + result = join(result, 'in'); + result = [ + join(result, generateExpression(stmt.right, { + precedence: Precedence.Sequence, + allowIn: true, + allowCall: true + })), + ')' + ]; + }); + result.push(maybeBlock(stmt.body, semicolon === '')); + break; + case Syntax.LabeledStatement: + result = [ + stmt.label.name + ':', + maybeBlock(stmt.body, semicolon === '') + ]; + break; + case Syntax.Program: + len = stmt.body.length; + result = [safeConcatenation && len > 0 ? '\n' : '']; + for (i = 0; i < len; ++i) { + fragment = addIndent(generateStatement(stmt.body[i], { + semicolonOptional: !safeConcatenation && i === len - 1, + directiveContext: true + })); + result.push(fragment); + if (i + 1 < len && !endsWithLineTerminator(toSourceNodeWhenNeeded(fragment).toString())) { + result.push(newline); + } + } + break; + case Syntax.FunctionDeclaration: + isGenerator = stmt.generator && !extra.moz.starlessGenerator; + result = [ + isGenerator ? 'function*' : 'function', + isGenerator ? space : noEmptySpace(), + generateIdentifier(stmt.id), + generateFunctionBody(stmt) + ]; + break; + case Syntax.ReturnStatement: + if (stmt.argument) { + result = [ + join('return', generateExpression(stmt.argument, { + precedence: Precedence.Sequence, + allowIn: true, + allowCall: true + })), + semicolon + ]; + } else { + result = ['return' + semicolon]; + } + break; + case Syntax.WhileStatement: + withIndent(function () { + result = [ + 'while' + space + '(', + generateExpression(stmt.test, { + precedence: Precedence.Sequence, + allowIn: true, + allowCall: true + }), + ')' + ]; + }); + result.push(maybeBlock(stmt.body, semicolon === '')); + break; + case Syntax.WithStatement: + withIndent(function () { + result = [ + 'with' + space + '(', + generateExpression(stmt.object, { + precedence: Precedence.Sequence, + allowIn: true, + allowCall: true + }), + ')' + ]; + }); + result.push(maybeBlock(stmt.body, semicolon === '')); + break; + default: + throw new Error('Unknown statement type: ' + stmt.type); + } + if (extra.comment) { + result = addCommentsToStatement(stmt, result); + } + fragment = toSourceNodeWhenNeeded(result).toString(); + if (stmt.type === Syntax.Program && !safeConcatenation && newline === '' && fragment.charAt(fragment.length - 1) === '\n') { + result = sourceMap ? toSourceNodeWhenNeeded(result).replaceRight(/\s+$/, '') : fragment.replace(/\s+$/, ''); + } + return toSourceNodeWhenNeeded(result, stmt); + } + function generate(node, options) { + var defaultOptions = getDefaultOptions(), result, pair; + if (options != null) { + if (typeof options.indent === 'string') { + defaultOptions.format.indent.style = options.indent; + } + if (typeof options.base === 'number') { + defaultOptions.format.indent.base = options.base; + } + options = updateDeeply(defaultOptions, options); + indent = options.format.indent.style; + if (typeof options.base === 'string') { + base = options.base; + } else { + base = stringRepeat(indent, options.format.indent.base); + } + } else { + options = defaultOptions; + indent = options.format.indent.style; + base = stringRepeat(indent, options.format.indent.base); + } + json = options.format.json; + renumber = options.format.renumber; + hexadecimal = json ? false : options.format.hexadecimal; + quotes = json ? 'double' : options.format.quotes; + escapeless = options.format.escapeless; + newline = options.format.newline; + space = options.format.space; + if (options.format.compact) { + newline = space = indent = base = ''; + } + parentheses = options.format.parentheses; + semicolons = options.format.semicolons; + safeConcatenation = options.format.safeConcatenation; + directive = options.directive; + parse = json ? null : options.parse; + sourceMap = options.sourceMap; + extra = options; + if (sourceMap) { + if (!exports.browser) { + SourceNode = require('/node_modules/source-map/lib/source-map.js', module).SourceNode; + } else { + SourceNode = global.sourceMap.SourceNode; + } + } + switch (node.type) { + case Syntax.BlockStatement: + case Syntax.BreakStatement: + case Syntax.CatchClause: + case Syntax.ContinueStatement: + case Syntax.DirectiveStatement: + case Syntax.DoWhileStatement: + case Syntax.DebuggerStatement: + case Syntax.EmptyStatement: + case Syntax.ExpressionStatement: + case Syntax.ForStatement: + case Syntax.ForInStatement: + case Syntax.FunctionDeclaration: + case Syntax.IfStatement: + case Syntax.LabeledStatement: + case Syntax.Program: + case Syntax.ReturnStatement: + case Syntax.SwitchStatement: + case Syntax.SwitchCase: + case Syntax.ThrowStatement: + case Syntax.TryStatement: + case Syntax.VariableDeclaration: + case Syntax.VariableDeclarator: + case Syntax.WhileStatement: + case Syntax.WithStatement: + result = generateStatement(node); + break; + case Syntax.AssignmentExpression: + case Syntax.ArrayExpression: + case Syntax.ArrayPattern: + case Syntax.BinaryExpression: + case Syntax.CallExpression: + case Syntax.ConditionalExpression: + case Syntax.FunctionExpression: + case Syntax.Identifier: + case Syntax.Literal: + case Syntax.LogicalExpression: + case Syntax.MemberExpression: + case Syntax.NewExpression: + case Syntax.ObjectExpression: + case Syntax.ObjectPattern: + case Syntax.Property: + case Syntax.SequenceExpression: + case Syntax.ThisExpression: + case Syntax.UnaryExpression: + case Syntax.UpdateExpression: + case Syntax.YieldExpression: + result = generateExpression(node, { + precedence: Precedence.Sequence, + allowIn: true, + allowCall: true + }); + break; + default: + throw new Error('Unknown node type: ' + node.type); + } + if (!sourceMap) { + return result.toString(); + } + pair = result.toStringWithSourceMap({ + file: options.file, + sourceRoot: options.sourceMapRoot + }); + if (options.sourceContent) { + pair.map.setSourceContent(options.sourceMap, options.sourceContent); + } + if (options.sourceMapWithCode) { + return pair; + } + return pair.map.toString(); + } + FORMAT_MINIFY = { + indent: { + style: '', + base: 0 + }, + renumber: true, + hexadecimal: true, + quotes: 'auto', + escapeless: true, + compact: true, + parentheses: false, + semicolons: false + }; + FORMAT_DEFAULTS = getDefaultOptions().format; + exports.version = require('/package.json', module).version; + exports.generate = generate; + exports.attachComments = estraverse.attachComments; + exports.browser = false; + exports.FORMAT_MINIFY = FORMAT_MINIFY; + exports.FORMAT_DEFAULTS = FORMAT_DEFAULTS; + }()); + }); + require.define('/package.json', function (module, exports, __dirname, __filename) { + module.exports = { + 'name': 'escodegen', + 'description': 'ECMAScript code generator', + 'homepage': 'http://github.com/Constellation/escodegen', + 'main': 'escodegen.js', + 'bin': { + 'esgenerate': './bin/esgenerate.js', + 'escodegen': './bin/escodegen.js' + }, + 'version': '1.1.0-dev', + 'engines': { 'node': '>=0.4.0' }, + 'maintainers': [{ + 'name': 'Yusuke Suzuki', + 'email': 'utatane.tea@gmail.com', + 'web': 'http://github.com/Constellation' + }], + 'repository': { + 'type': 'git', + 'url': 'http://github.com/Constellation/escodegen.git' + }, + 'dependencies': { + 'esprima': '~1.0.4', + 'estraverse': '~1.5.0', + 'esutils': '~1.0.0' + }, + 'optionalDependencies': { 'source-map': '~0.1.30' }, + 'devDependencies': { + 'esprima-moz': '*', + 'commonjs-everywhere': '~0.8.0', + 'q': '*', + 'bower': '*', + 'semver': '*', + 'chai': '~1.7.2', + 'grunt-contrib-jshint': '~0.5.0', + 'grunt-cli': '~0.1.9', + 'grunt': '~0.4.1', + 'grunt-mocha-test': '~0.6.2' + }, + 'licenses': [{ + 'type': 'BSD', + 'url': 'http://github.com/Constellation/escodegen/raw/master/LICENSE.BSD' + }], + 'scripts': { + 'test': 'grunt travis', + 'unit-test': 'grunt test', + 'lint': 'grunt lint', + 'release': 'node tools/release.js', + 'build-min': './node_modules/.bin/cjsify -ma path: tools/entry-point.js > escodegen.browser.min.js', + 'build': './node_modules/.bin/cjsify -a path: tools/entry-point.js > escodegen.browser.js' + } + }; + }); + require.define('/node_modules/source-map/lib/source-map.js', function (module, exports, __dirname, __filename) { + exports.SourceMapGenerator = require('/node_modules/source-map/lib/source-map/source-map-generator.js', module).SourceMapGenerator; + exports.SourceMapConsumer = require('/node_modules/source-map/lib/source-map/source-map-consumer.js', module).SourceMapConsumer; + exports.SourceNode = require('/node_modules/source-map/lib/source-map/source-node.js', module).SourceNode; + }); + require.define('/node_modules/source-map/lib/source-map/source-node.js', function (module, exports, __dirname, __filename) { + if (typeof define !== 'function') { + var define = require('/node_modules/source-map/node_modules/amdefine/amdefine.js', module)(module, require); + } + define(function (require, exports, module) { + var SourceMapGenerator = require('/node_modules/source-map/lib/source-map/source-map-generator.js', module).SourceMapGenerator; + var util = require('/node_modules/source-map/lib/source-map/util.js', module); + function SourceNode(aLine, aColumn, aSource, aChunks, aName) { + this.children = []; + this.sourceContents = {}; + this.line = aLine === undefined ? null : aLine; + this.column = aColumn === undefined ? null : aColumn; + this.source = aSource === undefined ? null : aSource; + this.name = aName === undefined ? null : aName; + if (aChunks != null) + this.add(aChunks); + } + SourceNode.fromStringWithSourceMap = function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer) { + var node = new SourceNode; + var remainingLines = aGeneratedCode.split('\n'); + var lastGeneratedLine = 1, lastGeneratedColumn = 0; + var lastMapping = null; + aSourceMapConsumer.eachMapping(function (mapping) { + if (lastMapping === null) { + while (lastGeneratedLine < mapping.generatedLine) { + node.add(remainingLines.shift() + '\n'); + lastGeneratedLine++; + } + if (lastGeneratedColumn < mapping.generatedColumn) { + var nextLine = remainingLines[0]; + node.add(nextLine.substr(0, mapping.generatedColumn)); + remainingLines[0] = nextLine.substr(mapping.generatedColumn); + lastGeneratedColumn = mapping.generatedColumn; + } + } else { + if (lastGeneratedLine < mapping.generatedLine) { + var code = ''; + do { + code += remainingLines.shift() + '\n'; + lastGeneratedLine++; + lastGeneratedColumn = 0; + } while (lastGeneratedLine < mapping.generatedLine); + if (lastGeneratedColumn < mapping.generatedColumn) { + var nextLine = remainingLines[0]; + code += nextLine.substr(0, mapping.generatedColumn); + remainingLines[0] = nextLine.substr(mapping.generatedColumn); + lastGeneratedColumn = mapping.generatedColumn; + } + addMappingWithCode(lastMapping, code); + } else { + var nextLine = remainingLines[0]; + var code = nextLine.substr(0, mapping.generatedColumn - lastGeneratedColumn); + remainingLines[0] = nextLine.substr(mapping.generatedColumn - lastGeneratedColumn); + lastGeneratedColumn = mapping.generatedColumn; + addMappingWithCode(lastMapping, code); + } + } + lastMapping = mapping; + }, this); + addMappingWithCode(lastMapping, remainingLines.join('\n')); + aSourceMapConsumer.sources.forEach(function (sourceFile) { + var content = aSourceMapConsumer.sourceContentFor(sourceFile); + if (content) { + node.setSourceContent(sourceFile, content); + } + }); + return node; + function addMappingWithCode(mapping, code) { + if (mapping === null || mapping.source === undefined) { + node.add(code); + } else { + node.add(new SourceNode(mapping.originalLine, mapping.originalColumn, mapping.source, code, mapping.name)); + } + } + }; + SourceNode.prototype.add = function SourceNode_add(aChunk) { + if (Array.isArray(aChunk)) { + aChunk.forEach(function (chunk) { + this.add(chunk); + }, this); + } else if (aChunk instanceof SourceNode || typeof aChunk === 'string') { + if (aChunk) { + this.children.push(aChunk); + } + } else { + throw new TypeError('Expected a SourceNode, string, or an array of SourceNodes and strings. Got ' + aChunk); + } + return this; + }; + SourceNode.prototype.prepend = function SourceNode_prepend(aChunk) { + if (Array.isArray(aChunk)) { + for (var i = aChunk.length - 1; i >= 0; i--) { + this.prepend(aChunk[i]); + } + } else if (aChunk instanceof SourceNode || typeof aChunk === 'string') { + this.children.unshift(aChunk); + } else { + throw new TypeError('Expected a SourceNode, string, or an array of SourceNodes and strings. Got ' + aChunk); + } + return this; + }; + SourceNode.prototype.walk = function SourceNode_walk(aFn) { + var chunk; + for (var i = 0, len = this.children.length; i < len; i++) { + chunk = this.children[i]; + if (chunk instanceof SourceNode) { + chunk.walk(aFn); + } else { + if (chunk !== '') { + aFn(chunk, { + source: this.source, + line: this.line, + column: this.column, + name: this.name + }); + } + } + } + }; + SourceNode.prototype.join = function SourceNode_join(aSep) { + var newChildren; + var i; + var len = this.children.length; + if (len > 0) { + newChildren = []; + for (i = 0; i < len - 1; i++) { + newChildren.push(this.children[i]); + newChildren.push(aSep); + } + newChildren.push(this.children[i]); + this.children = newChildren; + } + return this; + }; + SourceNode.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) { + var lastChild = this.children[this.children.length - 1]; + if (lastChild instanceof SourceNode) { + lastChild.replaceRight(aPattern, aReplacement); + } else if (typeof lastChild === 'string') { + this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement); + } else { + this.children.push(''.replace(aPattern, aReplacement)); + } + return this; + }; + SourceNode.prototype.setSourceContent = function SourceNode_setSourceContent(aSourceFile, aSourceContent) { + this.sourceContents[util.toSetString(aSourceFile)] = aSourceContent; + }; + SourceNode.prototype.walkSourceContents = function SourceNode_walkSourceContents(aFn) { + for (var i = 0, len = this.children.length; i < len; i++) { + if (this.children[i] instanceof SourceNode) { + this.children[i].walkSourceContents(aFn); + } + } + var sources = Object.keys(this.sourceContents); + for (var i = 0, len = sources.length; i < len; i++) { + aFn(util.fromSetString(sources[i]), this.sourceContents[sources[i]]); + } + }; + SourceNode.prototype.toString = function SourceNode_toString() { + var str = ''; + this.walk(function (chunk) { + str += chunk; + }); + return str; + }; + SourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) { + var generated = { + code: '', + line: 1, + column: 0 + }; + var map = new SourceMapGenerator(aArgs); + var sourceMappingActive = false; + var lastOriginalSource = null; + var lastOriginalLine = null; + var lastOriginalColumn = null; + var lastOriginalName = null; + this.walk(function (chunk, original) { + generated.code += chunk; + if (original.source !== null && original.line !== null && original.column !== null) { + if (lastOriginalSource !== original.source || lastOriginalLine !== original.line || lastOriginalColumn !== original.column || lastOriginalName !== original.name) { + map.addMapping({ + source: original.source, + original: { + line: original.line, + column: original.column + }, + generated: { + line: generated.line, + column: generated.column + }, + name: original.name + }); + } + lastOriginalSource = original.source; + lastOriginalLine = original.line; + lastOriginalColumn = original.column; + lastOriginalName = original.name; + sourceMappingActive = true; + } else if (sourceMappingActive) { + map.addMapping({ + generated: { + line: generated.line, + column: generated.column + } + }); + lastOriginalSource = null; + sourceMappingActive = false; + } + chunk.split('').forEach(function (ch) { + if (ch === '\n') { + generated.line++; + generated.column = 0; + } else { + generated.column++; + } + }); + }); + this.walkSourceContents(function (sourceFile, sourceContent) { + map.setSourceContent(sourceFile, sourceContent); + }); + return { + code: generated.code, + map: map + }; + }; + exports.SourceNode = SourceNode; + }); + }); + require.define('/node_modules/source-map/lib/source-map/util.js', function (module, exports, __dirname, __filename) { + if (typeof define !== 'function') { + var define = require('/node_modules/source-map/node_modules/amdefine/amdefine.js', module)(module, require); + } + define(function (require, exports, module) { + function getArg(aArgs, aName, aDefaultValue) { + if (aName in aArgs) { + return aArgs[aName]; + } else if (arguments.length === 3) { + return aDefaultValue; + } else { + throw new Error('"' + aName + '" is a required argument.'); + } + } + exports.getArg = getArg; + var urlRegexp = /([\w+\-.]+):\/\/((\w+:\w+)@)?([\w.]+)?(:(\d+))?(\S+)?/; + var dataUrlRegexp = /^data:.+\,.+/; + function urlParse(aUrl) { + var match = aUrl.match(urlRegexp); + if (!match) { + return null; + } + return { + scheme: match[1], + auth: match[3], + host: match[4], + port: match[6], + path: match[7] + }; + } + exports.urlParse = urlParse; + function urlGenerate(aParsedUrl) { + var url = aParsedUrl.scheme + '://'; + if (aParsedUrl.auth) { + url += aParsedUrl.auth + '@'; + } + if (aParsedUrl.host) { + url += aParsedUrl.host; + } + if (aParsedUrl.port) { + url += ':' + aParsedUrl.port; + } + if (aParsedUrl.path) { + url += aParsedUrl.path; + } + return url; + } + exports.urlGenerate = urlGenerate; + function join(aRoot, aPath) { + var url; + if (aPath.match(urlRegexp) || aPath.match(dataUrlRegexp)) { + return aPath; + } + if (aPath.charAt(0) === '/' && (url = urlParse(aRoot))) { + url.path = aPath; + return urlGenerate(url); + } + return aRoot.replace(/\/$/, '') + '/' + aPath; + } + exports.join = join; + function toSetString(aStr) { + return '$' + aStr; + } + exports.toSetString = toSetString; + function fromSetString(aStr) { + return aStr.substr(1); + } + exports.fromSetString = fromSetString; + function relative(aRoot, aPath) { + aRoot = aRoot.replace(/\/$/, ''); + var url = urlParse(aRoot); + if (aPath.charAt(0) == '/' && url && url.path == '/') { + return aPath.slice(1); + } + return aPath.indexOf(aRoot + '/') === 0 ? aPath.substr(aRoot.length + 1) : aPath; + } + exports.relative = relative; + function strcmp(aStr1, aStr2) { + var s1 = aStr1 || ''; + var s2 = aStr2 || ''; + return (s1 > s2) - (s1 < s2); + } + function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) { + var cmp; + cmp = strcmp(mappingA.source, mappingB.source); + if (cmp) { + return cmp; + } + cmp = mappingA.originalLine - mappingB.originalLine; + if (cmp) { + return cmp; + } + cmp = mappingA.originalColumn - mappingB.originalColumn; + if (cmp || onlyCompareOriginal) { + return cmp; + } + cmp = strcmp(mappingA.name, mappingB.name); + if (cmp) { + return cmp; + } + cmp = mappingA.generatedLine - mappingB.generatedLine; + if (cmp) { + return cmp; + } + return mappingA.generatedColumn - mappingB.generatedColumn; + } + ; + exports.compareByOriginalPositions = compareByOriginalPositions; + function compareByGeneratedPositions(mappingA, mappingB, onlyCompareGenerated) { + var cmp; + cmp = mappingA.generatedLine - mappingB.generatedLine; + if (cmp) { + return cmp; + } + cmp = mappingA.generatedColumn - mappingB.generatedColumn; + if (cmp || onlyCompareGenerated) { + return cmp; + } + cmp = strcmp(mappingA.source, mappingB.source); + if (cmp) { + return cmp; + } + cmp = mappingA.originalLine - mappingB.originalLine; + if (cmp) { + return cmp; + } + cmp = mappingA.originalColumn - mappingB.originalColumn; + if (cmp) { + return cmp; + } + return strcmp(mappingA.name, mappingB.name); + } + ; + exports.compareByGeneratedPositions = compareByGeneratedPositions; + }); + }); + require.define('/node_modules/source-map/node_modules/amdefine/amdefine.js', function (module, exports, __dirname, __filename) { + 'use strict'; + function amdefine(module, requireFn) { + 'use strict'; + var defineCache = {}, loaderCache = {}, alreadyCalled = false, path = require('path', module), makeRequire, stringRequire; + 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] === '..')) { + break; + } else if (i > 0) { + ary.splice(i - 1, 2); + i -= 2; + } + } + } + } + function normalize(name, baseName) { + var baseParts; + if (name && name.charAt(0) === '.') { + if (baseName) { + baseParts = baseName.split('/'); + baseParts = baseParts.slice(0, baseParts.length - 1); + baseParts = baseParts.concat(name.split('/')); + trimDots(baseParts); + name = baseParts.join('/'); + } + } + return name; + } + function makeNormalize(relName) { + return function (name) { + return normalize(name, relName); + }; + } + function makeLoad(id) { + function load(value) { + loaderCache[id] = value; + } + load.fromText = function (id, text) { + 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') { + return stringRequire(systemRequire, exports, module, deps, relId); + } else { + deps = deps.map(function (depName) { + return stringRequire(systemRequire, exports, module, depName, relId); + }); + 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; + }; + 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 { + if (alreadyCalled) { + throw new Error('amdefine with no module ID cannot be called more than once per file.'); + } + alreadyCalled = true; + e = module.exports; + m = module; + r = makeRequire(requireFn, e, m, module.id); + } + if (deps) { + deps = deps.map(function (depName) { + return r(depName); + }); + } + 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) { + var index = id.indexOf('!'), originalId = id, prefix, plugin; + if (index === -1) { + id = normalize(id, relId); + 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 { + 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 { + id = normalize(id, relId); + } + if (loaderCache[id]) { + return loaderCache[id]; + } else { + plugin.load(id, makeRequire(systemRequire, exports, module, relId), makeLoad(id), {}); + return loaderCache[id]; + } + } + }; + 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' + ]; + } + if (id) { + defineCache[id] = [ + id, + deps, + factory + ]; + } else { + runFactory(id, deps, factory); + } + } + 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; + }); + require.define('/node_modules/source-map/lib/source-map/source-map-generator.js', function (module, exports, __dirname, __filename) { + if (typeof define !== 'function') { + var define = require('/node_modules/source-map/node_modules/amdefine/amdefine.js', module)(module, require); + } + define(function (require, exports, module) { + var base64VLQ = require('/node_modules/source-map/lib/source-map/base64-vlq.js', module); + var util = require('/node_modules/source-map/lib/source-map/util.js', module); + var ArraySet = require('/node_modules/source-map/lib/source-map/array-set.js', module).ArraySet; + function SourceMapGenerator(aArgs) { + this._file = util.getArg(aArgs, 'file'); + this._sourceRoot = util.getArg(aArgs, 'sourceRoot', null); + this._sources = new ArraySet; + this._names = new ArraySet; + this._mappings = []; + this._sourcesContents = null; + } + SourceMapGenerator.prototype._version = 3; + SourceMapGenerator.fromSourceMap = function SourceMapGenerator_fromSourceMap(aSourceMapConsumer) { + var sourceRoot = aSourceMapConsumer.sourceRoot; + var generator = new SourceMapGenerator({ + file: aSourceMapConsumer.file, + sourceRoot: sourceRoot + }); + aSourceMapConsumer.eachMapping(function (mapping) { + var newMapping = { + generated: { + line: mapping.generatedLine, + column: mapping.generatedColumn + } + }; + if (mapping.source) { + newMapping.source = mapping.source; + if (sourceRoot) { + newMapping.source = util.relative(sourceRoot, newMapping.source); + } + newMapping.original = { + line: mapping.originalLine, + column: mapping.originalColumn + }; + if (mapping.name) { + newMapping.name = mapping.name; + } + } + generator.addMapping(newMapping); + }); + aSourceMapConsumer.sources.forEach(function (sourceFile) { + var content = aSourceMapConsumer.sourceContentFor(sourceFile); + if (content) { + generator.setSourceContent(sourceFile, content); + } + }); + return generator; + }; + SourceMapGenerator.prototype.addMapping = function SourceMapGenerator_addMapping(aArgs) { + var generated = util.getArg(aArgs, 'generated'); + var original = util.getArg(aArgs, 'original', null); + var source = util.getArg(aArgs, 'source', null); + var name = util.getArg(aArgs, 'name', null); + this._validateMapping(generated, original, source, name); + if (source && !this._sources.has(source)) { + this._sources.add(source); + } + if (name && !this._names.has(name)) { + this._names.add(name); + } + this._mappings.push({ + generatedLine: generated.line, + generatedColumn: generated.column, + originalLine: original != null && original.line, + originalColumn: original != null && original.column, + source: source, + name: name + }); + }; + SourceMapGenerator.prototype.setSourceContent = function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) { + var source = aSourceFile; + if (this._sourceRoot) { + source = util.relative(this._sourceRoot, source); + } + if (aSourceContent !== null) { + if (!this._sourcesContents) { + this._sourcesContents = {}; + } + this._sourcesContents[util.toSetString(source)] = aSourceContent; + } else { + delete this._sourcesContents[util.toSetString(source)]; + if (Object.keys(this._sourcesContents).length === 0) { + this._sourcesContents = null; + } + } + }; + SourceMapGenerator.prototype.applySourceMap = function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile) { + if (!aSourceFile) { + aSourceFile = aSourceMapConsumer.file; + } + var sourceRoot = this._sourceRoot; + if (sourceRoot) { + aSourceFile = util.relative(sourceRoot, aSourceFile); + } + var newSources = new ArraySet; + var newNames = new ArraySet; + this._mappings.forEach(function (mapping) { + if (mapping.source === aSourceFile && mapping.originalLine) { + var original = aSourceMapConsumer.originalPositionFor({ + line: mapping.originalLine, + column: mapping.originalColumn + }); + if (original.source !== null) { + if (sourceRoot) { + mapping.source = util.relative(sourceRoot, original.source); + } else { + mapping.source = original.source; + } + mapping.originalLine = original.line; + mapping.originalColumn = original.column; + if (original.name !== null && mapping.name !== null) { + mapping.name = original.name; + } + } + } + var source = mapping.source; + if (source && !newSources.has(source)) { + newSources.add(source); + } + var name = mapping.name; + if (name && !newNames.has(name)) { + newNames.add(name); + } + }, this); + this._sources = newSources; + this._names = newNames; + aSourceMapConsumer.sources.forEach(function (sourceFile) { + var content = aSourceMapConsumer.sourceContentFor(sourceFile); + if (content) { + if (sourceRoot) { + sourceFile = util.relative(sourceRoot, sourceFile); + } + this.setSourceContent(sourceFile, content); + } + }, this); + }; + SourceMapGenerator.prototype._validateMapping = function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource, aName) { + if (aGenerated && 'line' in aGenerated && 'column' in aGenerated && aGenerated.line > 0 && aGenerated.column >= 0 && !aOriginal && !aSource && !aName) { + return; + } else if (aGenerated && 'line' in aGenerated && 'column' in aGenerated && aOriginal && 'line' in aOriginal && 'column' in aOriginal && aGenerated.line > 0 && aGenerated.column >= 0 && aOriginal.line > 0 && aOriginal.column >= 0 && aSource) { + return; + } else { + throw new Error('Invalid mapping: ' + JSON.stringify({ + generated: aGenerated, + source: aSource, + orginal: aOriginal, + name: aName + })); + } + }; + SourceMapGenerator.prototype._serializeMappings = function SourceMapGenerator_serializeMappings() { + var previousGeneratedColumn = 0; + var previousGeneratedLine = 1; + var previousOriginalColumn = 0; + var previousOriginalLine = 0; + var previousName = 0; + var previousSource = 0; + var result = ''; + var mapping; + this._mappings.sort(util.compareByGeneratedPositions); + for (var i = 0, len = this._mappings.length; i < len; i++) { + mapping = this._mappings[i]; + if (mapping.generatedLine !== previousGeneratedLine) { + previousGeneratedColumn = 0; + while (mapping.generatedLine !== previousGeneratedLine) { + result += ';'; + previousGeneratedLine++; + } + } else { + if (i > 0) { + if (!util.compareByGeneratedPositions(mapping, this._mappings[i - 1])) { + continue; + } + result += ','; + } + } + result += base64VLQ.encode(mapping.generatedColumn - previousGeneratedColumn); + previousGeneratedColumn = mapping.generatedColumn; + if (mapping.source) { + result += base64VLQ.encode(this._sources.indexOf(mapping.source) - previousSource); + previousSource = this._sources.indexOf(mapping.source); + result += base64VLQ.encode(mapping.originalLine - 1 - previousOriginalLine); + previousOriginalLine = mapping.originalLine - 1; + result += base64VLQ.encode(mapping.originalColumn - previousOriginalColumn); + previousOriginalColumn = mapping.originalColumn; + if (mapping.name) { + result += base64VLQ.encode(this._names.indexOf(mapping.name) - previousName); + previousName = this._names.indexOf(mapping.name); + } + } + } + return result; + }; + SourceMapGenerator.prototype._generateSourcesContent = function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) { + return aSources.map(function (source) { + if (!this._sourcesContents) { + return null; + } + if (aSourceRoot) { + source = util.relative(aSourceRoot, source); + } + var key = util.toSetString(source); + return Object.prototype.hasOwnProperty.call(this._sourcesContents, key) ? this._sourcesContents[key] : null; + }, this); + }; + SourceMapGenerator.prototype.toJSON = function SourceMapGenerator_toJSON() { + var map = { + version: this._version, + file: this._file, + sources: this._sources.toArray(), + names: this._names.toArray(), + mappings: this._serializeMappings() + }; + if (this._sourceRoot) { + map.sourceRoot = this._sourceRoot; + } + if (this._sourcesContents) { + map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot); + } + return map; + }; + SourceMapGenerator.prototype.toString = function SourceMapGenerator_toString() { + return JSON.stringify(this); + }; + exports.SourceMapGenerator = SourceMapGenerator; + }); + }); + require.define('/node_modules/source-map/lib/source-map/array-set.js', function (module, exports, __dirname, __filename) { + if (typeof define !== 'function') { + var define = require('/node_modules/source-map/node_modules/amdefine/amdefine.js', module)(module, require); + } + define(function (require, exports, module) { + var util = require('/node_modules/source-map/lib/source-map/util.js', module); + function ArraySet() { + this._array = []; + this._set = {}; + } + ArraySet.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) { + var set = new ArraySet; + for (var i = 0, len = aArray.length; i < len; i++) { + set.add(aArray[i], aAllowDuplicates); + } + return set; + }; + ArraySet.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) { + var isDuplicate = this.has(aStr); + var idx = this._array.length; + if (!isDuplicate || aAllowDuplicates) { + this._array.push(aStr); + } + if (!isDuplicate) { + this._set[util.toSetString(aStr)] = idx; + } + }; + ArraySet.prototype.has = function ArraySet_has(aStr) { + return Object.prototype.hasOwnProperty.call(this._set, util.toSetString(aStr)); + }; + ArraySet.prototype.indexOf = function ArraySet_indexOf(aStr) { + if (this.has(aStr)) { + return this._set[util.toSetString(aStr)]; + } + throw new Error('"' + aStr + '" is not in the set.'); + }; + ArraySet.prototype.at = function ArraySet_at(aIdx) { + if (aIdx >= 0 && aIdx < this._array.length) { + return this._array[aIdx]; + } + throw new Error('No element indexed by ' + aIdx); + }; + ArraySet.prototype.toArray = function ArraySet_toArray() { + return this._array.slice(); + }; + exports.ArraySet = ArraySet; + }); + }); + require.define('/node_modules/source-map/lib/source-map/base64-vlq.js', function (module, exports, __dirname, __filename) { + if (typeof define !== 'function') { + var define = require('/node_modules/source-map/node_modules/amdefine/amdefine.js', module)(module, require); + } + define(function (require, exports, module) { + var base64 = require('/node_modules/source-map/lib/source-map/base64.js', module); + var VLQ_BASE_SHIFT = 5; + var VLQ_BASE = 1 << VLQ_BASE_SHIFT; + var VLQ_BASE_MASK = VLQ_BASE - 1; + var VLQ_CONTINUATION_BIT = VLQ_BASE; + function toVLQSigned(aValue) { + return aValue < 0 ? (-aValue << 1) + 1 : (aValue << 1) + 0; + } + function fromVLQSigned(aValue) { + var isNegative = (aValue & 1) === 1; + var shifted = aValue >> 1; + return isNegative ? -shifted : shifted; + } + exports.encode = function base64VLQ_encode(aValue) { + var encoded = ''; + var digit; + var vlq = toVLQSigned(aValue); + do { + digit = vlq & VLQ_BASE_MASK; + vlq >>>= VLQ_BASE_SHIFT; + if (vlq > 0) { + digit |= VLQ_CONTINUATION_BIT; + } + encoded += base64.encode(digit); + } while (vlq > 0); + return encoded; + }; + exports.decode = function base64VLQ_decode(aStr) { + var i = 0; + var strLen = aStr.length; + var result = 0; + var shift = 0; + var continuation, digit; + do { + if (i >= strLen) { + throw new Error('Expected more digits in base 64 VLQ value.'); + } + digit = base64.decode(aStr.charAt(i++)); + continuation = !!(digit & VLQ_CONTINUATION_BIT); + digit &= VLQ_BASE_MASK; + result = result + (digit << shift); + shift += VLQ_BASE_SHIFT; + } while (continuation); + return { + value: fromVLQSigned(result), + rest: aStr.slice(i) + }; + }; + }); + }); + require.define('/node_modules/source-map/lib/source-map/base64.js', function (module, exports, __dirname, __filename) { + if (typeof define !== 'function') { + var define = require('/node_modules/source-map/node_modules/amdefine/amdefine.js', module)(module, require); + } + define(function (require, exports, module) { + var charToIntMap = {}; + var intToCharMap = {}; + 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split('').forEach(function (ch, index) { + charToIntMap[ch] = index; + intToCharMap[index] = ch; + }); + exports.encode = function base64_encode(aNumber) { + if (aNumber in intToCharMap) { + return intToCharMap[aNumber]; + } + throw new TypeError('Must be between 0 and 63: ' + aNumber); + }; + exports.decode = function base64_decode(aChar) { + if (aChar in charToIntMap) { + return charToIntMap[aChar]; + } + throw new TypeError('Not a valid base 64 digit: ' + aChar); + }; + }); + }); + require.define('/node_modules/source-map/lib/source-map/source-map-consumer.js', function (module, exports, __dirname, __filename) { + if (typeof define !== 'function') { + var define = require('/node_modules/source-map/node_modules/amdefine/amdefine.js', module)(module, require); + } + define(function (require, exports, module) { + var util = require('/node_modules/source-map/lib/source-map/util.js', module); + var binarySearch = require('/node_modules/source-map/lib/source-map/binary-search.js', module); + var ArraySet = require('/node_modules/source-map/lib/source-map/array-set.js', module).ArraySet; + var base64VLQ = require('/node_modules/source-map/lib/source-map/base64-vlq.js', module); + function SourceMapConsumer(aSourceMap) { + var sourceMap = aSourceMap; + if (typeof aSourceMap === 'string') { + sourceMap = JSON.parse(aSourceMap.replace(/^\)\]\}'/, '')); + } + var version = util.getArg(sourceMap, 'version'); + var sources = util.getArg(sourceMap, 'sources'); + var names = util.getArg(sourceMap, 'names', []); + var sourceRoot = util.getArg(sourceMap, 'sourceRoot', null); + var sourcesContent = util.getArg(sourceMap, 'sourcesContent', null); + var mappings = util.getArg(sourceMap, 'mappings'); + var file = util.getArg(sourceMap, 'file', null); + if (version != this._version) { + throw new Error('Unsupported version: ' + version); + } + this._names = ArraySet.fromArray(names, true); + this._sources = ArraySet.fromArray(sources, true); + this.sourceRoot = sourceRoot; + this.sourcesContent = sourcesContent; + this._mappings = mappings; + this.file = file; + } + SourceMapConsumer.fromSourceMap = function SourceMapConsumer_fromSourceMap(aSourceMap) { + var smc = Object.create(SourceMapConsumer.prototype); + smc._names = ArraySet.fromArray(aSourceMap._names.toArray(), true); + smc._sources = ArraySet.fromArray(aSourceMap._sources.toArray(), true); + smc.sourceRoot = aSourceMap._sourceRoot; + smc.sourcesContent = aSourceMap._generateSourcesContent(smc._sources.toArray(), smc.sourceRoot); + smc.file = aSourceMap._file; + smc.__generatedMappings = aSourceMap._mappings.slice().sort(util.compareByGeneratedPositions); + smc.__originalMappings = aSourceMap._mappings.slice().sort(util.compareByOriginalPositions); + return smc; + }; + SourceMapConsumer.prototype._version = 3; + Object.defineProperty(SourceMapConsumer.prototype, 'sources', { + get: function () { + return this._sources.toArray().map(function (s) { + return this.sourceRoot ? util.join(this.sourceRoot, s) : s; + }, this); + } + }); + SourceMapConsumer.prototype.__generatedMappings = null; + Object.defineProperty(SourceMapConsumer.prototype, '_generatedMappings', { + get: function () { + if (!this.__generatedMappings) { + this.__generatedMappings = []; + this.__originalMappings = []; + this._parseMappings(this._mappings, this.sourceRoot); + } + return this.__generatedMappings; + } + }); + SourceMapConsumer.prototype.__originalMappings = null; + Object.defineProperty(SourceMapConsumer.prototype, '_originalMappings', { + get: function () { + if (!this.__originalMappings) { + this.__generatedMappings = []; + this.__originalMappings = []; + this._parseMappings(this._mappings, this.sourceRoot); + } + return this.__originalMappings; + } + }); + SourceMapConsumer.prototype._parseMappings = function SourceMapConsumer_parseMappings(aStr, aSourceRoot) { + var generatedLine = 1; + var previousGeneratedColumn = 0; + var previousOriginalLine = 0; + var previousOriginalColumn = 0; + var previousSource = 0; + var previousName = 0; + var mappingSeparator = /^[,;]/; + var str = aStr; + var mapping; + var temp; + while (str.length > 0) { + if (str.charAt(0) === ';') { + generatedLine++; + str = str.slice(1); + previousGeneratedColumn = 0; + } else if (str.charAt(0) === ',') { + str = str.slice(1); + } else { + mapping = {}; + mapping.generatedLine = generatedLine; + temp = base64VLQ.decode(str); + mapping.generatedColumn = previousGeneratedColumn + temp.value; + previousGeneratedColumn = mapping.generatedColumn; + str = temp.rest; + if (str.length > 0 && !mappingSeparator.test(str.charAt(0))) { + temp = base64VLQ.decode(str); + mapping.source = this._sources.at(previousSource + temp.value); + previousSource += temp.value; + str = temp.rest; + if (str.length === 0 || mappingSeparator.test(str.charAt(0))) { + throw new Error('Found a source, but no line and column'); + } + temp = base64VLQ.decode(str); + mapping.originalLine = previousOriginalLine + temp.value; + previousOriginalLine = mapping.originalLine; + mapping.originalLine += 1; + str = temp.rest; + if (str.length === 0 || mappingSeparator.test(str.charAt(0))) { + throw new Error('Found a source and line, but no column'); + } + temp = base64VLQ.decode(str); + mapping.originalColumn = previousOriginalColumn + temp.value; + previousOriginalColumn = mapping.originalColumn; + str = temp.rest; + if (str.length > 0 && !mappingSeparator.test(str.charAt(0))) { + temp = base64VLQ.decode(str); + mapping.name = this._names.at(previousName + temp.value); + previousName += temp.value; + str = temp.rest; + } + } + this.__generatedMappings.push(mapping); + if (typeof mapping.originalLine === 'number') { + this.__originalMappings.push(mapping); + } + } + } + this.__originalMappings.sort(util.compareByOriginalPositions); + }; + SourceMapConsumer.prototype._findMapping = function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName, aColumnName, aComparator) { + if (aNeedle[aLineName] <= 0) { + throw new TypeError('Line must be greater than or equal to 1, got ' + aNeedle[aLineName]); + } + if (aNeedle[aColumnName] < 0) { + throw new TypeError('Column must be greater than or equal to 0, got ' + aNeedle[aColumnName]); + } + return binarySearch.search(aNeedle, aMappings, aComparator); + }; + SourceMapConsumer.prototype.originalPositionFor = function SourceMapConsumer_originalPositionFor(aArgs) { + var needle = { + generatedLine: util.getArg(aArgs, 'line'), + generatedColumn: util.getArg(aArgs, 'column') + }; + var mapping = this._findMapping(needle, this._generatedMappings, 'generatedLine', 'generatedColumn', util.compareByGeneratedPositions); + if (mapping) { + var source = util.getArg(mapping, 'source', null); + if (source && this.sourceRoot) { + source = util.join(this.sourceRoot, source); + } + return { + source: source, + line: util.getArg(mapping, 'originalLine', null), + column: util.getArg(mapping, 'originalColumn', null), + name: util.getArg(mapping, 'name', null) + }; + } + return { + source: null, + line: null, + column: null, + name: null + }; + }; + SourceMapConsumer.prototype.sourceContentFor = function SourceMapConsumer_sourceContentFor(aSource) { + if (!this.sourcesContent) { + return null; + } + if (this.sourceRoot) { + aSource = util.relative(this.sourceRoot, aSource); + } + if (this._sources.has(aSource)) { + return this.sourcesContent[this._sources.indexOf(aSource)]; + } + var url; + if (this.sourceRoot && (url = util.urlParse(this.sourceRoot))) { + var fileUriAbsPath = aSource.replace(/^file:\/\//, ''); + if (url.scheme == 'file' && this._sources.has(fileUriAbsPath)) { + return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)]; + } + if ((!url.path || url.path == '/') && this._sources.has('/' + aSource)) { + return this.sourcesContent[this._sources.indexOf('/' + aSource)]; + } + } + throw new Error('"' + aSource + '" is not in the SourceMap.'); + }; + SourceMapConsumer.prototype.generatedPositionFor = function SourceMapConsumer_generatedPositionFor(aArgs) { + var needle = { + source: util.getArg(aArgs, 'source'), + originalLine: util.getArg(aArgs, 'line'), + originalColumn: util.getArg(aArgs, 'column') + }; + if (this.sourceRoot) { + needle.source = util.relative(this.sourceRoot, needle.source); + } + var mapping = this._findMapping(needle, this._originalMappings, 'originalLine', 'originalColumn', util.compareByOriginalPositions); + if (mapping) { + return { + line: util.getArg(mapping, 'generatedLine', null), + column: util.getArg(mapping, 'generatedColumn', null) + }; + } + return { + line: null, + column: null + }; + }; + SourceMapConsumer.GENERATED_ORDER = 1; + SourceMapConsumer.ORIGINAL_ORDER = 2; + SourceMapConsumer.prototype.eachMapping = function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) { + var context = aContext || null; + var order = aOrder || SourceMapConsumer.GENERATED_ORDER; + var mappings; + switch (order) { + case SourceMapConsumer.GENERATED_ORDER: + mappings = this._generatedMappings; + break; + case SourceMapConsumer.ORIGINAL_ORDER: + mappings = this._originalMappings; + break; + default: + throw new Error('Unknown order of iteration.'); + } + var sourceRoot = this.sourceRoot; + mappings.map(function (mapping) { + var source = mapping.source; + if (source && sourceRoot) { + source = util.join(sourceRoot, source); + } + return { + source: source, + generatedLine: mapping.generatedLine, + generatedColumn: mapping.generatedColumn, + originalLine: mapping.originalLine, + originalColumn: mapping.originalColumn, + name: mapping.name + }; + }).forEach(aCallback, context); + }; + exports.SourceMapConsumer = SourceMapConsumer; + }); + }); + require.define('/node_modules/source-map/lib/source-map/binary-search.js', function (module, exports, __dirname, __filename) { + if (typeof define !== 'function') { + var define = require('/node_modules/source-map/node_modules/amdefine/amdefine.js', module)(module, require); + } + define(function (require, exports, module) { + function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare) { + var mid = Math.floor((aHigh - aLow) / 2) + aLow; + var cmp = aCompare(aNeedle, aHaystack[mid], true); + if (cmp === 0) { + return aHaystack[mid]; + } else if (cmp > 0) { + if (aHigh - mid > 1) { + return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare); + } + return aHaystack[mid]; + } else { + if (mid - aLow > 1) { + return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare); + } + return aLow < 0 ? null : aHaystack[aLow]; + } + } + exports.search = function search(aNeedle, aHaystack, aCompare) { + return aHaystack.length > 0 ? recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack, aCompare) : null; + }; + }); + }); + require.define('/node_modules/esutils/lib/utils.js', function (module, exports, __dirname, __filename) { + (function () { + 'use strict'; + exports.code = require('/node_modules/esutils/lib/code.js', module); + exports.keyword = require('/node_modules/esutils/lib/keyword.js', module); + }()); + }); + require.define('/node_modules/esutils/lib/keyword.js', function (module, exports, __dirname, __filename) { + (function () { + 'use strict'; + var code = require('/node_modules/esutils/lib/code.js', module); + function isStrictModeReservedWordES6(id) { + switch (id) { + case 'implements': + case 'interface': + case 'package': + case 'private': + case 'protected': + case 'public': + case 'static': + case 'let': + return true; + default: + return false; + } + } + function isKeywordES5(id, strict) { + if (!strict && id === 'yield') { + return false; + } + return isKeywordES6(id, strict); + } + function isKeywordES6(id, strict) { + if (strict && isStrictModeReservedWordES6(id)) { + return true; + } + switch (id.length) { + case 2: + return id === 'if' || id === 'in' || id === 'do'; + case 3: + return id === 'var' || id === 'for' || id === 'new' || id === 'try'; + case 4: + return id === 'this' || id === 'else' || id === 'case' || id === 'void' || id === 'with' || id === 'enum'; + case 5: + return id === 'while' || id === 'break' || id === 'catch' || id === 'throw' || id === 'const' || id === 'yield' || id === 'class' || id === 'super'; + case 6: + return id === 'return' || id === 'typeof' || id === 'delete' || id === 'switch' || id === 'export' || id === 'import'; + case 7: + return id === 'default' || id === 'finally' || id === 'extends'; + case 8: + return id === 'function' || id === 'continue' || id === 'debugger'; + case 10: + return id === 'instanceof'; + default: + return false; + } + } + function isRestrictedWord(id) { + return id === 'eval' || id === 'arguments'; + } + function isIdentifierName(id) { + var i, iz, ch; + if (id.length === 0) { + return false; + } + ch = id.charCodeAt(0); + if (!code.isIdentifierStart(ch) || ch === 92) { + return false; + } + for (i = 1, iz = id.length; i < iz; ++i) { + ch = id.charCodeAt(i); + if (!code.isIdentifierPart(ch) || ch === 92) { + return false; + } + } + return true; + } + module.exports = { + isKeywordES5: isKeywordES5, + isKeywordES6: isKeywordES6, + isRestrictedWord: isRestrictedWord, + isIdentifierName: isIdentifierName + }; + }()); + }); + require.define('/node_modules/esutils/lib/code.js', function (module, exports, __dirname, __filename) { + (function () { + 'use strict'; + var Regex; + Regex = { + NonAsciiIdentifierStart: new RegExp('[\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u0527\u0531-\u0556\u0559\u0561-\u0587\u05d0-\u05ea\u05f0-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u08a0\u08a2-\u08ac\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0977\u0979-\u097f\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c33\u0c35-\u0c39\u0c3d\u0c58\u0c59\u0c60\u0c61\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d05-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d60\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e87\u0e88\u0e8a\u0e8d\u0e94-\u0e97\u0e99-\u0e9f\u0ea1-\u0ea3\u0ea5\u0ea7\u0eaa\u0eab\u0ead-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f4\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f0\u1700-\u170c\u170e-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1877\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191c\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19c1-\u19c7\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4b\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1ce9-\u1cec\u1cee-\u1cf1\u1cf5\u1cf6\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2119-\u211d\u2124\u2126\u2128\u212a-\u212d\u212f-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u2e2f\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309d-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312d\u3131-\u318e\u31a0-\u31ba\u31f0-\u31ff\u3400-\u4db5\u4e00-\u9fcc\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua697\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua78e\ua790-\ua793\ua7a0-\ua7aa\ua7f8-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa80-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uabc0-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc]'), + NonAsciiIdentifierPart: new RegExp('[\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0300-\u0374\u0376\u0377\u037a-\u037d\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u0483-\u0487\u048a-\u0527\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u05d0-\u05ea\u05f0-\u05f2\u0610-\u061a\u0620-\u0669\u066e-\u06d3\u06d5-\u06dc\u06df-\u06e8\u06ea-\u06fc\u06ff\u0710-\u074a\u074d-\u07b1\u07c0-\u07f5\u07fa\u0800-\u082d\u0840-\u085b\u08a0\u08a2-\u08ac\u08e4-\u08fe\u0900-\u0963\u0966-\u096f\u0971-\u0977\u0979-\u097f\u0981-\u0983\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bc-\u09c4\u09c7\u09c8\u09cb-\u09ce\u09d7\u09dc\u09dd\u09df-\u09e3\u09e6-\u09f1\u0a01-\u0a03\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a59-\u0a5c\u0a5e\u0a66-\u0a75\u0a81-\u0a83\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abc-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ad0\u0ae0-\u0ae3\u0ae6-\u0aef\u0b01-\u0b03\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3c-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b56\u0b57\u0b5c\u0b5d\u0b5f-\u0b63\u0b66-\u0b6f\u0b71\u0b82\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd0\u0bd7\u0be6-\u0bef\u0c01-\u0c03\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c33\u0c35-\u0c39\u0c3d-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c58\u0c59\u0c60-\u0c63\u0c66-\u0c6f\u0c82\u0c83\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbc-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0cde\u0ce0-\u0ce3\u0ce6-\u0cef\u0cf1\u0cf2\u0d02\u0d03\u0d05-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d-\u0d44\u0d46-\u0d48\u0d4a-\u0d4e\u0d57\u0d60-\u0d63\u0d66-\u0d6f\u0d7a-\u0d7f\u0d82\u0d83\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0df2\u0df3\u0e01-\u0e3a\u0e40-\u0e4e\u0e50-\u0e59\u0e81\u0e82\u0e84\u0e87\u0e88\u0e8a\u0e8d\u0e94-\u0e97\u0e99-\u0e9f\u0ea1-\u0ea3\u0ea5\u0ea7\u0eaa\u0eab\u0ead-\u0eb9\u0ebb-\u0ebd\u0ec0-\u0ec4\u0ec6\u0ec8-\u0ecd\u0ed0-\u0ed9\u0edc-\u0edf\u0f00\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f3e-\u0f47\u0f49-\u0f6c\u0f71-\u0f84\u0f86-\u0f97\u0f99-\u0fbc\u0fc6\u1000-\u1049\u1050-\u109d\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u135d-\u135f\u1380-\u138f\u13a0-\u13f4\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f0\u1700-\u170c\u170e-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176c\u176e-\u1770\u1772\u1773\u1780-\u17d3\u17d7\u17dc\u17dd\u17e0-\u17e9\u180b-\u180d\u1810-\u1819\u1820-\u1877\u1880-\u18aa\u18b0-\u18f5\u1900-\u191c\u1920-\u192b\u1930-\u193b\u1946-\u196d\u1970-\u1974\u1980-\u19ab\u19b0-\u19c9\u19d0-\u19d9\u1a00-\u1a1b\u1a20-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1aa7\u1b00-\u1b4b\u1b50-\u1b59\u1b6b-\u1b73\u1b80-\u1bf3\u1c00-\u1c37\u1c40-\u1c49\u1c4d-\u1c7d\u1cd0-\u1cd2\u1cd4-\u1cf6\u1d00-\u1de6\u1dfc-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u200c\u200d\u203f\u2040\u2054\u2071\u207f\u2090-\u209c\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2102\u2107\u210a-\u2113\u2115\u2119-\u211d\u2124\u2126\u2128\u212a-\u212d\u212f-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d7f-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u2de0-\u2dff\u2e2f\u3005-\u3007\u3021-\u302f\u3031-\u3035\u3038-\u303c\u3041-\u3096\u3099\u309a\u309d-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312d\u3131-\u318e\u31a0-\u31ba\u31f0-\u31ff\u3400-\u4db5\u4e00-\u9fcc\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua62b\ua640-\ua66f\ua674-\ua67d\ua67f-\ua697\ua69f-\ua6f1\ua717-\ua71f\ua722-\ua788\ua78b-\ua78e\ua790-\ua793\ua7a0-\ua7aa\ua7f8-\ua827\ua840-\ua873\ua880-\ua8c4\ua8d0-\ua8d9\ua8e0-\ua8f7\ua8fb\ua900-\ua92d\ua930-\ua953\ua960-\ua97c\ua980-\ua9c0\ua9cf-\ua9d9\uaa00-\uaa36\uaa40-\uaa4d\uaa50-\uaa59\uaa60-\uaa76\uaa7a\uaa7b\uaa80-\uaac2\uaadb-\uaadd\uaae0-\uaaef\uaaf2-\uaaf6\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uabc0-\uabea\uabec\uabed\uabf0-\uabf9\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe00-\ufe0f\ufe20-\ufe26\ufe33\ufe34\ufe4d-\ufe4f\ufe70-\ufe74\ufe76-\ufefc\uff10-\uff19\uff21-\uff3a\uff3f\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc]') + }; + function isDecimalDigit(ch) { + return ch >= 48 && ch <= 57; + } + function isHexDigit(ch) { + return isDecimalDigit(ch) || 97 <= ch && ch <= 102 || 65 <= ch && ch <= 70; + } + function isOctalDigit(ch) { + return ch >= 48 && ch <= 55; + } + function isWhiteSpace(ch) { + return ch === 32 || ch === 9 || ch === 11 || ch === 12 || ch === 160 || ch >= 5760 && [ + 5760, + 6158, + 8192, + 8193, + 8194, + 8195, + 8196, + 8197, + 8198, + 8199, + 8200, + 8201, + 8202, + 8239, + 8287, + 12288, + 65279 + ].indexOf(ch) >= 0; + } + function isLineTerminator(ch) { + return ch === 10 || ch === 13 || ch === 8232 || ch === 8233; + } + function isIdentifierStart(ch) { + return ch === 36 || ch === 95 || ch >= 65 && ch <= 90 || ch >= 97 && ch <= 122 || ch === 92 || ch >= 128 && Regex.NonAsciiIdentifierStart.test(String.fromCharCode(ch)); + } + function isIdentifierPart(ch) { + return ch === 36 || ch === 95 || ch >= 65 && ch <= 90 || ch >= 97 && ch <= 122 || ch >= 48 && ch <= 57 || ch === 92 || ch >= 128 && Regex.NonAsciiIdentifierPart.test(String.fromCharCode(ch)); + } + module.exports = { + isDecimalDigit: isDecimalDigit, + isHexDigit: isHexDigit, + isOctalDigit: isOctalDigit, + isWhiteSpace: isWhiteSpace, + isLineTerminator: isLineTerminator, + isIdentifierStart: isIdentifierStart, + isIdentifierPart: isIdentifierPart + }; + }()); + }); + require.define('/node_modules/estraverse/estraverse.js', function (module, exports, __dirname, __filename) { + (function (root, factory) { + 'use strict'; + if (typeof define === 'function' && define.amd) { + define(['exports'], factory); + } else if (typeof exports !== 'undefined') { + factory(exports); + } else { + factory(root.estraverse = {}); + } + }(this, function (exports) { + 'use strict'; + var Syntax, isArray, VisitorOption, VisitorKeys, BREAK, SKIP; + Syntax = { + AssignmentExpression: 'AssignmentExpression', + ArrayExpression: 'ArrayExpression', + ArrayPattern: 'ArrayPattern', + ArrowFunctionExpression: 'ArrowFunctionExpression', + BlockStatement: 'BlockStatement', + BinaryExpression: 'BinaryExpression', + BreakStatement: 'BreakStatement', + CallExpression: 'CallExpression', + CatchClause: 'CatchClause', + ClassBody: 'ClassBody', + ClassDeclaration: 'ClassDeclaration', + ClassExpression: 'ClassExpression', + ConditionalExpression: 'ConditionalExpression', + ContinueStatement: 'ContinueStatement', + DebuggerStatement: 'DebuggerStatement', + DirectiveStatement: 'DirectiveStatement', + DoWhileStatement: 'DoWhileStatement', + EmptyStatement: 'EmptyStatement', + ExpressionStatement: 'ExpressionStatement', + ForStatement: 'ForStatement', + ForInStatement: 'ForInStatement', + FunctionDeclaration: 'FunctionDeclaration', + FunctionExpression: 'FunctionExpression', + Identifier: 'Identifier', + IfStatement: 'IfStatement', + Literal: 'Literal', + LabeledStatement: 'LabeledStatement', + LogicalExpression: 'LogicalExpression', + MemberExpression: 'MemberExpression', + MethodDefinition: 'MethodDefinition', + NewExpression: 'NewExpression', + ObjectExpression: 'ObjectExpression', + ObjectPattern: 'ObjectPattern', + Program: 'Program', + Property: 'Property', + ReturnStatement: 'ReturnStatement', + SequenceExpression: 'SequenceExpression', + SwitchStatement: 'SwitchStatement', + SwitchCase: 'SwitchCase', + ThisExpression: 'ThisExpression', + ThrowStatement: 'ThrowStatement', + TryStatement: 'TryStatement', + UnaryExpression: 'UnaryExpression', + UpdateExpression: 'UpdateExpression', + VariableDeclaration: 'VariableDeclaration', + VariableDeclarator: 'VariableDeclarator', + WhileStatement: 'WhileStatement', + WithStatement: 'WithStatement', + YieldExpression: 'YieldExpression' + }; + function ignoreJSHintError() { + } + isArray = Array.isArray; + if (!isArray) { + isArray = function isArray(array) { + return Object.prototype.toString.call(array) === '[object Array]'; + }; + } + function deepCopy(obj) { + var ret = {}, key, val; + for (key in obj) { + if (obj.hasOwnProperty(key)) { + val = obj[key]; + if (typeof val === 'object' && val !== null) { + ret[key] = deepCopy(val); + } else { + ret[key] = val; + } + } + } + return ret; + } + function shallowCopy(obj) { + var ret = {}, key; + for (key in obj) { + if (obj.hasOwnProperty(key)) { + ret[key] = obj[key]; + } + } + return ret; + } + ignoreJSHintError(shallowCopy); + function upperBound(array, func) { + var diff, len, i, current; + len = array.length; + i = 0; + while (len) { + diff = len >>> 1; + current = i + diff; + if (func(array[current])) { + len = diff; + } else { + i = current + 1; + len -= diff + 1; + } + } + return i; + } + function lowerBound(array, func) { + var diff, len, i, current; + len = array.length; + i = 0; + while (len) { + diff = len >>> 1; + current = i + diff; + if (func(array[current])) { + i = current + 1; + len -= diff + 1; + } else { + len = diff; + } + } + return i; + } + ignoreJSHintError(lowerBound); + VisitorKeys = { + AssignmentExpression: [ + 'left', + 'right' + ], + ArrayExpression: ['elements'], + ArrayPattern: ['elements'], + ArrowFunctionExpression: [ + 'params', + 'defaults', + 'rest', + 'body' + ], + BlockStatement: ['body'], + BinaryExpression: [ + 'left', + 'right' + ], + BreakStatement: ['label'], + CallExpression: [ + 'callee', + 'arguments' + ], + CatchClause: [ + 'param', + 'body' + ], + ClassBody: ['body'], + ClassDeclaration: [ + 'id', + 'body', + 'superClass' + ], + ClassExpression: [ + 'id', + 'body', + 'superClass' + ], + ConditionalExpression: [ + 'test', + 'consequent', + 'alternate' + ], + ContinueStatement: ['label'], + DebuggerStatement: [], + DirectiveStatement: [], + DoWhileStatement: [ + 'body', + 'test' + ], + EmptyStatement: [], + ExpressionStatement: ['expression'], + ForStatement: [ + 'init', + 'test', + 'update', + 'body' + ], + ForInStatement: [ + 'left', + 'right', + 'body' + ], + FunctionDeclaration: [ + 'id', + 'params', + 'defaults', + 'rest', + 'body' + ], + FunctionExpression: [ + 'id', + 'params', + 'defaults', + 'rest', + 'body' + ], + Identifier: [], + IfStatement: [ + 'test', + 'consequent', + 'alternate' + ], + Literal: [], + LabeledStatement: [ + 'label', + 'body' + ], + LogicalExpression: [ + 'left', + 'right' + ], + MemberExpression: [ + 'object', + 'property' + ], + MethodDefinition: [ + 'key', + 'value' + ], + NewExpression: [ + 'callee', + 'arguments' + ], + ObjectExpression: ['properties'], + ObjectPattern: ['properties'], + Program: ['body'], + Property: [ + 'key', + 'value' + ], + ReturnStatement: ['argument'], + SequenceExpression: ['expressions'], + SwitchStatement: [ + 'discriminant', + 'cases' + ], + SwitchCase: [ + 'test', + 'consequent' + ], + ThisExpression: [], + ThrowStatement: ['argument'], + TryStatement: [ + 'block', + 'handlers', + 'handler', + 'guardedHandlers', + 'finalizer' + ], + UnaryExpression: ['argument'], + UpdateExpression: ['argument'], + VariableDeclaration: ['declarations'], + VariableDeclarator: [ + 'id', + 'init' + ], + WhileStatement: [ + 'test', + 'body' + ], + WithStatement: [ + 'object', + 'body' + ], + YieldExpression: ['argument'] + }; + BREAK = {}; + SKIP = {}; + VisitorOption = { + Break: BREAK, + Skip: SKIP + }; + function Reference(parent, key) { + this.parent = parent; + this.key = key; + } + Reference.prototype.replace = function replace(node) { + this.parent[this.key] = node; + }; + function Element(node, path, wrap, ref) { + this.node = node; + this.path = path; + this.wrap = wrap; + this.ref = ref; + } + function Controller() { + } + Controller.prototype.path = function path() { + var i, iz, j, jz, result, element; + function addToPath(result, path) { + if (isArray(path)) { + for (j = 0, jz = path.length; j < jz; ++j) { + result.push(path[j]); + } + } else { + result.push(path); + } + } + if (!this.__current.path) { + return null; + } + result = []; + for (i = 2, iz = this.__leavelist.length; i < iz; ++i) { + element = this.__leavelist[i]; + addToPath(result, element.path); + } + addToPath(result, this.__current.path); + return result; + }; + Controller.prototype.parents = function parents() { + var i, iz, result; + result = []; + for (i = 1, iz = this.__leavelist.length; i < iz; ++i) { + result.push(this.__leavelist[i].node); + } + return result; + }; + Controller.prototype.current = function current() { + return this.__current.node; + }; + Controller.prototype.__execute = function __execute(callback, element) { + var previous, result; + result = undefined; + previous = this.__current; + this.__current = element; + this.__state = null; + if (callback) { + result = callback.call(this, element.node, this.__leavelist[this.__leavelist.length - 1].node); + } + this.__current = previous; + return result; + }; + Controller.prototype.notify = function notify(flag) { + this.__state = flag; + }; + Controller.prototype.skip = function () { + this.notify(SKIP); + }; + Controller.prototype['break'] = function () { + this.notify(BREAK); + }; + Controller.prototype.__initialize = function (root, visitor) { + this.visitor = visitor; + this.root = root; + this.__worklist = []; + this.__leavelist = []; + this.__current = null; + this.__state = null; + }; + Controller.prototype.traverse = function traverse(root, visitor) { + var worklist, leavelist, element, node, nodeType, ret, key, current, current2, candidates, candidate, sentinel; + this.__initialize(root, visitor); + sentinel = {}; + worklist = this.__worklist; + leavelist = this.__leavelist; + worklist.push(new Element(root, null, null, null)); + leavelist.push(new Element(null, null, null, null)); + while (worklist.length) { + element = worklist.pop(); + if (element === sentinel) { + element = leavelist.pop(); + ret = this.__execute(visitor.leave, element); + if (this.__state === BREAK || ret === BREAK) { + return; + } + continue; + } + if (element.node) { + ret = this.__execute(visitor.enter, element); + if (this.__state === BREAK || ret === BREAK) { + return; + } + worklist.push(sentinel); + leavelist.push(element); + if (this.__state === SKIP || ret === SKIP) { + continue; + } + node = element.node; + nodeType = element.wrap || node.type; + candidates = VisitorKeys[nodeType]; + current = candidates.length; + while ((current -= 1) >= 0) { + key = candidates[current]; + candidate = node[key]; + if (!candidate) { + continue; + } + if (!isArray(candidate)) { + worklist.push(new Element(candidate, key, null, null)); + continue; + } + current2 = candidate.length; + while ((current2 -= 1) >= 0) { + if (!candidate[current2]) { + continue; + } + if ((nodeType === Syntax.ObjectExpression || nodeType === Syntax.ObjectPattern) && 'properties' === candidates[current]) { + element = new Element(candidate[current2], [ + key, + current2 + ], 'Property', null); + } else { + element = new Element(candidate[current2], [ + key, + current2 + ], null, null); + } + worklist.push(element); + } + } + } + } + }; + Controller.prototype.replace = function replace(root, visitor) { + var worklist, leavelist, node, nodeType, target, element, current, current2, candidates, candidate, sentinel, outer, key; + this.__initialize(root, visitor); + sentinel = {}; + worklist = this.__worklist; + leavelist = this.__leavelist; + outer = { root: root }; + element = new Element(root, null, null, new Reference(outer, 'root')); + worklist.push(element); + leavelist.push(element); + while (worklist.length) { + element = worklist.pop(); + if (element === sentinel) { + element = leavelist.pop(); + target = this.__execute(visitor.leave, element); + if (target !== undefined && target !== BREAK && target !== SKIP) { + element.ref.replace(target); + } + if (this.__state === BREAK || target === BREAK) { + return outer.root; + } + continue; + } + target = this.__execute(visitor.enter, element); + if (target !== undefined && target !== BREAK && target !== SKIP) { + element.ref.replace(target); + element.node = target; + } + if (this.__state === BREAK || target === BREAK) { + return outer.root; + } + node = element.node; + if (!node) { + continue; + } + worklist.push(sentinel); + leavelist.push(element); + if (this.__state === SKIP || target === SKIP) { + continue; + } + nodeType = element.wrap || node.type; + candidates = VisitorKeys[nodeType]; + current = candidates.length; + while ((current -= 1) >= 0) { + key = candidates[current]; + candidate = node[key]; + if (!candidate) { + continue; + } + if (!isArray(candidate)) { + worklist.push(new Element(candidate, key, null, new Reference(node, key))); + continue; + } + current2 = candidate.length; + while ((current2 -= 1) >= 0) { + if (!candidate[current2]) { + continue; + } + if (nodeType === Syntax.ObjectExpression && 'properties' === candidates[current]) { + element = new Element(candidate[current2], [ + key, + current2 + ], 'Property', new Reference(candidate, current2)); + } else { + element = new Element(candidate[current2], [ + key, + current2 + ], null, new Reference(candidate, current2)); + } + worklist.push(element); + } + } + } + return outer.root; + }; + function traverse(root, visitor) { + var controller = new Controller; + return controller.traverse(root, visitor); + } + function replace(root, visitor) { + var controller = new Controller; + return controller.replace(root, visitor); + } + function extendCommentRange(comment, tokens) { + var target; + target = upperBound(tokens, function search(token) { + return token.range[0] > comment.range[0]; + }); + comment.extendedRange = [ + comment.range[0], + comment.range[1] + ]; + if (target !== tokens.length) { + comment.extendedRange[1] = tokens[target].range[0]; + } + target -= 1; + if (target >= 0) { + comment.extendedRange[0] = tokens[target].range[1]; + } + return comment; + } + function attachComments(tree, providedComments, tokens) { + var comments = [], comment, len, i, cursor; + if (!tree.range) { + throw new Error('attachComments needs range information'); + } + if (!tokens.length) { + if (providedComments.length) { + for (i = 0, len = providedComments.length; i < len; i += 1) { + comment = deepCopy(providedComments[i]); + comment.extendedRange = [ + 0, + tree.range[0] + ]; + comments.push(comment); + } + tree.leadingComments = comments; + } + return tree; + } + for (i = 0, len = providedComments.length; i < len; i += 1) { + comments.push(extendCommentRange(deepCopy(providedComments[i]), tokens)); + } + cursor = 0; + traverse(tree, { + enter: function (node) { + var comment; + while (cursor < comments.length) { + comment = comments[cursor]; + if (comment.extendedRange[1] > node.range[0]) { + break; + } + if (comment.extendedRange[1] === node.range[0]) { + if (!node.leadingComments) { + node.leadingComments = []; + } + node.leadingComments.push(comment); + comments.splice(cursor, 1); + } else { + cursor += 1; + } + } + if (cursor === comments.length) { + return VisitorOption.Break; + } + if (comments[cursor].extendedRange[0] > node.range[1]) { + return VisitorOption.Skip; + } + } + }); + cursor = 0; + traverse(tree, { + leave: function (node) { + var comment; + while (cursor < comments.length) { + comment = comments[cursor]; + if (node.range[1] < comment.extendedRange[0]) { + break; + } + if (node.range[1] === comment.extendedRange[0]) { + if (!node.trailingComments) { + node.trailingComments = []; + } + node.trailingComments.push(comment); + comments.splice(cursor, 1); + } else { + cursor += 1; + } + } + if (cursor === comments.length) { + return VisitorOption.Break; + } + if (comments[cursor].extendedRange[0] > node.range[1]) { + return VisitorOption.Skip; + } + } + }); + return tree; + } + exports.version = '1.3.3-dev'; + exports.Syntax = Syntax; + exports.traverse = traverse; + exports.replace = replace; + exports.attachComments = attachComments; + exports.VisitorKeys = VisitorKeys; + exports.VisitorOption = VisitorOption; + exports.Controller = Controller; + })); + }); + require('/tools/entry-point.js'); +}.call(this, this)); diff --git a/editor/scripts/escope.js b/editor/scripts/escope.js new file mode 100644 index 0000000..cdf917b --- /dev/null +++ b/editor/scripts/escope.js @@ -0,0 +1,1117 @@ +/* + Copyright (C) 2012-2013 Yusuke Suzuki + Copyright (C) 2013 Alex Seville + + 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. + + 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 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. +*/ + +/** + * Escope (escope) is an ECMAScript + * scope analyzer extracted from the esmangle project. + *

+ * escope finds lexical scopes in a source program, i.e. areas of that + * program where different occurrences of the same identifier refer to the same + * variable. With each scope the contained variables are collected, and each + * identifier reference in code is linked to its corresponding variable (if + * possible). + *

+ * escope works on a syntax tree of the parsed source code which has + * to adhere to the + * Mozilla Parser API. E.g. esprima is a parser + * that produces such syntax trees. + *

+ * The main interface is the {@link analyze} function. + * @module + */ + +/*jslint bitwise:true */ +/*global exports:true, define:true, require:true*/ +(function (factory, global) { + 'use strict'; + + function namespace(str, obj) { + var i, iz, names, name; + names = str.split('.'); + for (i = 0, iz = names.length; i < iz; ++i) { + name = names[i]; + if (obj.hasOwnProperty(name)) { + obj = obj[name]; + } else { + obj = (obj[name] = {}); + } + } + return obj; + } + + // Universal Module Definition (UMD) to support AMD, CommonJS/Node.js, + // and plain browser loading, + if (typeof define === 'function' && define.amd) { + define('escope', ['exports', 'estraverse'], function (exports, estraverse) { + factory(exports, global, estraverse); + }); + } else if (typeof exports !== 'undefined') { + factory(exports, global, require('estraverse')); + } else { + factory(namespace('escope', global), global, global.estraverse); + } +}(function (exports, global, estraverse) { + 'use strict'; + + var Syntax, + Map, + currentScope, + globalScope, + scopes, + options; + + Syntax = estraverse.Syntax; + + if (typeof global.Map !== 'undefined') { + // ES6 Map + Map = global.Map; + } else { + Map = function Map() { + this.__data = {}; + }; + + Map.prototype.get = function MapGet(key) { + key = '$' + key; + if (this.__data.hasOwnProperty(key)) { + return this.__data[key]; + } + return undefined; + }; + + Map.prototype.has = function MapHas(key) { + key = '$' + key; + return this.__data.hasOwnProperty(key); + }; + + Map.prototype.set = function MapSet(key, val) { + key = '$' + key; + this.__data[key] = val; + }; + + Map.prototype['delete'] = function MapDelete(key) { + key = '$' + key; + return delete this.__data[key]; + }; + } + + function assert(cond, text) { + if (!cond) { + throw new Error(text); + } + } + + function defaultOptions() { + return { + optimistic: false, + directive: false + }; + } + + function updateDeeply(target, override) { + var key, val; + + function isHashObject(target) { + return typeof target === 'object' && target instanceof Object && !(target instanceof RegExp); + } + + for (key in override) { + if (override.hasOwnProperty(key)) { + val = override[key]; + if (isHashObject(val)) { + if (isHashObject(target[key])) { + updateDeeply(target[key], val); + } else { + target[key] = updateDeeply({}, val); + } + } else { + target[key] = val; + } + } + } + return target; + } + + /** + * A Reference represents a single occurrence of an identifier in code. + * @class Reference + */ + function Reference(ident, scope, flag, writeExpr, maybeImplicitGlobal) { + /** + * Identifier syntax node. + * @member {esprima#Identifier} Reference#identifier + */ + this.identifier = ident; + /** + * Reference to the enclosing Scope. + * @member {Scope} Reference#from + */ + this.from = scope; + /** + * Whether the reference comes from a dynamic scope (such as 'eval', + * 'with', etc.), and may be trapped by dynamic scopes. + * @member {boolean} Reference#tainted + */ + this.tainted = false; + /** + * The variable this reference is resolved with. + * @member {Variable} Reference#resolved + */ + this.resolved = null; + /** + * The read-write mode of the reference. (Value is one of {@link + * Reference.READ}, {@link Reference.RW}, {@link Reference.WRITE}). + * @member {number} Reference#flag + * @private + */ + this.flag = flag; + if (this.isWrite()) { + /** + * If reference is writeable, this is the tree being written to it. + * @member {esprima#Node} Reference#writeExpr + */ + this.writeExpr = writeExpr; + } + /** + * Whether the Reference might refer to a global variable. + * @member {boolean} Reference#__maybeImplicitGlobal + * @private + */ + this.__maybeImplicitGlobal = maybeImplicitGlobal; + } + + /** + * @constant Reference.READ + * @private + */ + Reference.READ = 0x1; + /** + * @constant Reference.WRITE + * @private + */ + Reference.WRITE = 0x2; + /** + * @constant Reference.RW + * @private + */ + Reference.RW = 0x3; + + /** + * Whether the reference is static. + * @method Reference#isStatic + * @return {boolean} + */ + Reference.prototype.isStatic = function isStatic() { + return !this.tainted && this.resolved && this.resolved.scope.isStatic(); + }; + + /** + * Whether the reference is writeable. + * @method Reference#isWrite + * @return {boolean} + */ + Reference.prototype.isWrite = function isWrite() { + return this.flag & Reference.WRITE; + }; + + /** + * Whether the reference is readable. + * @method Reference#isRead + * @return {boolean} + */ + Reference.prototype.isRead = function isRead() { + return this.flag & Reference.READ; + }; + + /** + * Whether the reference is read-only. + * @method Reference#isReadOnly + * @return {boolean} + */ + Reference.prototype.isReadOnly = function isReadOnly() { + return this.flag === Reference.READ; + }; + + /** + * Whether the reference is write-only. + * @method Reference#isWriteOnly + * @return {boolean} + */ + Reference.prototype.isWriteOnly = function isWriteOnly() { + return this.flag === Reference.WRITE; + }; + + /** + * Whether the reference is read-write. + * @method Reference#isReadWrite + * @return {boolean} + */ + Reference.prototype.isReadWrite = function isReadWrite() { + return this.flag === Reference.RW; + }; + + /** + * A Variable represents a locally scoped identifier. These include arguments to + * functions. + * @class Variable + */ + function Variable(name, scope) { + /** + * The variable name, as given in the source code. + * @member {String} Variable#name + */ + this.name = name; + /** + * List of defining occurrences of this variable (like in 'var ...' + * statements or as parameter), as AST nodes. + * @member {esprima.Identifier[]} Variable#identifiers + */ + this.identifiers = []; + /** + * List of {@link Reference|references} of this variable (excluding parameter entries) + * in its defining scope and all nested scopes. For defining + * occurrences only see {@link Variable#defs}. + * @member {Reference[]} Variable#references + */ + this.references = []; + + /** + * List of defining occurrences of this variable (like in 'var ...' + * statements or as parameter), as custom objects. + * @typedef {Object} DefEntry + * @property {String} DefEntry.type - the type of the occurrence (e.g. + * "Parameter", "Variable", ...) + * @property {esprima.Identifier} DefEntry.name - the identifier AST node of the occurrence + * @property {esprima.Node} DefEntry.node - the enclosing node of the + * identifier + * @property {esprima.Node} [DefEntry.parent] - the enclosing statement + * node of the identifier + * @member {DefEntry[]} Variable#defs + */ + this.defs = []; + + this.tainted = false; + /** + * Whether this is a stack variable. + * @member {boolean} Variable#stack + */ + this.stack = true; + /** + * Reference to the enclosing Scope. + * @member {Scope} Variable#scope + */ + this.scope = scope; + } + + Variable.CatchClause = 'CatchClause'; + Variable.Parameter = 'Parameter'; + Variable.FunctionName = 'FunctionName'; + Variable.Variable = 'Variable'; + Variable.ImplicitGlobalVariable = 'ImplicitGlobalVariable'; + + function isStrictScope(scope, block) { + var body, i, iz, stmt, expr; + + // When upper scope is exists and strict, inner scope is also strict. + if (scope.upper && scope.upper.isStrict) { + return true; + } + + if (scope.type === 'function') { + body = block.body; + } else if (scope.type === 'global') { + body = block; + } else { + return false; + } + + if (options.directive) { + for (i = 0, iz = body.body.length; i < iz; ++i) { + stmt = body.body[i]; + if (stmt.type !== 'DirectiveStatement') { + break; + } + if (stmt.raw === '"use strict"' || stmt.raw === '\'use strict\'') { + return true; + } + } + } else { + for (i = 0, iz = body.body.length; i < iz; ++i) { + stmt = body.body[i]; + if (stmt.type !== Syntax.ExpressionStatement) { + break; + } + expr = stmt.expression; + if (expr.type !== Syntax.Literal || typeof expr.value !== 'string') { + break; + } + if (expr.raw != null) { + if (expr.raw === '"use strict"' || expr.raw === '\'use strict\'') { + return true; + } + } else { + if (expr.value === 'use strict') { + return true; + } + } + } + } + return false; + } + + /** + * @class Scope + */ + function Scope(block, opt) { + var variable, body; + + /** + * One of 'catch', 'with', 'function' or 'global'. + * @member {String} Scope#type + */ + this.type = + (block.type === Syntax.CatchClause) ? 'catch' : + (block.type === Syntax.WithStatement) ? 'with' : + (block.type === Syntax.Program) ? 'global' : 'function'; + /** + * The scoped {@link Variable}s of this scope, as { Variable.name + * : Variable }. + * @member {Map} Scope#set + */ + this.set = new Map(); + /** + * The tainted variables of this scope, as { Variable.name : + * boolean }. + * @member {Map} Scope#taints */ + this.taints = new Map(); + /** + * Generally, through the lexical scoping of JS you can always know + * which variable an identifier in the source code refers to. There are + * a few exceptions to this rule. With 'global' and 'with' scopes you + * can only decide at runtime which variable a reference refers to. + * Moreover, if 'eval()' is used in a scope, it might introduce new + * bindings in this or its prarent scopes. + * All those scopes are considered 'dynamic'. + * @member {boolean} Scope#dynamic + */ + this.dynamic = this.type === 'global' || this.type === 'with'; + /** + * A reference to the scope-defining syntax node. + * @member {esprima.Node} Scope#block + */ + this.block = block; + /** + * The {@link Reference|references} that are not resolved with this scope. + * @member {Reference[]} Scope#through + */ + this.through = []; + /** + * The scoped {@link Variable}s of this scope. In the case of a + * 'function' scope this includes the automatic argument arguments as + * its first element, as well as all further formal arguments. + * @member {Variable[]} Scope#variables + */ + this.variables = []; + /** + * Any variable {@link Reference|reference} found in this scope. This + * includes occurrences of local variables as well as variables from + * parent scopes (including the global scope). For local variables + * this also includes defining occurrences (like in a 'var' statement). + * In a 'function' scope this does not include the occurrences of the + * formal parameter in the parameter list. + * @member {Reference[]} Scope#references + */ + this.references = []; + /** + * List of {@link Reference}s that are left to be resolved (i.e. which + * need to be linked to the variable they refer to). Used internally to + * resolve bindings during scope analysis. On a finalized scope + * analysis, all sopes have left value null. + * @member {Reference[]} Scope#left + */ + this.left = []; + /** + * For 'global' and 'function' scopes, this is a self-reference. For + * other scope types this is the variableScope value of the + * parent scope. + * @member {Scope} Scope#variableScope + */ + this.variableScope = + (this.type === 'global' || this.type === 'function') ? this : currentScope.variableScope; + /** + * Whether this scope is created by a FunctionExpression. + * @member {boolean} Scope#functionExpressionScope + */ + this.functionExpressionScope = false; + /** + * Whether this is a scope that contains an 'eval()' invocation. + * @member {boolean} Scope#directCallToEvalScope + */ + this.directCallToEvalScope = false; + /** + * @member {boolean} Scope#thisFound + */ + this.thisFound = false; + body = this.type === 'function' ? block.body : block; + if (opt.naming) { + this.__define(block.id, { + type: Variable.FunctionName, + name: block.id, + node: block + }); + this.functionExpressionScope = true; + } else { + if (this.type === 'function') { + variable = new Variable('arguments', this); + this.taints.set('arguments', true); + this.set.set('arguments', variable); + this.variables.push(variable); + } + + if (block.type === Syntax.FunctionExpression && block.id) { + new Scope(block, { naming: true }); + } + } + + /** + * Reference to the parent {@link Scope|scope}. + * @member {Scope} Scope#upper + */ + this.upper = currentScope; + /** + * Whether 'use strict' is in effect in this scope. + * @member {boolean} Scope#isStrict + */ + this.isStrict = isStrictScope(this, block); + + /** + * List of nested {@link Scope}s. + * @member {Scope[]} Scope#childScopes + */ + this.childScopes = []; + if (currentScope) { + currentScope.childScopes.push(this); + } + + + // RAII + currentScope = this; + if (this.type === 'global') { + globalScope = this; + globalScope.implicit = { + set: new Map(), + variables: [] + }; + } + scopes.push(this); + } + + Scope.prototype.__close = function __close() { + var i, iz, ref, current, node, implicit; + + // Because if this is global environment, upper is null + if (!this.dynamic || options.optimistic) { + // static resolve + for (i = 0, iz = this.left.length; i < iz; ++i) { + ref = this.left[i]; + if (!this.__resolve(ref)) { + this.__delegateToUpperScope(ref); + } + } + } else { + // this is "global" / "with" / "function with eval" environment + if (this.type === 'with') { + for (i = 0, iz = this.left.length; i < iz; ++i) { + ref = this.left[i]; + ref.tainted = true; + this.__delegateToUpperScope(ref); + } + } else { + for (i = 0, iz = this.left.length; i < iz; ++i) { + // notify all names are through to global + ref = this.left[i]; + current = this; + do { + current.through.push(ref); + current = current.upper; + } while (current); + } + } + } + + if (this.type === 'global') { + implicit = []; + for (i = 0, iz = this.left.length; i < iz; ++i) { + ref = this.left[i]; + if (ref.__maybeImplicitGlobal && !this.set.has(ref.identifier.name)) { + implicit.push(ref.__maybeImplicitGlobal); + } + } + + // create an implicit global variable from assignment expression + for (i = 0, iz = implicit.length; i < iz; ++i) { + node = implicit[i]; + this.__defineImplicit(node.left, { + type: Variable.ImplicitGlobalVariable, + name: node.left, + node: node + }); + } + } + + this.left = null; + currentScope = this.upper; + }; + + Scope.prototype.__resolve = function __resolve(ref) { + var variable, name; + name = ref.identifier.name; + if (this.set.has(name)) { + variable = this.set.get(name); + variable.references.push(ref); + variable.stack = variable.stack && ref.from.variableScope === this.variableScope; + if (ref.tainted) { + variable.tainted = true; + this.taints.set(variable.name, true); + } + ref.resolved = variable; + return true; + } + return false; + }; + + Scope.prototype.__delegateToUpperScope = function __delegateToUpperScope(ref) { + if (this.upper) { + this.upper.left.push(ref); + } + this.through.push(ref); + }; + + Scope.prototype.__defineImplicit = function __defineImplicit(node, info) { + var name, variable; + if (node && node.type === Syntax.Identifier) { + name = node.name; + if (!this.implicit.set.has(name)) { + variable = new Variable(name, this); + variable.identifiers.push(node); + variable.defs.push(info); + this.implicit.set.set(name, variable); + this.implicit.variables.push(variable); + } else { + variable = this.implicit.set.get(name); + variable.identifiers.push(node); + variable.defs.push(info); + } + } + }; + + Scope.prototype.__define = function __define(node, info) { + var name, variable; + if (node && node.type === Syntax.Identifier) { + name = node.name; + if (!this.set.has(name)) { + variable = new Variable(name, this); + variable.identifiers.push(node); + variable.defs.push(info); + this.set.set(name, variable); + this.variables.push(variable); + } else { + variable = this.set.get(name); + variable.identifiers.push(node); + variable.defs.push(info); + } + } + }; + + Scope.prototype.__referencing = function __referencing(node, assign, writeExpr, maybeImplicitGlobal) { + var ref; + // because Array element may be null + if (node && node.type === Syntax.Identifier) { + ref = new Reference(node, this, assign || Reference.READ, writeExpr, maybeImplicitGlobal); + this.references.push(ref); + this.left.push(ref); + } + }; + + Scope.prototype.__detectEval = function __detectEval() { + var current; + current = this; + this.directCallToEvalScope = true; + do { + current.dynamic = true; + current = current.upper; + } while (current); + }; + + Scope.prototype.__detectThis = function __detectThis() { + this.thisFound = true; + }; + + Scope.prototype.__isClosed = function isClosed() { + return this.left === null; + }; + + // API Scope#resolve(name) + // returns resolved reference + Scope.prototype.resolve = function resolve(ident) { + var ref, i, iz; + assert(this.__isClosed(), 'scope should be closed'); + assert(ident.type === Syntax.Identifier, 'target should be identifier'); + for (i = 0, iz = this.references.length; i < iz; ++i) { + ref = this.references[i]; + if (ref.identifier === ident) { + return ref; + } + } + return null; + }; + + // API Scope#isStatic + // returns this scope is static + Scope.prototype.isStatic = function isStatic() { + return !this.dynamic; + }; + + // API Scope#isArgumentsMaterialized + // return this scope has materialized arguments + Scope.prototype.isArgumentsMaterialized = function isArgumentsMaterialized() { + // TODO(Constellation) + // We can more aggressive on this condition like this. + // + // function t() { + // // arguments of t is always hidden. + // function arguments() { + // } + // } + var variable; + + // This is not function scope + if (this.type !== 'function') { + return true; + } + + if (!this.isStatic()) { + return true; + } + + variable = this.set.get('arguments'); + assert(variable, 'always have arguments variable'); + return variable.tainted || variable.references.length !== 0; + }; + + // API Scope#isThisMaterialized + // return this scope has materialized `this` reference + Scope.prototype.isThisMaterialized = function isThisMaterialized() { + // This is not function scope + if (this.type !== 'function') { + return true; + } + if (!this.isStatic()) { + return true; + } + return this.thisFound; + }; + + Scope.mangledName = '__$escope$__'; + + Scope.prototype.attach = function attach() { + if (!this.functionExpressionScope) { + this.block[Scope.mangledName] = this; + } + }; + + Scope.prototype.detach = function detach() { + if (!this.functionExpressionScope) { + delete this.block[Scope.mangledName]; + } + }; + + Scope.prototype.isUsedName = function (name) { + if (this.set.has(name)) { + return true; + } + for (var i = 0, iz = this.through.length; i < iz; ++i) { + if (this.through[i].identifier.name === name) { + return true; + } + } + return false; + }; + + /** + * @class ScopeManager + */ + function ScopeManager(scopes) { + this.scopes = scopes; + this.attached = false; + } + + // Returns appropliate scope for this node + ScopeManager.prototype.__get = function __get(node) { + var i, iz, scope; + if (this.attached) { + return node[Scope.mangledName] || null; + } + if (Scope.isScopeRequired(node)) { + for (i = 0, iz = this.scopes.length; i < iz; ++i) { + scope = this.scopes[i]; + if (!scope.functionExpressionScope) { + if (scope.block === node) { + return scope; + } + } + } + } + return null; + }; + + ScopeManager.prototype.acquire = function acquire(node) { + return this.__get(node); + }; + + ScopeManager.prototype.release = function release(node) { + var scope = this.__get(node); + if (scope) { + scope = scope.upper; + while (scope) { + if (!scope.functionExpressionScope) { + return scope; + } + scope = scope.upper; + } + } + return null; + }; + + ScopeManager.prototype.attach = function attach() { + var i, iz; + for (i = 0, iz = this.scopes.length; i < iz; ++i) { + this.scopes[i].attach(); + } + this.attached = true; + }; + + ScopeManager.prototype.detach = function detach() { + var i, iz; + for (i = 0, iz = this.scopes.length; i < iz; ++i) { + this.scopes[i].detach(); + } + this.attached = false; + }; + + Scope.isScopeRequired = function isScopeRequired(node) { + return Scope.isVariableScopeRequired(node) || node.type === Syntax.WithStatement || node.type === Syntax.CatchClause; + }; + + Scope.isVariableScopeRequired = function isVariableScopeRequired(node) { + return node.type === Syntax.Program || node.type === Syntax.FunctionExpression || node.type === Syntax.FunctionDeclaration; + }; + + /** + * Main interface function. Takes an Esprima syntax tree and returns the + * analyzed scopes. + * @function analyze + * @param {esprima.Tree} tree + * @param {Object} providedOptions - Options that tailor the scope analysis + * @param {boolean} [providedOptions.optimistic=false] - the optimistic flag + * @param {boolean} [providedOptions.directive=false]- the directive flag + * @param {boolean} [providedOptions.ignoreEval=false]- whether to check 'eval()' calls + * @return {ScopeManager} + */ + function analyze(tree, providedOptions) { + var resultScopes; + + options = updateDeeply(defaultOptions(), providedOptions); + resultScopes = scopes = []; + currentScope = null; + globalScope = null; + + // attach scope and collect / resolve names + estraverse.traverse(tree, { + enter: function enter(node) { + var i, iz, decl; + if (Scope.isScopeRequired(node)) { + new Scope(node, {}); + } + + switch (node.type) { + case Syntax.AssignmentExpression: + if (node.operator === '=') { + currentScope.__referencing(node.left, Reference.WRITE, node.right, (!currentScope.isStrict && node.left.name != null) && node); + } else { + currentScope.__referencing(node.left, Reference.RW, node.right); + } + currentScope.__referencing(node.right); + break; + + case Syntax.ArrayExpression: + for (i = 0, iz = node.elements.length; i < iz; ++i) { + currentScope.__referencing(node.elements[i]); + } + break; + + case Syntax.BlockStatement: + break; + + case Syntax.BinaryExpression: + currentScope.__referencing(node.left); + currentScope.__referencing(node.right); + break; + + case Syntax.BreakStatement: + break; + + case Syntax.CallExpression: + currentScope.__referencing(node.callee); + for (i = 0, iz = node['arguments'].length; i < iz; ++i) { + currentScope.__referencing(node['arguments'][i]); + } + + // check this is direct call to eval + if (!options.ignoreEval && node.callee.type === Syntax.Identifier && node.callee.name === 'eval') { + currentScope.variableScope.__detectEval(); + } + break; + + case Syntax.CatchClause: + currentScope.__define(node.param, { + type: Variable.CatchClause, + name: node.param, + node: node + }); + break; + + case Syntax.ConditionalExpression: + currentScope.__referencing(node.test); + currentScope.__referencing(node.consequent); + currentScope.__referencing(node.alternate); + break; + + case Syntax.ContinueStatement: + break; + + case Syntax.DirectiveStatement: + break; + + case Syntax.DoWhileStatement: + currentScope.__referencing(node.test); + break; + + case Syntax.DebuggerStatement: + break; + + case Syntax.EmptyStatement: + break; + + case Syntax.ExpressionStatement: + currentScope.__referencing(node.expression); + break; + + case Syntax.ForStatement: + currentScope.__referencing(node.init); + currentScope.__referencing(node.test); + currentScope.__referencing(node.update); + break; + + case Syntax.ForInStatement: + if (node.left.type === Syntax.VariableDeclaration) { + currentScope.__referencing(node.left.declarations[0].id, Reference.WRITE, null, false); + } else { + currentScope.__referencing(node.left, Reference.WRITE, null, (!currentScope.isStrict && node.left.name != null) && node); + } + currentScope.__referencing(node.right); + break; + + case Syntax.FunctionDeclaration: + // FunctionDeclaration name is defined in upper scope + currentScope.upper.__define(node.id, { + type: Variable.FunctionName, + name: node.id, + node: node + }); + for (i = 0, iz = node.params.length; i < iz; ++i) { + currentScope.__define(node.params[i], { + type: Variable.Parameter, + name: node.params[i], + node: node, + index: i + }); + } + break; + + case Syntax.FunctionExpression: + // id is defined in upper scope + for (i = 0, iz = node.params.length; i < iz; ++i) { + currentScope.__define(node.params[i], { + type: Variable.Parameter, + name: node.params[i], + node: node, + index: i + }); + } + break; + + case Syntax.Identifier: + break; + + case Syntax.IfStatement: + currentScope.__referencing(node.test); + break; + + case Syntax.Literal: + break; + + case Syntax.LabeledStatement: + break; + + case Syntax.LogicalExpression: + currentScope.__referencing(node.left); + currentScope.__referencing(node.right); + break; + + case Syntax.MemberExpression: + currentScope.__referencing(node.object); + if (node.computed) { + currentScope.__referencing(node.property); + } + break; + + case Syntax.NewExpression: + currentScope.__referencing(node.callee); + for (i = 0, iz = node['arguments'].length; i < iz; ++i) { + currentScope.__referencing(node['arguments'][i]); + } + break; + + case Syntax.ObjectExpression: + break; + + case Syntax.Program: + break; + + case Syntax.Property: + currentScope.__referencing(node.value); + break; + + case Syntax.ReturnStatement: + currentScope.__referencing(node.argument); + break; + + case Syntax.SequenceExpression: + for (i = 0, iz = node.expressions.length; i < iz; ++i) { + currentScope.__referencing(node.expressions[i]); + } + break; + + case Syntax.SwitchStatement: + currentScope.__referencing(node.discriminant); + break; + + case Syntax.SwitchCase: + currentScope.__referencing(node.test); + break; + + case Syntax.ThisExpression: + currentScope.variableScope.__detectThis(); + break; + + case Syntax.ThrowStatement: + currentScope.__referencing(node.argument); + break; + + case Syntax.TryStatement: + break; + + case Syntax.UnaryExpression: + currentScope.__referencing(node.argument); + break; + + case Syntax.UpdateExpression: + currentScope.__referencing(node.argument, Reference.RW, null); + break; + + case Syntax.VariableDeclaration: + for (i = 0, iz = node.declarations.length; i < iz; ++i) { + decl = node.declarations[i]; + currentScope.variableScope.__define(decl.id, { + type: Variable.Variable, + name: decl.id, + node: decl, + index: i, + parent: node + }); + if (decl.init) { + // initializer is found + currentScope.__referencing(decl.id, Reference.WRITE, decl.init, false); + currentScope.__referencing(decl.init); + } + } + break; + + case Syntax.VariableDeclarator: + break; + + case Syntax.WhileStatement: + currentScope.__referencing(node.test); + break; + + case Syntax.WithStatement: + // WithStatement object is referenced at upper scope + currentScope.upper.__referencing(node.object); + break; + } + }, + + leave: function leave(node) { + while (currentScope && node === currentScope.block) { + currentScope.__close(); + } + } + }); + + assert(currentScope === null); + globalScope = null; + scopes = null; + options = null; + + return new ScopeManager(resultScopes); + } + + /** @name module:escope.version */ + exports.version = '1.0.1'; + /** @name module:escope.Reference */ + exports.Reference = Reference; + /** @name module:escope.Variable */ + exports.Variable = Variable; + /** @name module:escope.Scope */ + exports.Scope = Scope; + /** @name module:escope.ScopeManager */ + exports.ScopeManager = ScopeManager; + /** @name module:escope.analyze */ + exports.analyze = analyze; +}, this)); +/* vim: set sw=4 ts=4 et tw=80 : */ diff --git a/editor/scripts/estraverse.js b/editor/scripts/estraverse.js new file mode 100644 index 0000000..e8f65d2 --- /dev/null +++ b/editor/scripts/estraverse.js @@ -0,0 +1,688 @@ +/* + Copyright (C) 2012-2013 Yusuke Suzuki + Copyright (C) 2012 Ariya Hidayat + + 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. + + 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 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. +*/ +/*jslint vars:false, bitwise:true*/ +/*jshint indent:4*/ +/*global exports:true, define:true*/ +(function (root, factory) { + 'use strict'; + + // Universal Module Definition (UMD) to support AMD, CommonJS/Node.js, + // and plain browser loading, + if (typeof define === 'function' && define.amd) { + define(['exports'], factory); + } else if (typeof exports !== 'undefined') { + factory(exports); + } else { + factory((root.estraverse = {})); + } +}(this, function (exports) { + 'use strict'; + + var Syntax, + isArray, + VisitorOption, + VisitorKeys, + BREAK, + SKIP; + + Syntax = { + AssignmentExpression: 'AssignmentExpression', + ArrayExpression: 'ArrayExpression', + ArrayPattern: 'ArrayPattern', + ArrowFunctionExpression: 'ArrowFunctionExpression', + BlockStatement: 'BlockStatement', + BinaryExpression: 'BinaryExpression', + BreakStatement: 'BreakStatement', + CallExpression: 'CallExpression', + CatchClause: 'CatchClause', + ClassBody: 'ClassBody', + ClassDeclaration: 'ClassDeclaration', + ClassExpression: 'ClassExpression', + ConditionalExpression: 'ConditionalExpression', + ContinueStatement: 'ContinueStatement', + DebuggerStatement: 'DebuggerStatement', + DirectiveStatement: 'DirectiveStatement', + DoWhileStatement: 'DoWhileStatement', + EmptyStatement: 'EmptyStatement', + ExpressionStatement: 'ExpressionStatement', + ForStatement: 'ForStatement', + ForInStatement: 'ForInStatement', + FunctionDeclaration: 'FunctionDeclaration', + FunctionExpression: 'FunctionExpression', + Identifier: 'Identifier', + IfStatement: 'IfStatement', + Literal: 'Literal', + LabeledStatement: 'LabeledStatement', + LogicalExpression: 'LogicalExpression', + MemberExpression: 'MemberExpression', + MethodDefinition: 'MethodDefinition', + NewExpression: 'NewExpression', + ObjectExpression: 'ObjectExpression', + ObjectPattern: 'ObjectPattern', + Program: 'Program', + Property: 'Property', + ReturnStatement: 'ReturnStatement', + SequenceExpression: 'SequenceExpression', + SwitchStatement: 'SwitchStatement', + SwitchCase: 'SwitchCase', + ThisExpression: 'ThisExpression', + ThrowStatement: 'ThrowStatement', + TryStatement: 'TryStatement', + UnaryExpression: 'UnaryExpression', + UpdateExpression: 'UpdateExpression', + VariableDeclaration: 'VariableDeclaration', + VariableDeclarator: 'VariableDeclarator', + WhileStatement: 'WhileStatement', + WithStatement: 'WithStatement', + YieldExpression: 'YieldExpression' + }; + + function ignoreJSHintError() { } + + isArray = Array.isArray; + if (!isArray) { + isArray = function isArray(array) { + return Object.prototype.toString.call(array) === '[object Array]'; + }; + } + + function deepCopy(obj) { + var ret = {}, key, val; + for (key in obj) { + if (obj.hasOwnProperty(key)) { + val = obj[key]; + if (typeof val === 'object' && val !== null) { + ret[key] = deepCopy(val); + } else { + ret[key] = val; + } + } + } + return ret; + } + + function shallowCopy(obj) { + var ret = {}, key; + for (key in obj) { + if (obj.hasOwnProperty(key)) { + ret[key] = obj[key]; + } + } + return ret; + } + ignoreJSHintError(shallowCopy); + + // based on LLVM libc++ upper_bound / lower_bound + // MIT License + + function upperBound(array, func) { + var diff, len, i, current; + + len = array.length; + i = 0; + + while (len) { + diff = len >>> 1; + current = i + diff; + if (func(array[current])) { + len = diff; + } else { + i = current + 1; + len -= diff + 1; + } + } + return i; + } + + function lowerBound(array, func) { + var diff, len, i, current; + + len = array.length; + i = 0; + + while (len) { + diff = len >>> 1; + current = i + diff; + if (func(array[current])) { + i = current + 1; + len -= diff + 1; + } else { + len = diff; + } + } + return i; + } + ignoreJSHintError(lowerBound); + + VisitorKeys = { + AssignmentExpression: ['left', 'right'], + ArrayExpression: ['elements'], + ArrayPattern: ['elements'], + ArrowFunctionExpression: ['params', 'defaults', 'rest', 'body'], + BlockStatement: ['body'], + BinaryExpression: ['left', 'right'], + BreakStatement: ['label'], + CallExpression: ['callee', 'arguments'], + CatchClause: ['param', 'body'], + ClassBody: ['body'], + ClassDeclaration: ['id', 'body', 'superClass'], + ClassExpression: ['id', 'body', 'superClass'], + ConditionalExpression: ['test', 'consequent', 'alternate'], + ContinueStatement: ['label'], + DebuggerStatement: [], + DirectiveStatement: [], + DoWhileStatement: ['body', 'test'], + EmptyStatement: [], + ExpressionStatement: ['expression'], + ForStatement: ['init', 'test', 'update', 'body'], + ForInStatement: ['left', 'right', 'body'], + FunctionDeclaration: ['id', 'params', 'defaults', 'rest', 'body'], + FunctionExpression: ['id', 'params', 'defaults', 'rest', 'body'], + Identifier: [], + IfStatement: ['test', 'consequent', 'alternate'], + Literal: [], + LabeledStatement: ['label', 'body'], + LogicalExpression: ['left', 'right'], + MemberExpression: ['object', 'property'], + MethodDefinition: ['key', 'value'], + NewExpression: ['callee', 'arguments'], + ObjectExpression: ['properties'], + ObjectPattern: ['properties'], + Program: ['body'], + Property: ['key', 'value'], + ReturnStatement: ['argument'], + SequenceExpression: ['expressions'], + SwitchStatement: ['discriminant', 'cases'], + SwitchCase: ['test', 'consequent'], + ThisExpression: [], + ThrowStatement: ['argument'], + TryStatement: ['block', 'handlers', 'handler', 'guardedHandlers', 'finalizer'], + UnaryExpression: ['argument'], + UpdateExpression: ['argument'], + VariableDeclaration: ['declarations'], + VariableDeclarator: ['id', 'init'], + WhileStatement: ['test', 'body'], + WithStatement: ['object', 'body'], + YieldExpression: ['argument'] + }; + + // unique id + BREAK = {}; + SKIP = {}; + + VisitorOption = { + Break: BREAK, + Skip: SKIP + }; + + function Reference(parent, key) { + this.parent = parent; + this.key = key; + } + + Reference.prototype.replace = function replace(node) { + this.parent[this.key] = node; + }; + + function Element(node, path, wrap, ref) { + this.node = node; + this.path = path; + this.wrap = wrap; + this.ref = ref; + } + + function Controller() { } + + // API: + // return property path array from root to current node + Controller.prototype.path = function path() { + var i, iz, j, jz, result, element; + + function addToPath(result, path) { + if (isArray(path)) { + for (j = 0, jz = path.length; j < jz; ++j) { + result.push(path[j]); + } + } else { + result.push(path); + } + } + + // root node + if (!this.__current.path) { + return null; + } + + // first node is sentinel, second node is root element + result = []; + for (i = 2, iz = this.__leavelist.length; i < iz; ++i) { + element = this.__leavelist[i]; + addToPath(result, element.path); + } + addToPath(result, this.__current.path); + return result; + }; + + // API: + // return array of parent elements + Controller.prototype.parents = function parents() { + var i, iz, result; + + // first node is sentinel + result = []; + for (i = 1, iz = this.__leavelist.length; i < iz; ++i) { + result.push(this.__leavelist[i].node); + } + + return result; + }; + + // API: + // return current node + Controller.prototype.current = function current() { + return this.__current.node; + }; + + Controller.prototype.__execute = function __execute(callback, element) { + var previous, result; + + result = undefined; + + previous = this.__current; + this.__current = element; + this.__state = null; + if (callback) { + result = callback.call(this, element.node, this.__leavelist[this.__leavelist.length - 1].node); + } + this.__current = previous; + + return result; + }; + + // API: + // notify control skip / break + Controller.prototype.notify = function notify(flag) { + this.__state = flag; + }; + + // API: + // skip child nodes of current node + Controller.prototype.skip = function () { + this.notify(SKIP); + }; + + // API: + // break traversals + Controller.prototype['break'] = function () { + this.notify(BREAK); + }; + + Controller.prototype.__initialize = function(root, visitor) { + this.visitor = visitor; + this.root = root; + this.__worklist = []; + this.__leavelist = []; + this.__current = null; + this.__state = null; + }; + + Controller.prototype.traverse = function traverse(root, visitor) { + var worklist, + leavelist, + element, + node, + nodeType, + ret, + key, + current, + current2, + candidates, + candidate, + sentinel; + + this.__initialize(root, visitor); + + sentinel = {}; + + // reference + worklist = this.__worklist; + leavelist = this.__leavelist; + + // initialize + worklist.push(new Element(root, null, null, null)); + leavelist.push(new Element(null, null, null, null)); + + while (worklist.length) { + element = worklist.pop(); + + if (element === sentinel) { + element = leavelist.pop(); + + ret = this.__execute(visitor.leave, element); + + if (this.__state === BREAK || ret === BREAK) { + return; + } + continue; + } + + if (element.node) { + + ret = this.__execute(visitor.enter, element); + + if (this.__state === BREAK || ret === BREAK) { + return; + } + + worklist.push(sentinel); + leavelist.push(element); + + if (this.__state === SKIP || ret === SKIP) { + continue; + } + + node = element.node; + nodeType = element.wrap || node.type; + candidates = VisitorKeys[nodeType]; + + current = candidates.length; + while ((current -= 1) >= 0) { + key = candidates[current]; + candidate = node[key]; + if (!candidate) { + continue; + } + + if (!isArray(candidate)) { + worklist.push(new Element(candidate, key, null, null)); + continue; + } + + current2 = candidate.length; + while ((current2 -= 1) >= 0) { + if (!candidate[current2]) { + continue; + } + if ((nodeType === Syntax.ObjectExpression || nodeType === Syntax.ObjectPattern) && 'properties' === candidates[current]) { + element = new Element(candidate[current2], [key, current2], 'Property', null); + } else { + element = new Element(candidate[current2], [key, current2], null, null); + } + worklist.push(element); + } + } + } + } + }; + + Controller.prototype.replace = function replace(root, visitor) { + var worklist, + leavelist, + node, + nodeType, + target, + element, + current, + current2, + candidates, + candidate, + sentinel, + outer, + key; + + this.__initialize(root, visitor); + + sentinel = {}; + + // reference + worklist = this.__worklist; + leavelist = this.__leavelist; + + // initialize + outer = { + root: root + }; + element = new Element(root, null, null, new Reference(outer, 'root')); + worklist.push(element); + leavelist.push(element); + + while (worklist.length) { + element = worklist.pop(); + + if (element === sentinel) { + element = leavelist.pop(); + + target = this.__execute(visitor.leave, element); + + // node may be replaced with null, + // so distinguish between undefined and null in this place + if (target !== undefined && target !== BREAK && target !== SKIP) { + // replace + element.ref.replace(target); + } + + if (this.__state === BREAK || target === BREAK) { + return outer.root; + } + continue; + } + + target = this.__execute(visitor.enter, element); + + // node may be replaced with null, + // so distinguish between undefined and null in this place + if (target !== undefined && target !== BREAK && target !== SKIP) { + // replace + element.ref.replace(target); + element.node = target; + } + + if (this.__state === BREAK || target === BREAK) { + return outer.root; + } + + // node may be null + node = element.node; + if (!node) { + continue; + } + + worklist.push(sentinel); + leavelist.push(element); + + if (this.__state === SKIP || target === SKIP) { + continue; + } + + nodeType = element.wrap || node.type; + candidates = VisitorKeys[nodeType]; + + current = candidates.length; + while ((current -= 1) >= 0) { + key = candidates[current]; + candidate = node[key]; + if (!candidate) { + continue; + } + + if (!isArray(candidate)) { + worklist.push(new Element(candidate, key, null, new Reference(node, key))); + continue; + } + + current2 = candidate.length; + while ((current2 -= 1) >= 0) { + if (!candidate[current2]) { + continue; + } + if (nodeType === Syntax.ObjectExpression && 'properties' === candidates[current]) { + element = new Element(candidate[current2], [key, current2], 'Property', new Reference(candidate, current2)); + } else { + element = new Element(candidate[current2], [key, current2], null, new Reference(candidate, current2)); + } + worklist.push(element); + } + } + } + + return outer.root; + }; + + function traverse(root, visitor) { + var controller = new Controller(); + return controller.traverse(root, visitor); + } + + function replace(root, visitor) { + var controller = new Controller(); + return controller.replace(root, visitor); + } + + function extendCommentRange(comment, tokens) { + var target; + + target = upperBound(tokens, function search(token) { + return token.range[0] > comment.range[0]; + }); + + comment.extendedRange = [comment.range[0], comment.range[1]]; + + if (target !== tokens.length) { + comment.extendedRange[1] = tokens[target].range[0]; + } + + target -= 1; + if (target >= 0) { + comment.extendedRange[0] = tokens[target].range[1]; + } + + return comment; + } + + function attachComments(tree, providedComments, tokens) { + // At first, we should calculate extended comment ranges. + var comments = [], comment, len, i, cursor; + + if (!tree.range) { + throw new Error('attachComments needs range information'); + } + + // tokens array is empty, we attach comments to tree as 'leadingComments' + if (!tokens.length) { + if (providedComments.length) { + for (i = 0, len = providedComments.length; i < len; i += 1) { + comment = deepCopy(providedComments[i]); + comment.extendedRange = [0, tree.range[0]]; + comments.push(comment); + } + tree.leadingComments = comments; + } + return tree; + } + + for (i = 0, len = providedComments.length; i < len; i += 1) { + comments.push(extendCommentRange(deepCopy(providedComments[i]), tokens)); + } + + // This is based on John Freeman's implementation. + cursor = 0; + traverse(tree, { + enter: function (node) { + var comment; + + while (cursor < comments.length) { + comment = comments[cursor]; + if (comment.extendedRange[1] > node.range[0]) { + break; + } + + if (comment.extendedRange[1] === node.range[0]) { + if (!node.leadingComments) { + node.leadingComments = []; + } + node.leadingComments.push(comment); + comments.splice(cursor, 1); + } else { + cursor += 1; + } + } + + // already out of owned node + if (cursor === comments.length) { + return VisitorOption.Break; + } + + if (comments[cursor].extendedRange[0] > node.range[1]) { + return VisitorOption.Skip; + } + } + }); + + cursor = 0; + traverse(tree, { + leave: function (node) { + var comment; + + while (cursor < comments.length) { + comment = comments[cursor]; + if (node.range[1] < comment.extendedRange[0]) { + break; + } + + if (node.range[1] === comment.extendedRange[0]) { + if (!node.trailingComments) { + node.trailingComments = []; + } + node.trailingComments.push(comment); + comments.splice(cursor, 1); + } else { + cursor += 1; + } + } + + // already out of owned node + if (cursor === comments.length) { + return VisitorOption.Break; + } + + if (comments[cursor].extendedRange[0] > node.range[1]) { + return VisitorOption.Skip; + } + } + }); + + return tree; + } + + exports.version = '1.3.3-dev'; + exports.Syntax = Syntax; + exports.traverse = traverse; + exports.replace = replace; + exports.attachComments = attachComments; + exports.VisitorKeys = VisitorKeys; + exports.VisitorOption = VisitorOption; + exports.Controller = Controller; +})); +/* vim: set sw=4 ts=4 et tw=80 : */ diff --git a/editor/scripts/expander.js b/editor/scripts/expander.js new file mode 100644 index 0000000..f303a34 --- /dev/null +++ b/editor/scripts/expander.js @@ -0,0 +1,2528 @@ +/* + Copyright (C) 2012 Tim Disney + + + 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. + + 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 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. +*/ +(function (root, factory) { + if (typeof exports === 'object') { + // CommonJS + factory(exports, require('underscore'), require('./parser'), require('./syntax'), require('./scopedEval'), require('./patterns'), require('escodegen')); + } else if (typeof define === 'function' && define.amd) { + // AMD. Register as an anonymous module. + define([ + 'exports', + 'underscore', + 'parser', + 'syntax', + 'scopedEval', + 'patterns', + 'escodegen' + ], factory); + } +}(this, function (exports$2, _, parser, syn, se, patternModule, gen) { + 'use strict'; + // escodegen still doesn't quite support AMD: https://github.com/Constellation/escodegen/issues/115 + var codegen = typeof escodegen !== 'undefined' ? escodegen : gen; + var assert = syn.assert; + var throwSyntaxError = syn.throwSyntaxError; + var throwSyntaxCaseError = syn.throwSyntaxCaseError; + var SyntaxCaseError = syn.SyntaxCaseError; + var unwrapSyntax = syn.unwrapSyntax; + // used to export "private" methods for unit testing + exports$2._test = {}; + function StringMap(o) { + this.__data = o || {}; + } + StringMap.prototype = { + has: function (key) { + return Object.prototype.hasOwnProperty.call(this.__data, key); + }, + get: function (key) { + return this.has(key) ? this.__data[key] : void 0; + }, + set: function (key, value) { + this.__data[key] = value; + }, + extend: function () { + var args = _.map(_.toArray(arguments), function (x) { + return x.__data; + }); + _.extend.apply(_, [this.__data].concat(args)); + return this; + } + }; + var scopedEval = se.scopedEval; + var Rename = syn.Rename; + var Mark = syn.Mark; + var Def = syn.Def; + var syntaxFromToken = syn.syntaxFromToken; + var joinSyntax = syn.joinSyntax; + var builtinMode = false; + var expandCount = 0; + var maxExpands; + var push = Array.prototype.push; + function remdup(mark, mlist) { + if (mark === _.first(mlist)) { + return _.rest(mlist, 1); + } + return [mark].concat(mlist); + } + // (CSyntax) -> [...Num] + function marksof(ctx, stopName, originalName) { + while (ctx) { + if (ctx.constructor === Mark) { + return remdup(ctx.mark, marksof(ctx.context, stopName, originalName)); + } + if (ctx.constructor === Def) { + ctx = ctx.context; + continue; + } + if (ctx.constructor === Rename) { + if (stopName === originalName + '$' + ctx.name) { + return []; + } + ctx = ctx.context; + continue; + } + } + return []; + } + function resolve(stx) { + return resolveCtx(stx.token.value, stx.context, [], [], {}); + } + // This call memoizes intermediate results in the recursive invocation. + // The scope of the memo cache is the resolve() call, so that multiple + // resolve() calls don't walk all over each other, and memory used for + // the memoization can be garbage collected. + // + // The memoization addresses issue #232. + // + // It looks like the memoization uses only the context and doesn't look + // at originalName, stop_spine and stop_branch arguments. This is valid + // because whenever in every recursive call operates on a "deeper" or + // else a newly created context. Therefore the collection of + // [originalName, stop_spine, stop_branch] can all be associated with a + // unique context. This argument is easier to see in a recursive + // rewrite of the resolveCtx function than with the while loop + // optimization - https://gist.github.com/srikumarks/9847260 - where the + // recursive steps always operate on a different context. + // + // This might make it seem that the resolution results can be stored on + // the context object itself, but that would not work in general + // because multiple resolve() calls will walk over each other's cache + // results, which fails tests. So the memoization uses only a context's + // unique instance numbers as the memoization key and is local to each + // resolve() call. + // + // With this memoization, the time complexity of the resolveCtx call is + // no longer exponential for the cases in issue #232. + function resolveCtx(originalName, ctx, stop_spine, stop_branch, cache) { + if (!ctx) { + return originalName; + } + var key = ctx.instNum; + return cache[key] || (cache[key] = resolveCtxFull(originalName, ctx, stop_spine, stop_branch, cache)); + } + // (Syntax) -> String + function resolveCtxFull(originalName, ctx, stop_spine, stop_branch, cache) { + while (true) { + if (!ctx) { + return originalName; + } + if (ctx.constructor === Mark) { + ctx = ctx.context; + continue; + } + if (ctx.constructor === Def) { + if (stop_spine.indexOf(ctx.defctx) !== -1) { + ctx = ctx.context; + continue; + } else { + stop_branch = unionEl(stop_branch, ctx.defctx); + ctx = renames(ctx.defctx, ctx.context, originalName); + continue; + } + } + if (ctx.constructor === Rename) { + if (originalName === ctx.id.token.value) { + var idName = resolveCtx(ctx.id.token.value, ctx.id.context, stop_branch, stop_branch, cache); + var subName = resolveCtx(originalName, ctx.context, unionEl(stop_spine, ctx.def), stop_branch, cache); + if (idName === subName) { + var idMarks = marksof(ctx.id.context, originalName + '$' + ctx.name, originalName); + var subMarks = marksof(ctx.context, originalName + '$' + ctx.name, originalName); + if (arraysEqual(idMarks, subMarks)) { + return originalName + '$' + ctx.name; + } + } + } + ctx = ctx.context; + continue; + } + return originalName; + } + } + function arraysEqual(a, b) { + if (a.length !== b.length) { + return false; + } + for (var i = 0; i < a.length; i++) { + if (a[i] !== b[i]) { + return false; + } + } + return true; + } + function renames(defctx, oldctx, originalName) { + var acc = oldctx; + for (var i = 0; i < defctx.length; i++) { + if (defctx[i].id.token.value === originalName) { + acc = new Rename(defctx[i].id, defctx[i].name, acc, defctx); + } + } + return acc; + } + function unionEl(arr, el) { + if (arr.indexOf(el) === -1) { + var res = arr.slice(0); + res.push(el); + return res; + } + return arr; + } + var nextFresh = 0; + // fun () -> Num + function fresh() { + return nextFresh++; + } + // wraps the array of syntax objects in the delimiters given by the second argument + // ([...CSyntax], CSyntax) -> [...CSyntax] + function wrapDelim(towrap, delimSyntax) { + assert(delimSyntax.token.type === parser.Token.Delimiter, 'expecting a delimiter token'); + return syntaxFromToken({ + type: parser.Token.Delimiter, + value: delimSyntax.token.value, + inner: towrap, + range: delimSyntax.token.range, + startLineNumber: delimSyntax.token.startLineNumber, + lineStart: delimSyntax.token.lineStart + }, delimSyntax); + } + // (CSyntax) -> [...CSyntax] + function getParamIdentifiers(argSyntax) { + if (argSyntax.token.type === parser.Token.Delimiter) { + return _.filter(argSyntax.token.inner, function (stx) { + return stx.token.value !== ','; + }); + } else if (argSyntax.token.type === parser.Token.Identifier) { + return [argSyntax]; + } else { + assert(false, 'expecting a delimiter or a single identifier for function parameters'); + } + } + function inherit(parent, child, methods) { + var P = function () { + }; + P.prototype = parent.prototype; + child.prototype = new P(); + child.prototype.constructor = child; + _.extend(child.prototype, methods); + } + // A TermTree is the core data structure for the macro expansion process. + // It acts as a semi-structured representation of the syntax. + function TermTree() { + } + TermTree.properties = []; + TermTree.create = function () { + return new TermTree(); + }; + TermTree.prototype = { + 'isTermTree': true, + 'destruct': function () { + var self = this; + return _.reduce(this.constructor.properties, function (acc, prop) { + if (self[prop] && self[prop].isTermTree) { + push.apply(acc, self[prop].destruct()); + return acc; + } else if (self[prop] && self[prop].token && self[prop].token.inner) { + var src = self[prop].token; + var keys = Object.keys(src); + var newtok = {}; + for (var i = 0, len = keys.length, key; i < len; i++) { + key = keys[i]; + newtok[key] = src[key]; + } + var clone = syntaxFromToken(newtok, self[prop]); + clone.token.inner = _.reduce(clone.token.inner, function (acc$2, t) { + if (t && t.isTermTree) { + push.apply(acc$2, t.destruct()); + return acc$2; + } + acc$2.push(t); + return acc$2; + }, []); + acc.push(clone); + return acc; + } else if (Array.isArray(self[prop])) { + var destArr = _.reduce(self[prop], function (acc$2, t) { + if (t && t.isTermTree) { + push.apply(acc$2, t.destruct()); + return acc$2; + } + acc$2.push(t); + return acc$2; + }, []); + push.apply(acc, destArr); + return acc; + } else if (self[prop]) { + acc.push(self[prop]); + return acc; + } else { + return acc; + } + }, []); + }, + 'addDefCtx': function (def) { + var self = this; + _.each(this.constructor.properties, function (prop) { + if (Array.isArray(self[prop])) { + self[prop] = _.map(self[prop], function (item) { + return item.addDefCtx(def); + }); + } else if (self[prop]) { + self[prop] = self[prop].addDefCtx(def); + } + }); + return this; + }, + 'rename': function (id, name) { + var self = this; + _.each(this.constructor.properties, function (prop) { + if (Array.isArray(self[prop])) { + self[prop] = _.map(self[prop], function (item) { + return item.rename(id, name); + }); + } else if (self[prop]) { + self[prop] = self[prop].rename(id, name); + } + }); + return this; + } + }; + function EOF(eof) { + this.eof = eof; + } + EOF.properties = ['eof']; + EOF.create = function (eof) { + return new EOF(eof); + }; + inherit(TermTree, EOF, { 'isEOF': true }); + function Keyword(keyword) { + this.keyword = keyword; + } + Keyword.properties = ['keyword']; + Keyword.create = function (keyword) { + return new Keyword(keyword); + }; + inherit(TermTree, Keyword, { 'isKeyword': true }); + function Punc(punc) { + this.punc = punc; + } + Punc.properties = ['punc']; + Punc.create = function (punc) { + return new Punc(punc); + }; + inherit(TermTree, Punc, { 'isPunc': true }); + function Delimiter(delim) { + this.delim = delim; + } + Delimiter.properties = ['delim']; + Delimiter.create = function (delim) { + return new Delimiter(delim); + }; + inherit(TermTree, Delimiter, { 'isDelimiter': true }); + function LetMacro(name, body) { + this.name = name; + this.body = body; + } + LetMacro.properties = [ + 'name', + 'body' + ]; + LetMacro.create = function (name, body) { + return new LetMacro(name, body); + }; + inherit(TermTree, LetMacro, { 'isLetMacro': true }); + function Macro(name, body) { + this.name = name; + this.body = body; + } + Macro.properties = [ + 'name', + 'body' + ]; + Macro.create = function (name, body) { + return new Macro(name, body); + }; + inherit(TermTree, Macro, { 'isMacro': true }); + function AnonMacro(body) { + this.body = body; + } + AnonMacro.properties = ['body']; + AnonMacro.create = function (body) { + return new AnonMacro(body); + }; + inherit(TermTree, AnonMacro, { 'isAnonMacro': true }); + function OperatorDefinition(type, name, prec, assoc, body) { + this.type = type; + this.name = name; + this.prec = prec; + this.assoc = assoc; + this.body = body; + } + OperatorDefinition.properties = [ + 'type', + 'name', + 'prec', + 'assoc', + 'body' + ]; + OperatorDefinition.create = function (type, name, prec, assoc, body) { + return new OperatorDefinition(type, name, prec, assoc, body); + }; + inherit(TermTree, OperatorDefinition, { 'isOperatorDefinition': true }); + function Module(body, exports$3) { + this.body = body; + this.exports = exports$3; + } + Module.properties = [ + 'body', + 'exports' + ]; + Module.create = function (body, exports$3) { + return new Module(body, exports$3); + }; + inherit(TermTree, Module, { 'isModule': true }); + function Export(name) { + this.name = name; + } + Export.properties = ['name']; + Export.create = function (name) { + return new Export(name); + }; + inherit(TermTree, Export, { 'isExport': true }); + function VariableDeclaration(ident, eq, init, comma) { + this.ident = ident; + this.eq = eq; + this.init = init; + this.comma = comma; + } + VariableDeclaration.properties = [ + 'ident', + 'eq', + 'init', + 'comma' + ]; + VariableDeclaration.create = function (ident, eq, init, comma) { + return new VariableDeclaration(ident, eq, init, comma); + }; + inherit(TermTree, VariableDeclaration, { 'isVariableDeclaration': true }); + function Statement() { + } + Statement.properties = []; + Statement.create = function () { + return new Statement(); + }; + inherit(TermTree, Statement, { 'isStatement': true }); + function Empty() { + } + Empty.properties = []; + Empty.create = function () { + return new Empty(); + }; + inherit(Statement, Empty, { 'isEmpty': true }); + function CatchClause(keyword, params, body) { + this.keyword = keyword; + this.params = params; + this.body = body; + } + CatchClause.properties = [ + 'keyword', + 'params', + 'body' + ]; + CatchClause.create = function (keyword, params, body) { + return new CatchClause(keyword, params, body); + }; + inherit(Statement, CatchClause, { 'isCatchClause': true }); + function ForStatement(keyword, cond) { + this.keyword = keyword; + this.cond = cond; + } + ForStatement.properties = [ + 'keyword', + 'cond' + ]; + ForStatement.create = function (keyword, cond) { + return new ForStatement(keyword, cond); + }; + inherit(Statement, ForStatement, { 'isForStatement': true }); + function ReturnStatement(keyword, expr) { + this.keyword = keyword; + this.expr = expr; + } + ReturnStatement.properties = [ + 'keyword', + 'expr' + ]; + ReturnStatement.create = function (keyword, expr) { + return new ReturnStatement(keyword, expr); + }; + inherit(Statement, ReturnStatement, { + 'isReturnStatement': true, + 'destruct': function () { + var expr = this.expr.destruct(); + // need to adjust the line numbers to make sure that the expr + // starts on the same line as the return keyword. This might + // not be the case if an operator or infix macro perturbed the + // line numbers during expansion. + expr = adjustLineContext(expr, this.keyword.keyword); + return this.keyword.destruct().concat(expr); + } + }); + function Expr() { + } + Expr.properties = []; + Expr.create = function () { + return new Expr(); + }; + inherit(Statement, Expr, { 'isExpr': true }); + function UnaryOp(op, expr) { + this.op = op; + this.expr = expr; + } + UnaryOp.properties = [ + 'op', + 'expr' + ]; + UnaryOp.create = function (op, expr) { + return new UnaryOp(op, expr); + }; + inherit(Expr, UnaryOp, { 'isUnaryOp': true }); + function PostfixOp(expr, op) { + this.expr = expr; + this.op = op; + } + PostfixOp.properties = [ + 'expr', + 'op' + ]; + PostfixOp.create = function (expr, op) { + return new PostfixOp(expr, op); + }; + inherit(Expr, PostfixOp, { 'isPostfixOp': true }); + function BinOp(left, op, right) { + this.left = left; + this.op = op; + this.right = right; + } + BinOp.properties = [ + 'left', + 'op', + 'right' + ]; + BinOp.create = function (left, op, right) { + return new BinOp(left, op, right); + }; + inherit(Expr, BinOp, { 'isBinOp': true }); + function AssignmentExpression(left, op, right) { + this.left = left; + this.op = op; + this.right = right; + } + AssignmentExpression.properties = [ + 'left', + 'op', + 'right' + ]; + AssignmentExpression.create = function (left, op, right) { + return new AssignmentExpression(left, op, right); + }; + inherit(Expr, AssignmentExpression, { 'isAssignmentExpression': true }); + function ConditionalExpression(cond, question, tru, colon, fls) { + this.cond = cond; + this.question = question; + this.tru = tru; + this.colon = colon; + this.fls = fls; + } + ConditionalExpression.properties = [ + 'cond', + 'question', + 'tru', + 'colon', + 'fls' + ]; + ConditionalExpression.create = function (cond, question, tru, colon, fls) { + return new ConditionalExpression(cond, question, tru, colon, fls); + }; + inherit(Expr, ConditionalExpression, { 'isConditionalExpression': true }); + function NamedFun(keyword, star, name, params, body) { + this.keyword = keyword; + this.star = star; + this.name = name; + this.params = params; + this.body = body; + } + NamedFun.properties = [ + 'keyword', + 'star', + 'name', + 'params', + 'body' + ]; + NamedFun.create = function (keyword, star, name, params, body) { + return new NamedFun(keyword, star, name, params, body); + }; + inherit(Expr, NamedFun, { 'isNamedFun': true }); + function AnonFun(keyword, star, params, body) { + this.keyword = keyword; + this.star = star; + this.params = params; + this.body = body; + } + AnonFun.properties = [ + 'keyword', + 'star', + 'params', + 'body' + ]; + AnonFun.create = function (keyword, star, params, body) { + return new AnonFun(keyword, star, params, body); + }; + inherit(Expr, AnonFun, { 'isAnonFun': true }); + function ArrowFun(params, arrow, body) { + this.params = params; + this.arrow = arrow; + this.body = body; + } + ArrowFun.properties = [ + 'params', + 'arrow', + 'body' + ]; + ArrowFun.create = function (params, arrow, body) { + return new ArrowFun(params, arrow, body); + }; + inherit(Expr, ArrowFun, { 'isArrowFun': true }); + function ObjDotGet(left, dot, right) { + this.left = left; + this.dot = dot; + this.right = right; + } + ObjDotGet.properties = [ + 'left', + 'dot', + 'right' + ]; + ObjDotGet.create = function (left, dot, right) { + return new ObjDotGet(left, dot, right); + }; + inherit(Expr, ObjDotGet, { 'isObjDotGet': true }); + function ObjGet(left, right) { + this.left = left; + this.right = right; + } + ObjGet.properties = [ + 'left', + 'right' + ]; + ObjGet.create = function (left, right) { + return new ObjGet(left, right); + }; + inherit(Expr, ObjGet, { 'isObjGet': true }); + function Template(template) { + this.template = template; + } + Template.properties = ['template']; + Template.create = function (template) { + return new Template(template); + }; + inherit(Expr, Template, { 'isTemplate': true }); + function Call(fun, args) { + this.fun = fun; + this.args = args; + } + Call.properties = [ + 'fun', + 'args' + ]; + Call.create = function (fun, args) { + return new Call(fun, args); + }; + inherit(Expr, Call, { 'isCall': true }); + function PrimaryExpression() { + } + PrimaryExpression.properties = []; + PrimaryExpression.create = function () { + return new PrimaryExpression(); + }; + inherit(Expr, PrimaryExpression, { 'isPrimaryExpression': true }); + function ThisExpression(keyword) { + this.keyword = keyword; + } + ThisExpression.properties = ['keyword']; + ThisExpression.create = function (keyword) { + return new ThisExpression(keyword); + }; + inherit(PrimaryExpression, ThisExpression, { 'isThisExpression': true }); + function Lit(lit) { + this.lit = lit; + } + Lit.properties = ['lit']; + Lit.create = function (lit) { + return new Lit(lit); + }; + inherit(PrimaryExpression, Lit, { 'isLit': true }); + function Block(body) { + this.body = body; + } + Block.properties = ['body']; + Block.create = function (body) { + return new Block(body); + }; + inherit(PrimaryExpression, Block, { 'isBlock': true }); + function ArrayLiteral(array) { + this.array = array; + } + ArrayLiteral.properties = ['array']; + ArrayLiteral.create = function (array) { + return new ArrayLiteral(array); + }; + inherit(PrimaryExpression, ArrayLiteral, { 'isArrayLiteral': true }); + function Id(id) { + this.id = id; + } + Id.properties = ['id']; + Id.create = function (id) { + return new Id(id); + }; + inherit(PrimaryExpression, Id, { 'isId': true }); + function Partial() { + } + Partial.properties = []; + Partial.create = function () { + return new Partial(); + }; + inherit(TermTree, Partial, { 'isPartial': true }); + function PartialOperation(stx, left) { + this.stx = stx; + this.left = left; + } + PartialOperation.properties = [ + 'stx', + 'left' + ]; + PartialOperation.create = function (stx, left) { + return new PartialOperation(stx, left); + }; + inherit(Partial, PartialOperation, { 'isPartialOperation': true }); + function PartialExpression(stx, left, combine) { + this.stx = stx; + this.left = left; + this.combine = combine; + } + PartialExpression.properties = [ + 'stx', + 'left', + 'combine' + ]; + PartialExpression.create = function (stx, left, combine) { + return new PartialExpression(stx, left, combine); + }; + inherit(Partial, PartialExpression, { 'isPartialExpression': true }); + function BindingStatement(keyword, decls) { + this.keyword = keyword; + this.decls = decls; + } + BindingStatement.properties = [ + 'keyword', + 'decls' + ]; + BindingStatement.create = function (keyword, decls) { + return new BindingStatement(keyword, decls); + }; + inherit(Statement, BindingStatement, { + 'isBindingStatement': true, + 'destruct': function () { + return this.keyword.destruct().concat(_.reduce(this.decls, function (acc, decl) { + push.apply(acc, decl.destruct()); + return acc; + }, [])); + } + }); + function VariableStatement(keyword, decls) { + this.keyword = keyword; + this.decls = decls; + } + VariableStatement.properties = [ + 'keyword', + 'decls' + ]; + VariableStatement.create = function (keyword, decls) { + return new VariableStatement(keyword, decls); + }; + inherit(BindingStatement, VariableStatement, { 'isVariableStatement': true }); + function LetStatement(keyword, decls) { + this.keyword = keyword; + this.decls = decls; + } + LetStatement.properties = [ + 'keyword', + 'decls' + ]; + LetStatement.create = function (keyword, decls) { + return new LetStatement(keyword, decls); + }; + inherit(BindingStatement, LetStatement, { 'isLetStatement': true }); + function ConstStatement(keyword, decls) { + this.keyword = keyword; + this.decls = decls; + } + ConstStatement.properties = [ + 'keyword', + 'decls' + ]; + ConstStatement.create = function (keyword, decls) { + return new ConstStatement(keyword, decls); + }; + inherit(BindingStatement, ConstStatement, { 'isConstStatement': true }); + function ParenExpression(args, delim, commas) { + this.args = args; + this.delim = delim; + this.commas = commas; + } + ParenExpression.properties = [ + 'args', + 'delim', + 'commas' + ]; + ParenExpression.create = function (args, delim, commas) { + return new ParenExpression(args, delim, commas); + }; + inherit(PrimaryExpression, ParenExpression, { + 'isParenExpression': true, + 'destruct': function () { + var commas = this.commas.slice(); + var src = this.delim.token; + var keys = Object.keys(src); + var newtok = {}; + for (var i = 0, len = keys.length, key; i < len; i++) { + key = keys[i]; + newtok[key] = src[key]; + } + var delim = syntaxFromToken(newtok, this.delim); + delim.token.inner = _.reduce(this.args, function (acc, term) { + assert(term && term.isTermTree, 'expecting term trees in destruct of ParenExpression'); + push.apply(acc, term.destruct()); + // add all commas except for the last one + if (commas.length > 0) { + acc.push(commas.shift()); + } + return acc; + }, []); + return Delimiter.create(delim).destruct(); + } + }); + function stxIsUnaryOp(stx) { + var staticOperators = [ + '+', + '-', + '~', + '!', + 'delete', + 'void', + 'typeof', + 'yield', + 'new', + '++', + '--' + ]; + return _.contains(staticOperators, unwrapSyntax(stx)); + } + function stxIsBinOp(stx) { + var staticOperators = [ + '+', + '-', + '*', + '/', + '%', + '||', + '&&', + '|', + '&', + '^', + '==', + '!=', + '===', + '!==', + '<', + '>', + '<=', + '>=', + 'in', + 'instanceof', + '<<', + '>>', + '>>>' + ]; + return _.contains(staticOperators, unwrapSyntax(stx)); + } + function getUnaryOpPrec(op) { + var operatorPrecedence = { + 'new': 16, + '++': 15, + '--': 15, + '!': 14, + '~': 14, + '+': 14, + '-': 14, + 'typeof': 14, + 'void': 14, + 'delete': 14, + 'yield': 2 + }; + return operatorPrecedence[op]; + } + function getBinaryOpPrec(op) { + var operatorPrecedence = { + '*': 13, + '/': 13, + '%': 13, + '+': 12, + '-': 12, + '>>': 11, + '<<': 11, + '>>>': 11, + '<': 10, + '<=': 10, + '>': 10, + '>=': 10, + 'in': 10, + 'instanceof': 10, + '==': 9, + '!=': 9, + '===': 9, + '!==': 9, + '&': 8, + '^': 7, + '|': 6, + '&&': 5, + '||': 4 + }; + return operatorPrecedence[op]; + } + function getBinaryOpAssoc(op) { + var operatorAssoc = { + '*': 'left', + '/': 'left', + '%': 'left', + '+': 'left', + '-': 'left', + '>>': 'left', + '<<': 'left', + '>>>': 'left', + '<': 'left', + '<=': 'left', + '>': 'left', + '>=': 'left', + 'in': 'left', + 'instanceof': 'left', + '==': 'left', + '!=': 'left', + '===': 'left', + '!==': 'left', + '&': 'left', + '^': 'left', + '|': 'left', + '&&': 'left', + '||': 'left' + }; + return operatorAssoc[op]; + } + function stxIsAssignOp(stx) { + var staticOperators = [ + '=', + '+=', + '-=', + '*=', + '/=', + '%=', + '<<=', + '>>=', + '>>>=', + '|=', + '^=', + '&=' + ]; + return _.contains(staticOperators, unwrapSyntax(stx)); + } + function enforestVarStatement(stx, context, varStx) { + var decls = []; + var rest = stx; + var rhs; + if (!rest.length) { + throwSyntaxError('enforest', 'Unexpected end of input', varStx); + } + if (expandCount >= maxExpands) { + return null; + } + while (rest.length) { + if (rest[0].token.type === parser.Token.Identifier) { + if (rest[1] && rest[1].token.type === parser.Token.Punctuator && rest[1].token.value === '=') { + rhs = get_expression(rest.slice(2), context); + if (rhs.result == null) { + throwSyntaxError('enforest', 'Unexpected token', rhs.rest[0]); + } + if (rhs.rest[0] && rhs.rest[0].token.type === parser.Token.Punctuator && rhs.rest[0].token.value === ',') { + decls.push(VariableDeclaration.create(rest[0], rest[1], rhs.result, rhs.rest[0])); + rest = rhs.rest.slice(1); + continue; + } else { + decls.push(VariableDeclaration.create(rest[0], rest[1], rhs.result, null)); + rest = rhs.rest; + break; + } + } else if (rest[1] && rest[1].token.type === parser.Token.Punctuator && rest[1].token.value === ',') { + decls.push(VariableDeclaration.create(rest[0], null, null, rest[1])); + rest = rest.slice(2); + } else { + decls.push(VariableDeclaration.create(rest[0], null, null, null)); + rest = rest.slice(1); + break; + } + } else { + throwSyntaxError('enforest', 'Unexpected token', rest[0]); + } + } + return { + result: decls, + rest: rest + }; + } + function enforestAssignment(stx, context, left, prevStx, prevTerms) { + var op = stx[0]; + var rightStx = stx.slice(1); + var opTerm = Punc.create(stx[0]); + var opPrevStx = tagWithTerm(opTerm, [stx[0]]).concat(tagWithTerm(left, left.destruct().reverse()), prevStx); + var opPrevTerms = [ + opTerm, + left + ].concat(prevTerms); + var opRes = enforest(rightStx, context, opPrevStx, opPrevTerms); + if (opRes.result) { + // Lookbehind was matched, so it may not even be a binop anymore. + if (opRes.prevTerms.length < opPrevTerms.length) { + return opRes; + } + var right = opRes.result; + // only a binop if the right is a real expression + // so 2+2++ will only match 2+2 + if (right.isExpr) { + var term = AssignmentExpression.create(left, op, right); + return { + result: term, + rest: opRes.rest, + prevStx: prevStx, + prevTerms: prevTerms + }; + } + } else { + return opRes; + } + } + function enforestParenExpression(parens, context) { + var argRes, enforestedArgs = [], commas = []; + var innerTokens = parens.expose().token.inner; + while (innerTokens.length > 0) { + argRes = enforest(innerTokens, context); + if (!argRes.result || !argRes.result.isExpr) { + return null; + } + enforestedArgs.push(argRes.result); + innerTokens = argRes.rest; + if (innerTokens[0] && innerTokens[0].token.value === ',') { + // record the comma for later + commas.push(innerTokens[0]); + // but dump it for the next loop turn + innerTokens = innerTokens.slice(1); + } else { + // either there are no more tokens or + // they aren't a comma, either way we + // are done with the loop + break; + } + } + return innerTokens.length ? null : ParenExpression.create(enforestedArgs, parens, commas); + } + function adjustLineContext(stx, original, current) { + current = current || { + lastLineNumber: stx[0].token.lineNumber || stx[0].token.startLineNumber, + lineNumber: original.token.lineNumber + }; + return _.map(stx, function (stx$2) { + if (stx$2.token.type === parser.Token.Delimiter) { + // handle tokens with missing line info + stx$2.token.startLineNumber = typeof stx$2.token.startLineNumber == 'undefined' ? original.token.lineNumber : stx$2.token.startLineNumber; + stx$2.token.endLineNumber = typeof stx$2.token.endLineNumber == 'undefined' ? original.token.lineNumber : stx$2.token.endLineNumber; + stx$2.token.startLineStart = typeof stx$2.token.startLineStart == 'undefined' ? original.token.lineStart : stx$2.token.startLineStart; + stx$2.token.endLineStart = typeof stx$2.token.endLineStart == 'undefined' ? original.token.lineStart : stx$2.token.endLineStart; + stx$2.token.startRange = typeof stx$2.token.startRange == 'undefined' ? original.token.range : stx$2.token.startRange; + stx$2.token.endRange = typeof stx$2.token.endRange == 'undefined' ? original.token.range : stx$2.token.endRange; + stx$2.token.sm_startLineNumber = typeof stx$2.token.sm_startLineNumber == 'undefined' ? stx$2.token.startLineNumber : stx$2.token.sm_startLineNumber; + stx$2.token.sm_endLineNumber = typeof stx$2.token.sm_endLineNumber == 'undefined' ? stx$2.token.endLineNumber : stx$2.token.sm_endLineNumber; + stx$2.token.sm_startLineStart = typeof stx$2.token.sm_startLineStart == 'undefined' ? stx$2.token.startLineStart : stx$2.token.sm_startLineStart; + stx$2.token.sm_endLineStart = typeof stx$2.token.sm_endLineStart == 'undefined' ? stx$2.token.endLineStart : stx$2.token.sm_endLineStart; + stx$2.token.sm_startRange = typeof stx$2.token.sm_startRange == 'undefined' ? stx$2.token.startRange : stx$2.token.sm_startRange; + stx$2.token.sm_endRange = typeof stx$2.token.sm_endRange == 'undefined' ? stx$2.token.endRange : stx$2.token.sm_endRange; + if (stx$2.token.startLineNumber !== current.lineNumber) { + if (stx$2.token.startLineNumber !== current.lastLineNumber) { + current.lineNumber++; + current.lastLineNumber = stx$2.token.startLineNumber; + stx$2.token.startLineNumber = current.lineNumber; + } else { + current.lastLineNumber = stx$2.token.startLineNumber; + stx$2.token.startLineNumber = current.lineNumber; + } + } + if (stx$2.token.inner.length > 0) { + stx$2.token.inner = adjustLineContext(stx$2.token.inner, original, current); + } + return stx$2; + } + // handle tokens with missing line info + stx$2.token.lineNumber = typeof stx$2.token.lineNumber == 'undefined' ? original.token.lineNumber : stx$2.token.lineNumber; + stx$2.token.lineStart = typeof stx$2.token.lineStart == 'undefined' ? original.token.lineStart : stx$2.token.lineStart; + stx$2.token.range = typeof stx$2.token.range == 'undefined' ? original.token.range : stx$2.token.range; + // Only set the sourcemap line info once. Necessary because a single + // syntax object can go through expansion multiple times. If at some point + // we want to write an expansion stepper this might be a good place to store + // intermediate expansion line info (ie push to a stack instead of + // just write once). + stx$2.token.sm_lineNumber = typeof stx$2.token.sm_lineNumber == 'undefined' ? stx$2.token.lineNumber : stx$2.token.sm_lineNumber; + stx$2.token.sm_lineStart = typeof stx$2.token.sm_lineStart == 'undefined' ? stx$2.token.lineStart : stx$2.token.sm_lineStart; + stx$2.token.sm_range = typeof stx$2.token.sm_range == 'undefined' ? stx$2.token.range.slice() : stx$2.token.sm_range; + // move the line info to line up with the macro name + // (line info starting from the macro name) + if (stx$2.token.lineNumber !== current.lineNumber) { + if (stx$2.token.lineNumber !== current.lastLineNumber) { + current.lineNumber++; + current.lastLineNumber = stx$2.token.lineNumber; + stx$2.token.lineNumber = current.lineNumber; + } else { + current.lastLineNumber = stx$2.token.lineNumber; + stx$2.token.lineNumber = current.lineNumber; + } + } + return stx$2; + }); + } + function getName(head, rest) { + var idx = 0; + var curr = head; + var next = rest[idx]; + var name = [head]; + while (true) { + if (next && (next.token.type === parser.Token.Punctuator || next.token.type === parser.Token.Identifier || next.token.type === parser.Token.Keyword) && (curr.token.sm_range && next.token.sm_range && curr.token.sm_range[1] === next.token.sm_range[0] || curr.token.range[1] === next.token.range[0])) { + name.push(next); + curr = next; + next = rest[++idx]; + } else { + return name; + } + } + } + function getMacroInEnv(head, rest, env) { + if (!(head.token.type === parser.Token.Identifier || head.token.type === parser.Token.Keyword || head.token.type === parser.Token.Punctuator)) { + return null; + } + var name = getName(head, rest); + // simple case, don't need to create a new syntax object + if (name.length === 1) { + if (env.names.get(unwrapSyntax(name[0]))) { + var resolvedName = resolve(name[0]); + if (env.has(resolvedName)) { + return env.get(resolvedName); + } + } + return null; + } else { + while (name.length > 0) { + var nameStr = name.map(unwrapSyntax).join(''); + if (env.names.get(nameStr)) { + var nameStx = syn.makeIdent(nameStr, name[0]); + var resolvedName = resolve(nameStx); + if (env.has(resolvedName)) { + return env.get(resolvedName); + } + } + name.pop(); + } + return null; + } + } + function nameInEnv(head, rest, env) { + return getMacroInEnv(head, rest, env) !== null; + } + // This should only be used on things that can't be rebound except by + // macros (puncs, keywords). + function resolveFast(stx, env) { + var name = unwrapSyntax(stx); + return env.names.get(name) ? resolve(stx) : name; + } + function expandMacro(stx, context, opCtx, opType, macroObj) { + // pull the macro transformer out the environment + var head = stx[0]; + var rest = stx.slice(1); + macroObj = macroObj || getMacroInEnv(head, rest, context.env); + var stxArg = rest.slice(macroObj.fullName.length - 1); + var transformer; + if (opType != null) { + assert(opType === 'binary' || opType === 'unary', 'operator type should be either unary or binary: ' + opType); + transformer = macroObj[opType].fn; + } else { + transformer = macroObj.fn; + } + // create a new mark to be used for the input to + // the macro + var newMark = fresh(); + var transformerContext = makeExpanderContext(_.defaults({ mark: newMark }, context)); + // apply the transformer + var rt; + try { + rt = transformer([head].concat(stxArg), transformerContext, opCtx.prevStx, opCtx.prevTerms); + } catch (e) { + if (e instanceof SyntaxCaseError) { + // add a nicer error for syntax case + var nameStr = macroObj.fullName.map(function (stx$2) { + return stx$2.token.value; + }).join(''); + if (opType != null) { + var argumentString = '`' + stxArg.slice(0, 5).map(function (stx$2) { + return stx$2.token.value; + }).join(' ') + '...`'; + throwSyntaxError('operator', 'Operator `' + nameStr + '` could not be matched with ' + argumentString, head); + } else { + var argumentString = '`' + stxArg.slice(0, 5).map(function (stx$2) { + return stx$2.token.value; + }).join(' ') + '...`'; + throwSyntaxError('macro', 'Macro `' + nameStr + '` could not be matched with ' + argumentString, head); + } + } else { + // just rethrow it + throw e; + } + } + if (!builtinMode && !macroObj.builtin) { + expandCount++; + } + if (!Array.isArray(rt.result)) { + throwSyntaxError('enforest', 'Macro must return a syntax array', stx[0]); + } + if (rt.result.length > 0) { + var adjustedResult = adjustLineContext(rt.result, head); + if (stx[0].token.leadingComments) { + if (adjustedResult[0].token.leadingComments) { + adjustedResult[0].token.leadingComments = adjustedResult[0].token.leadingComments.concat(head.token.leadingComments); + } else { + adjustedResult[0].token.leadingComments = head.token.leadingComments; + } + } + rt.result = adjustedResult; + } + return rt; + } + function comparePrec(left, right, assoc) { + if (assoc === 'left') { + return left <= right; + } + return left < right; + } + // enforest the tokens, returns an object with the `result` TermTree and + // the uninterpreted `rest` of the syntax + function enforest(toks, context, prevStx, prevTerms) { + assert(toks.length > 0, 'enforest assumes there are tokens to work with'); + prevStx = prevStx || []; + prevTerms = prevTerms || []; + if (expandCount >= maxExpands) { + return { + result: null, + rest: toks + }; + } + function step(head, rest, opCtx) { + var innerTokens; + assert(Array.isArray(rest), 'result must at least be an empty array'); + if (head.isTermTree) { + var isCustomOp = false; + var uopMacroObj; + var uopSyntax; + if (head.isPunc || head.isKeyword || head.isId) { + if (head.isPunc) { + uopSyntax = head.punc; + } else if (head.isKeyword) { + uopSyntax = head.keyword; + } else if (head.isId) { + uopSyntax = head.id; + } + uopMacroObj = getMacroInEnv(uopSyntax, rest, context.env); + isCustomOp = uopMacroObj && uopMacroObj.isOp; + } + // look up once (we want to check multiple properties on bopMacroObj + // without repeatedly calling getMacroInEnv) + var bopMacroObj; + if (rest[0] && rest[1]) { + bopMacroObj = getMacroInEnv(rest[0], rest.slice(1), context.env); + } + // unary operator + if (isCustomOp && uopMacroObj.unary || uopSyntax && stxIsUnaryOp(uopSyntax)) { + var uopPrec; + if (isCustomOp && uopMacroObj.unary) { + uopPrec = uopMacroObj.unary.prec; + } else { + uopPrec = getUnaryOpPrec(unwrapSyntax(uopSyntax)); + } + var opRest = rest; + var uopMacroName; + if (uopMacroObj) { + uopMacroName = [uopSyntax].concat(rest.slice(0, uopMacroObj.fullName.length - 1)); + opRest = rest.slice(uopMacroObj.fullName.length - 1); + } + var leftLeft = opCtx.prevTerms[0] && opCtx.prevTerms[0].isPartial ? opCtx.prevTerms[0] : null; + var unopTerm = PartialOperation.create(head, leftLeft); + var unopPrevStx = tagWithTerm(unopTerm, head.destruct().reverse()).concat(opCtx.prevStx); + var unopPrevTerms = [unopTerm].concat(opCtx.prevTerms); + var unopOpCtx = _.extend({}, opCtx, { + combine: function (t) { + if (t.isExpr) { + if (isCustomOp && uopMacroObj.unary) { + var rt$2 = expandMacro(uopMacroName.concat(t.destruct()), context, opCtx, 'unary'); + var newt = get_expression(rt$2.result, context); + assert(newt.rest.length === 0, 'should never have left over syntax'); + return opCtx.combine(newt.result); + } + return opCtx.combine(UnaryOp.create(uopSyntax, t)); + } else { + // not actually an expression so don't create + // a UnaryOp term just return with the punctuator + return opCtx.combine(head); + } + }, + prec: uopPrec, + prevStx: unopPrevStx, + prevTerms: unopPrevTerms, + op: unopTerm + }); + return step(opRest[0], opRest.slice(1), unopOpCtx); + } // BinOp + else if (head.isExpr && (rest[0] && rest[1] && (stxIsBinOp(rest[0]) && !bopMacroObj || bopMacroObj && bopMacroObj.isOp && bopMacroObj.binary))) { + var opRes; + var op = rest[0]; + var left = head; + var rightStx = rest.slice(1); + var leftLeft = opCtx.prevTerms[0] && opCtx.prevTerms[0].isPartial ? opCtx.prevTerms[0] : null; + var leftTerm = PartialExpression.create(head.destruct(), leftLeft, function () { + return step(head, [], opCtx); + }); + var opTerm = PartialOperation.create(op, leftTerm); + var opPrevStx = tagWithTerm(opTerm, [rest[0]]).concat(tagWithTerm(leftTerm, head.destruct()).reverse(), opCtx.prevStx); + var opPrevTerms = [ + opTerm, + leftTerm + ].concat(opCtx.prevTerms); + var isCustomOp = bopMacroObj && bopMacroObj.isOp && bopMacroObj.binary; + var bopPrec; + var bopAssoc; + if (isCustomOp && bopMacroObj.binary) { + bopPrec = bopMacroObj.binary.prec; + bopAssoc = bopMacroObj.binary.assoc; + } else { + bopPrec = getBinaryOpPrec(unwrapSyntax(op)); + bopAssoc = getBinaryOpAssoc(unwrapSyntax(op)); + } + assert(bopPrec !== undefined, 'expecting a precedence for operator: ' + op); + var newStack; + if (comparePrec(bopPrec, opCtx.prec, bopAssoc)) { + var bopCtx = opCtx; + var combResult = opCtx.combine(head); + if (opCtx.stack.length > 0) { + return step(combResult.term, rest, opCtx.stack[0]); + } + left = combResult.term; + newStack = opCtx.stack; + opPrevStx = combResult.prevStx; + opPrevTerms = combResult.prevTerms; + } else { + newStack = [opCtx].concat(opCtx.stack); + } + assert(opCtx.combine !== undefined, 'expecting a combine function'); + var opRightStx = rightStx; + var bopMacroName; + if (isCustomOp) { + bopMacroName = rest.slice(0, bopMacroObj.fullName.length); + opRightStx = rightStx.slice(bopMacroObj.fullName.length - 1); + } + var bopOpCtx = _.extend({}, opCtx, { + combine: function (right) { + if (right.isExpr) { + if (isCustomOp && bopMacroObj.binary) { + var leftStx = left.destruct(); + var rightStx$2 = right.destruct(); + var rt$2 = expandMacro(bopMacroName.concat(syn.makeDelim('()', leftStx, leftStx[0]), syn.makeDelim('()', rightStx$2, rightStx$2[0])), context, opCtx, 'binary'); + var newt = get_expression(rt$2.result, context); + assert(newt.rest.length === 0, 'should never have left over syntax'); + return { + term: newt.result, + prevStx: opPrevStx, + prevTerms: opPrevTerms + }; + } + return { + term: BinOp.create(left, op, right), + prevStx: opPrevStx, + prevTerms: opPrevTerms + }; + } else { + return { + term: head, + prevStx: opPrevStx, + prevTerms: opPrevTerms + }; + } + }, + prec: bopPrec, + op: opTerm, + stack: newStack, + prevStx: opPrevStx, + prevTerms: opPrevTerms + }); + return step(opRightStx[0], opRightStx.slice(1), bopOpCtx); + } // Call + else if (head.isExpr && (rest[0] && rest[0].token.type === parser.Token.Delimiter && rest[0].token.value === '()')) { + var parenRes = enforestParenExpression(rest[0], context); + if (parenRes) { + return step(Call.create(head, parenRes), rest.slice(1), opCtx); + } + } // Conditional ( x ? true : false) + else if (head.isExpr && (rest[0] && resolveFast(rest[0], context.env) === '?')) { + var question = rest[0]; + var condRes = enforest(rest.slice(1), context); + if (condRes.result) { + var truExpr = condRes.result; + var condRight = condRes.rest; + if (truExpr.isExpr && condRight[0] && resolveFast(condRight[0], context.env) === ':') { + var colon = condRight[0]; + var flsRes = enforest(condRight.slice(1), context); + var flsExpr = flsRes.result; + if (flsExpr.isExpr) { + return step(ConditionalExpression.create(head, question, truExpr, colon, flsExpr), flsRes.rest, opCtx); + } + } + } + } // Arrow functions with expression bodies + else if (head.isDelimiter && head.delim.token.value === '()' && rest[0] && rest[0].token.type === parser.Token.Punctuator && resolveFast(rest[0], context.env) === '=>') { + var arrowRes = enforest(rest.slice(1), context); + if (arrowRes.result && arrowRes.result.isExpr) { + return step(ArrowFun.create(head.delim, rest[0], arrowRes.result.destruct()), arrowRes.rest, opCtx); + } else { + throwSyntaxError('enforest', 'Body of arrow function must be an expression', rest.slice(1)); + } + } // Arrow functions with expression bodies + else if (head.isId && rest[0] && rest[0].token.type === parser.Token.Punctuator && resolveFast(rest[0], context.env) === '=>') { + var res = enforest(rest.slice(1), context); + if (res.result && res.result.isExpr) { + return step(ArrowFun.create(head.id, rest[0], res.result.destruct()), res.rest, opCtx); + } else { + throwSyntaxError('enforest', 'Body of arrow function must be an expression', rest.slice(1)); + } + } // ParenExpr + else if (head.isDelimiter && head.delim.token.value === '()') { + // empty parens are acceptable but enforest + // doesn't accept empty arrays so short + // circuit here + if (head.delim.token.inner.length === 0) { + return step(ParenExpression.create([Empty.create()], head.delim.expose(), []), rest, opCtx); + } else { + var parenRes = enforestParenExpression(head.delim, context); + if (parenRes) { + return step(parenRes, rest, opCtx); + } + } + } // AssignmentExpression + else if (head.isExpr && ((head.isId || head.isObjGet || head.isObjDotGet || head.isThisExpression) && rest[0] && rest[1] && !bopMacroObj && stxIsAssignOp(rest[0]))) { + var opRes = enforestAssignment(rest, context, head, prevStx, prevTerms); + if (opRes && opRes.result) { + return step(opRes.result, opRes.rest, _.extend({}, opCtx, { + prevStx: opRes.prevStx, + prevTerms: opRes.prevTerms + })); + } + } // Postfix + else if (head.isExpr && (rest[0] && (unwrapSyntax(rest[0]) === '++' || unwrapSyntax(rest[0]) === '--'))) { + // Check if the operator is a macro first. + if (context.env.has(resolveFast(rest[0], context.env))) { + var headStx = tagWithTerm(head, head.destruct().reverse()); + var opPrevStx = headStx.concat(prevStx); + var opPrevTerms = [head].concat(prevTerms); + var opRes = enforest(rest, context, opPrevStx, opPrevTerms); + if (opRes.prevTerms.length < opPrevTerms.length) { + return opRes; + } else if (opRes.result) { + return step(head, opRes.result.destruct().concat(opRes.rest), opCtx); + } + } + return step(PostfixOp.create(head, rest[0]), rest.slice(1), opCtx); + } // ObjectGet (computed) + else if (head.isExpr && (rest[0] && rest[0].token.value === '[]')) { + return step(ObjGet.create(head, Delimiter.create(rest[0].expose())), rest.slice(1), opCtx); + } // ObjectGet + else if (head.isExpr && (rest[0] && unwrapSyntax(rest[0]) === '.' && !context.env.has(resolveFast(rest[0], context.env)) && rest[1] && (rest[1].token.type === parser.Token.Identifier || rest[1].token.type === parser.Token.Keyword))) { + // Check if the identifier is a macro first. + if (context.env.has(resolveFast(rest[1], context.env))) { + var headStx = tagWithTerm(head, head.destruct().reverse()); + var dotTerm = Punc.create(rest[0]); + var dotTerms = [dotTerm].concat(head, prevTerms); + var dotStx = tagWithTerm(dotTerm, [rest[0]]).concat(headStx, prevStx); + var dotRes = enforest(rest.slice(1), context, dotStx, dotTerms); + if (dotRes.prevTerms.length < dotTerms.length) { + return dotRes; + } else if (dotRes.result) { + return step(head, [rest[0]].concat(dotRes.result.destruct(), dotRes.rest), opCtx); + } + } + return step(ObjDotGet.create(head, rest[0], rest[1]), rest.slice(2), opCtx); + } // ArrayLiteral + else if (head.isDelimiter && head.delim.token.value === '[]') { + return step(ArrayLiteral.create(head), rest, opCtx); + } // Block + else if (head.isDelimiter && head.delim.token.value === '{}') { + return step(Block.create(head), rest, opCtx); + } // quote syntax + else if (head.isId && unwrapSyntax(head.id) === '#quoteSyntax' && rest[0] && rest[0].token.value === '{}') { + var tempId = fresh(); + context.templateMap.set(tempId, rest[0].token.inner); + return step(syn.makeIdent('getTemplate', head.id), [syn.makeDelim('()', [syn.makeValue(tempId, head.id)], head.id)].concat(rest.slice(1)), opCtx); + } // return statement + else if (head.isKeyword && unwrapSyntax(head.keyword) === 'return') { + if (rest[0]) { + var returnPrevStx = tagWithTerm(head, head.destruct()).concat(opCtx.prevStx); + var returnPrevTerms = [head].concat(opCtx.prevTerms); + var returnExpr = enforest(rest, context, returnPrevStx, returnPrevTerms); + if (returnExpr.prevTerms.length < opCtx.prevTerms.length) { + return returnExpr; + } + if (returnExpr.result.isExpr) { + return step(ReturnStatement.create(head, returnExpr.result), returnExpr.rest, opCtx); + } + } + } // let statements + else if (head.isKeyword && unwrapSyntax(head.keyword) === 'let') { + var nameTokens = []; + if (rest[0] && rest[0].token.type === parser.Token.Delimiter && rest[0].token.value === '()') { + nameTokens = rest[0].token.inner; + } else { + nameTokens.push(rest[0]); + } + // Let macro + if (rest[1] && rest[1].token.value === '=' && rest[2] && rest[2].token.value === 'macro') { + var mac = enforest(rest.slice(2), context); + if (mac.result) { + if (!mac.result.isAnonMacro) { + throwSyntaxError('enforest', 'expecting an anonymous macro definition in syntax let binding', rest.slice(2)); + } + return step(LetMacro.create(nameTokens, mac.result.body), mac.rest, opCtx); + } + } // Let statement + else { + var lsRes = enforestVarStatement(rest, context, head.keyword); + if (lsRes && lsRes.result) { + return step(LetStatement.create(head, lsRes.result), lsRes.rest, opCtx); + } + } + } // VariableStatement + else if (head.isKeyword && unwrapSyntax(head.keyword) === 'var' && rest[0]) { + var vsRes = enforestVarStatement(rest, context, head.keyword); + if (vsRes && vsRes.result) { + return step(VariableStatement.create(head, vsRes.result), vsRes.rest, opCtx); + } + } // Const Statement + else if (head.isKeyword && unwrapSyntax(head.keyword) === 'const' && rest[0]) { + var csRes = enforestVarStatement(rest, context, head.keyword); + if (csRes && csRes.result) { + return step(ConstStatement.create(head, csRes.result), csRes.rest, opCtx); + } + } // for statement + else if (head.isKeyword && unwrapSyntax(head.keyword) === 'for' && rest[0] && rest[0].token.value === '()') { + return step(ForStatement.create(head.keyword, rest[0]), rest.slice(1), opCtx); + } + } else { + assert(head && head.token, 'assuming head is a syntax object'); + var macroObj = expandCount < maxExpands && getMacroInEnv(head, rest, context.env); + // macro invocation + if (macroObj && !macroObj.isOp) { + var rt = expandMacro([head].concat(rest), context, opCtx, null, macroObj); + var newOpCtx = opCtx; + if (rt.prevTerms && rt.prevTerms.length < opCtx.prevTerms.length) { + newOpCtx = rewindOpCtx(opCtx, rt); + } + if (rt.result.length > 0) { + return step(rt.result[0], rt.result.slice(1).concat(rt.rest), newOpCtx); + } else { + return step(Empty.create(), rt.rest, newOpCtx); + } + } // anon macro definition + else if (head.token.type === parser.Token.Identifier && resolve(head) === 'macro' && rest[0] && rest[0].token.value === '{}') { + return step(AnonMacro.create(rest[0].expose().token.inner), rest.slice(1), opCtx); + } // macro definition + else if (head.token.type === parser.Token.Identifier && resolve(head) === 'macro') { + var nameTokens = []; + if (rest[0] && rest[0].token.type === parser.Token.Delimiter && rest[0].token.value === '()') { + nameTokens = rest[0].expose().token.inner; + } else { + nameTokens.push(rest[0]); + } + if (rest[1] && rest[1].token.type === parser.Token.Delimiter) { + return step(Macro.create(nameTokens, rest[1].expose().token.inner), rest.slice(2), opCtx); + } else { + throwSyntaxError('enforest', 'Macro declaration must include body', rest[1]); + } + } // operator definition + // unaryop (neg) 1 { macro { rule { $op:expr } => { $op } } } + else if (head.token.type === parser.Token.Identifier && head.token.value === 'unaryop' && rest[0] && rest[0].token.type === parser.Token.Delimiter && rest[0].token.value === '()' && rest[1] && rest[1].token.type === parser.Token.NumericLiteral && rest[2] && rest[2].token.type === parser.Token.Delimiter && rest[2] && rest[2].token.value === '{}') { + var trans = enforest(rest[2].expose().token.inner, context); + return step(OperatorDefinition.create('unary', rest[0].expose().token.inner, rest[1], null, trans.result.body), rest.slice(3), opCtx); + } // operator definition + // binaryop (neg) 1 left { macro { rule { $op:expr } => { $op } } } + else if (head.token.type === parser.Token.Identifier && head.token.value === 'binaryop' && rest[0] && rest[0].token.type === parser.Token.Delimiter && rest[0].token.value === '()' && rest[1] && rest[1].token.type === parser.Token.NumericLiteral && rest[2] && rest[2].token.type === parser.Token.Identifier && rest[3] && rest[3].token.type === parser.Token.Delimiter && rest[3] && rest[3].token.value === '{}') { + var trans = enforest(rest[3].expose().token.inner, context); + return step(OperatorDefinition.create('binary', rest[0].expose().token.inner, rest[1], rest[2], trans.result.body), rest.slice(4), opCtx); + } // module definition + else if (unwrapSyntax(head) === 'module' && rest[0] && rest[0].token.value === '{}') { + return step(Module.create(rest[0], []), rest.slice(1), opCtx); + } // function definition + else if (head.token.type === parser.Token.Keyword && unwrapSyntax(head) === 'function' && rest[0] && rest[0].token.type === parser.Token.Identifier && rest[1] && rest[1].token.type === parser.Token.Delimiter && rest[1].token.value === '()' && rest[2] && rest[2].token.type === parser.Token.Delimiter && rest[2].token.value === '{}') { + rest[1].token.inner = rest[1].expose().token.inner; + rest[2].token.inner = rest[2].expose().token.inner; + return step(NamedFun.create(head, null, rest[0], rest[1], rest[2]), rest.slice(3), opCtx); + } // generator function definition + else if (head.token.type === parser.Token.Keyword && unwrapSyntax(head) === 'function' && rest[0] && rest[0].token.type === parser.Token.Punctuator && rest[0].token.value === '*' && rest[1] && rest[1].token.type === parser.Token.Identifier && rest[2] && rest[2].token.type === parser.Token.Delimiter && rest[2].token.value === '()' && rest[3] && rest[3].token.type === parser.Token.Delimiter && rest[3].token.value === '{}') { + rest[2].token.inner = rest[2].expose().token.inner; + rest[3].token.inner = rest[3].expose().token.inner; + return step(NamedFun.create(head, rest[0], rest[1], rest[2], rest[3]), rest.slice(4), opCtx); + } // anonymous function definition + else if (head.token.type === parser.Token.Keyword && unwrapSyntax(head) === 'function' && rest[0] && rest[0].token.type === parser.Token.Delimiter && rest[0].token.value === '()' && rest[1] && rest[1].token.type === parser.Token.Delimiter && rest[1].token.value === '{}') { + rest[0].token.inner = rest[0].expose().token.inner; + rest[1].token.inner = rest[1].expose().token.inner; + return step(AnonFun.create(head, null, rest[0], rest[1]), rest.slice(2), opCtx); + } // anonymous generator function definition + else if (head.token.type === parser.Token.Keyword && unwrapSyntax(head) === 'function' && rest[0] && rest[0].token.type === parser.Token.Punctuator && rest[0].token.value === '*' && rest[1] && rest[1].token.type === parser.Token.Delimiter && rest[1].token.value === '()' && rest[2] && rest[2].token.type === parser.Token.Delimiter && rest[2].token.value === '{}') { + rest[1].token.inner = rest[1].expose().token.inner; + rest[2].token.inner = rest[2].expose().token.inner; + return step(AnonFun.create(head, rest[0], rest[1], rest[2]), rest.slice(3), opCtx); + } // arrow function + else if ((head.token.type === parser.Token.Delimiter && head.token.value === '()' || head.token.type === parser.Token.Identifier) && rest[0] && rest[0].token.type === parser.Token.Punctuator && resolveFast(rest[0], context.env) === '=>' && rest[1] && rest[1].token.type === parser.Token.Delimiter && rest[1].token.value === '{}') { + return step(ArrowFun.create(head, rest[0], rest[1]), rest.slice(2), opCtx); + } // catch statement + else if (head.token.type === parser.Token.Keyword && unwrapSyntax(head) === 'catch' && rest[0] && rest[0].token.type === parser.Token.Delimiter && rest[0].token.value === '()' && rest[1] && rest[1].token.type === parser.Token.Delimiter && rest[1].token.value === '{}') { + rest[0].token.inner = rest[0].expose().token.inner; + rest[1].token.inner = rest[1].expose().token.inner; + return step(CatchClause.create(head, rest[0], rest[1]), rest.slice(2), opCtx); + } // this expression + else if (head.token.type === parser.Token.Keyword && unwrapSyntax(head) === 'this') { + return step(ThisExpression.create(head), rest, opCtx); + } // literal + else if (head.token.type === parser.Token.NumericLiteral || head.token.type === parser.Token.StringLiteral || head.token.type === parser.Token.BooleanLiteral || head.token.type === parser.Token.RegularExpression || head.token.type === parser.Token.NullLiteral) { + return step(Lit.create(head), rest, opCtx); + } // export + else if (head.token.type === parser.Token.Keyword && unwrapSyntax(head) === 'export' && rest[0] && (rest[0].token.type === parser.Token.Identifier || rest[0].token.type === parser.Token.Keyword || rest[0].token.type === parser.Token.Punctuator || rest[0].token.type === parser.Token.Delimiter && rest[0].token.value === '()')) { + // Consume optional semicolon + if (unwrapSyntax(rest[1]) === ';') { + rest.splice(1, 1); + } + return step(Export.create(rest[0]), rest.slice(1), opCtx); + } // identifier + else if (head.token.type === parser.Token.Identifier) { + return step(Id.create(head), rest, opCtx); + } // punctuator + else if (head.token.type === parser.Token.Punctuator) { + return step(Punc.create(head), rest, opCtx); + } else if (head.token.type === parser.Token.Keyword && unwrapSyntax(head) === 'with') { + throwSyntaxError('enforest', 'with is not supported in sweet.js', head); + } // keyword + else if (head.token.type === parser.Token.Keyword) { + return step(Keyword.create(head), rest, opCtx); + } // Delimiter + else if (head.token.type === parser.Token.Delimiter) { + return step(Delimiter.create(head.expose()), rest, opCtx); + } else if (head.token.type === parser.Token.Template) { + return step(Template.create(head), rest, opCtx); + } // end of file + else if (head.token.type === parser.Token.EOF) { + assert(rest.length === 0, 'nothing should be after an EOF'); + return step(EOF.create(head), [], opCtx); + } else { + // todo: are we missing cases? + assert(false, 'not implemented'); + } + } + // Potentially an infix macro + // This should only be invoked on runtime syntax terms + if (!head.isMacro && !head.isLetMacro && !head.isAnonMacro && !head.isOperatorDefinition && rest.length && nameInEnv(rest[0], rest.slice(1), context.env)) { + var infLeftTerm = opCtx.prevTerms[0] && opCtx.prevTerms[0].isPartial ? opCtx.prevTerms[0] : null; + var infTerm = PartialExpression.create(head.destruct(), infLeftTerm, function () { + return step(head, [], opCtx); + }); + var infPrevStx = tagWithTerm(infTerm, head.destruct()).reverse().concat(opCtx.prevStx); + var infPrevTerms = [infTerm].concat(opCtx.prevTerms); + var infRes = expandMacro(rest, context, { + prevStx: infPrevStx, + prevTerms: infPrevTerms + }); + if (infRes.prevTerms && infRes.prevTerms.length < infPrevTerms.length) { + var infOpCtx = rewindOpCtx(opCtx, infRes); + return step(infRes.result[0], infRes.result.slice(1).concat(infRes.rest), infOpCtx); + } else { + return step(head, infRes.result.concat(infRes.rest), opCtx); + } + } + // done with current step so combine and continue on + var combResult = opCtx.combine(head); + if (opCtx.stack.length === 0) { + return { + result: combResult.term, + rest: rest, + prevStx: combResult.prevStx, + prevTerms: combResult.prevTerms + }; + } else { + return step(combResult.term, rest, opCtx.stack[0]); + } + } + return step(toks[0], toks.slice(1), { + combine: function (t) { + return { + term: t, + prevStx: prevStx, + prevTerms: prevTerms + }; + }, + prec: 0, + stack: [], + op: null, + prevStx: prevStx, + prevTerms: prevTerms + }); + } + function rewindOpCtx(opCtx, res) { + // If we've consumed all pending operators, we can just start over. + // It's important that we always thread the new prevStx and prevTerms + // through, otherwise the old ones will still persist. + if (!res.prevTerms.length || !res.prevTerms[0].isPartial) { + return _.extend({}, opCtx, { + combine: function (t) { + return { + term: t, + prevStx: res.prevStx, + prevTerms: res.prevTerms + }; + }, + prec: 0, + op: null, + stack: [], + prevStx: res.prevStx, + prevTerms: res.prevTerms + }); + } + // To rewind, we need to find the first (previous) pending operator. It + // acts as a marker in the opCtx to let us know how far we need to go + // back. + var op = null; + for (var i = 0; i < res.prevTerms.length; i++) { + if (!res.prevTerms[i].isPartial) { + break; + } + if (res.prevTerms[i].isPartialOperation) { + op = res.prevTerms[i]; + break; + } + } + // If the op matches the current opCtx, we don't need to rewind + // anything, but we still need to persist the prevStx and prevTerms. + if (opCtx.op === op) { + return _.extend({}, opCtx, { + prevStx: res.prevStx, + prevTerms: res.prevTerms + }); + } + for (var i = 0; i < opCtx.stack.length; i++) { + if (opCtx.stack[i].op === op) { + return _.extend({}, opCtx.stack[i], { + prevStx: res.prevStx, + prevTerms: res.prevTerms + }); + } + } + assert(false, 'Rewind failed.'); + } + function get_expression(stx, context) { + if (stx[0].term) { + for (var termLen = 1; termLen < stx.length; termLen++) { + if (stx[termLen].term !== stx[0].term) { + break; + } + } + // Guard the termLen because we can have a multi-token term that + // we don't want to split. TODO: is there something we can do to + // get around this safely? + if (stx[0].term.isPartialExpression && termLen === stx[0].term.stx.length) { + var expr = stx[0].term.combine().result; + for (var i = 1, term = stx[0].term; i < stx.length; i++) { + if (stx[i].term !== term) { + if (term && term.isPartial) { + term = term.left; + i--; + } else { + break; + } + } + } + return { + result: expr, + rest: stx.slice(i) + }; + } else if (stx[0].term.isExpr) { + return { + result: stx[0].term, + rest: stx.slice(termLen) + }; + } else { + return { + result: null, + rest: stx + }; + } + } + var res = enforest(stx, context); + if (!res.result || !res.result.isExpr) { + return { + result: null, + rest: stx + }; + } + return res; + } + function tagWithTerm(term, stx) { + return stx.map(function (s) { + var src = s.token; + var keys = Object.keys(src); + var newtok = {}; + for (var i = 0, len = keys.length, key; i < len; i++) { + key = keys[i]; + newtok[key] = src[key]; + } + s = syntaxFromToken(newtok, s); + s.term = term; + return s; + }); + } + // mark each syntax object in the pattern environment, + // mutating the environment + function applyMarkToPatternEnv(newMark, env) { + /* + Takes a `match` object: + + { + level: , + match: [ or ] + } + + where the match property is an array of syntax objects at the bottom (0) level. + Does a depth-first search and applys the mark to each syntax object. + */ + function dfs(match) { + if (match.level === 0) { + // replace the match property with the marked syntax + match.match = _.map(match.match, function (stx) { + return stx.mark(newMark); + }); + } else { + _.each(match.match, function (match$2) { + dfs(match$2); + }); + } + } + _.keys(env).forEach(function (key) { + dfs(env[key]); + }); + } + // given the syntax for a macro, produce a macro transformer + // (Macro) -> (([...CSyntax]) -> ReadTree) + function loadMacroDef(body, context) { + // raw function primitive form + if (!(body[0] && body[0].token.type === parser.Token.Keyword && body[0].token.value === 'function')) { + throwSyntaxError('load macro', 'Primitive macro form must contain a function for the macro body', body); + } + var stub = parser.read('()'); + stub[0].token.inner = body; + var expanded = expand(stub, context); + expanded = expanded[0].destruct().concat(expanded[1].eof); + var flattend = flatten(expanded); + var bodyCode = codegen.generate(parser.parse(flattend)); + var macroFn = scopedEval(bodyCode, { + makeValue: syn.makeValue, + makeRegex: syn.makeRegex, + makeIdent: syn.makeIdent, + makeKeyword: syn.makeKeyword, + makePunc: syn.makePunc, + makeDelim: syn.makeDelim, + require: function (id) { + if (context.requireModule) { + return context.requireModule(id, context.filename); + } + return require(id); + }, + getExpr: function (stx) { + var r; + if (stx.length === 0) { + return { + success: false, + result: [], + rest: [] + }; + } + r = get_expression(stx, context); + return { + success: r.result !== null, + result: r.result === null ? [] : r.result.destruct(), + rest: r.rest + }; + }, + getIdent: function (stx) { + if (stx[0] && stx[0].token.type === parser.Token.Identifier) { + return { + success: true, + result: [stx[0]], + rest: stx.slice(1) + }; + } + return { + success: false, + result: [], + rest: stx + }; + }, + getLit: function (stx) { + if (stx[0] && patternModule.typeIsLiteral(stx[0].token.type)) { + return { + success: true, + result: [stx[0]], + rest: stx.slice(1) + }; + } + return { + success: false, + result: [], + rest: stx + }; + }, + unwrapSyntax: syn.unwrapSyntax, + throwSyntaxError: throwSyntaxError, + throwSyntaxCaseError: throwSyntaxCaseError, + prettyPrint: syn.prettyPrint, + parser: parser, + __fresh: fresh, + _: _, + patternModule: patternModule, + getPattern: function (id) { + return context.patternMap.get(id); + }, + getTemplate: function (id) { + return syn.cloneSyntaxArray(context.templateMap.get(id)); + }, + applyMarkToPatternEnv: applyMarkToPatternEnv, + mergeMatches: function (newMatch, oldMatch) { + newMatch.patternEnv = _.extend({}, oldMatch.patternEnv, newMatch.patternEnv); + return newMatch; + } + }); + return macroFn; + } + // similar to `parse1` in the honu paper + // ([Syntax], Map) -> {terms: [TermTree], env: Map} + function expandToTermTree(stx, context) { + assert(context, 'expander context is required'); + var f, head, prevStx, restStx, prevTerms, macroDefinition; + var rest = stx; + while (rest.length > 0) { + assert(rest[0].token, 'expecting a syntax object'); + f = enforest(rest, context, prevStx, prevTerms); + // head :: TermTree + head = f.result; + // rest :: [Syntax] + rest = f.rest; + if (!head) { + // no head means the expansions stopped prematurely (for stepping) + restStx = rest; + break; + } + if (head.isMacro && expandCount < maxExpands) { + // load the macro definition into the environment and continue expanding + macroDefinition = loadMacroDef(head.body, context); + var name = head.name.map(unwrapSyntax).join(''); + var nameStx = syn.makeIdent(name, head.name[0]); + addToDefinitionCtx([nameStx], context.defscope, false, context.paramscope); + context.env.names.set(name, true); + context.env.set(resolve(nameStx), { + fn: macroDefinition, + isOp: false, + builtin: builtinMode, + fullName: head.name + }); + continue; + } + if (head.isLetMacro && expandCount < maxExpands) { + // load the macro definition into the environment and continue expanding + macroDefinition = loadMacroDef(head.body, context); + var freshName = fresh(); + var name = head.name.map(unwrapSyntax).join(''); + var nameStx = syn.makeIdent(name, head.name[0]); + var renamedName = nameStx.rename(nameStx, freshName); + rest = _.map(rest, function (stx$2) { + return stx$2.rename(nameStx, freshName); + }); + context.env.names.set(name, true); + context.env.set(resolve(renamedName), { + fn: macroDefinition, + isOp: false, + builtin: builtinMode, + fullName: head.name + }); + continue; + } + if (head.isOperatorDefinition) { + var opDefinition = loadMacroDef(head.body, context); + var name = head.name.map(unwrapSyntax).join(''); + var nameStx = syn.makeIdent(name, head.name[0]); + addToDefinitionCtx([nameStx], context.defscope, false, context.paramscope); + var resolvedName = resolve(nameStx); + var opObj = context.env.get(resolvedName); + if (!opObj) { + opObj = { + isOp: true, + builtin: builtinMode, + fullName: head.name + }; + } + assert(head.type === 'binary' || head.type === 'unary', 'operator must either be binary or unary'); + opObj[head.type] = { + fn: opDefinition, + prec: head.prec.token.value, + assoc: head.assoc ? head.assoc.token.value : null + }; + context.env.names.set(name, true); + context.env.set(resolvedName, opObj); + continue; + } + // We build the newPrevTerms/Stx here (instead of at the beginning) so + // that macro definitions don't get added to it. + var destructed = tagWithTerm(head, f.result.destruct()); + prevTerms = [head].concat(f.prevTerms); + prevStx = destructed.reverse().concat(f.prevStx); + if (head.isNamedFun) { + addToDefinitionCtx([head.name], context.defscope, true, context.paramscope); + } + if (head.isVariableStatement || head.isLetStatement || head.isConstStatement) { + addToDefinitionCtx(_.map(head.decls, function (decl) { + return decl.ident; + }), context.defscope, true, context.paramscope); + } + if (head.isBlock && head.body.isDelimiter) { + head.body.delim.token.inner.forEach(function (term) { + if (term.isVariableStatement) { + addToDefinitionCtx(_.map(term.decls, function (decl) { + return decl.ident; + }), context.defscope, true, context.paramscope); + } + }); + } + if (head.isDelimiter) { + head.delim.token.inner.forEach(function (term) { + if (term.isVariableStatement) { + addToDefinitionCtx(_.map(term.decls, function (decl) { + return decl.ident; + }), context.defscope, true, context.paramscope); + } + }); + } + if (head.isForStatement) { + head.cond.expose(); + var forCond = head.cond.token.inner; + if (forCond[0] && resolve(forCond[0]) === 'let' && forCond[1] && forCond[1].token.type === parser.Token.Identifier) { + var letNew = fresh(); + var letId = forCond[1]; + forCond = forCond.map(function (stx$2) { + return stx$2.rename(letId, letNew); + }); + // hack: we want to do the let renaming here, not + // in the expansion of `for (...)` so just remove the `let` + // keyword + head.cond.token.inner = expand([forCond[0]], context).concat(expand(forCond.slice(1), context)); + // nice and easy case: `for (...) { ... }` + if (rest[0] && rest[0].token.value === '{}') { + rest[0] = rest[0].rename(letId, letNew); + } else { + // need to deal with things like `for (...) if (...) log(...)` + var bodyEnf = enforest(rest, context); + var bodyDestructed = bodyEnf.result.destruct(); + var renamedBodyTerm = bodyEnf.result.rename(letId, letNew); + tagWithTerm(renamedBodyTerm, bodyDestructed); + rest = bodyEnf.rest; + prevStx = bodyDestructed.reverse().concat(prevStx); + prevTerms = [renamedBodyTerm].concat(prevTerms); + } + } else { + head.cond.token.inner = expand(head.cond.token.inner, context); + } + } + } + return { + terms: prevTerms ? prevTerms.reverse() : [], + restStx: restStx, + context: context + }; + } + function addToDefinitionCtx(idents, defscope, skipRep, paramscope) { + assert(idents && idents.length > 0, 'expecting some variable identifiers'); + // flag for skipping repeats since we reuse this function to place both + // variables declarations (which need to skip redeclarations) and + // macro definitions which don't + skipRep = skipRep || false; + _.chain(idents).filter(function (id) { + if (skipRep) { + /* + When var declarations repeat in the same function scope: + + var x = 24; + ... + var x = 42; + + we just need to use the first renaming and leave the + definition context as is. + */ + var varDeclRep = _.find(defscope, function (def) { + return def.id.token.value === id.token.value && arraysEqual(marksof(def.id.context), marksof(id.context)); + }); + /* + When var declaration repeat one of the function parameters: + + function foo(x) { + var x; + } + + we don't need to add the var to the definition context. + */ + var paramDeclRep = _.find(paramscope, function (param) { + return param.token.value === id.token.value && arraysEqual(marksof(param.context), marksof(id.context)); + }); + return typeof varDeclRep === 'undefined' && typeof paramDeclRep === 'undefined'; + } + return true; + }).each(function (id) { + var name = fresh(); + defscope.push({ + id: id, + name: name + }); + }); + } + // similar to `parse2` in the honu paper except here we + // don't generate an AST yet + // (TermTree, Map, Map) -> TermTree + function expandTermTreeToFinal(term, context) { + assert(context && context.env, 'environment map is required'); + if (term.isArrayLiteral) { + term.array.delim.token.inner = expand(term.array.delim.expose().token.inner, context); + return term; + } else if (term.isBlock) { + term.body.delim.token.inner = expand(term.body.delim.expose().token.inner, context); + return term; + } else if (term.isParenExpression) { + term.args = _.map(term.args, function (arg) { + return expandTermTreeToFinal(arg, context); + }); + return term; + } else if (term.isCall) { + term.fun = expandTermTreeToFinal(term.fun, context); + term.args = expandTermTreeToFinal(term.args, context); + return term; + } else if (term.isReturnStatement) { + term.expr = expandTermTreeToFinal(term.expr, context); + return term; + } else if (term.isUnaryOp) { + term.expr = expandTermTreeToFinal(term.expr, context); + return term; + } else if (term.isBinOp || term.isAssignmentExpression) { + term.left = expandTermTreeToFinal(term.left, context); + term.right = expandTermTreeToFinal(term.right, context); + return term; + } else if (term.isObjGet) { + term.left = expandTermTreeToFinal(term.left, context); + term.right.delim.token.inner = expand(term.right.delim.expose().token.inner, context); + return term; + } else if (term.isObjDotGet) { + term.left = expandTermTreeToFinal(term.left, context); + term.right = expandTermTreeToFinal(term.right, context); + return term; + } else if (term.isConditionalExpression) { + term.cond = expandTermTreeToFinal(term.cond, context); + term.tru = expandTermTreeToFinal(term.tru, context); + term.fls = expandTermTreeToFinal(term.fls, context); + return term; + } else if (term.isVariableDeclaration) { + if (term.init) { + term.init = expandTermTreeToFinal(term.init, context); + } + return term; + } else if (term.isVariableStatement) { + term.decls = _.map(term.decls, function (decl) { + return expandTermTreeToFinal(decl, context); + }); + return term; + } else if (term.isDelimiter) { + // expand inside the delimiter and then continue on + term.delim.token.inner = expand(term.delim.expose().token.inner, context); + return term; + } else if (term.isNamedFun || term.isAnonFun || term.isCatchClause || term.isArrowFun || term.isModule) { + // function definitions need a bunch of hygiene logic + // push down a fresh definition context + var newDef = []; + var paramSingleIdent = term.params && term.params.token.type === parser.Token.Identifier; + var params; + if (term.params && term.params.token.type === parser.Token.Delimiter) { + params = term.params.expose(); + } else if (paramSingleIdent) { + params = term.params; + } else { + params = syn.makeDelim('()', [], null); + } + var bodies; + if (Array.isArray(term.body)) { + bodies = syn.makeDelim('{}', term.body, null); + } else { + bodies = term.body; + } + bodies = bodies.addDefCtx(newDef); + var paramNames = _.map(getParamIdentifiers(params), function (param) { + var freshName = fresh(); + return { + freshName: freshName, + originalParam: param, + renamedParam: param.rename(param, freshName) + }; + }); + var bodyContext = makeExpanderContext(_.defaults({ + defscope: newDef, + paramscope: paramNames.map(function (p) { + return p.renamedParam; + }) + }, context)); + // rename the function body for each of the parameters + var renamedBody = _.reduce(paramNames, function (accBody, p) { + return accBody.rename(p.originalParam, p.freshName); + }, bodies); + renamedBody = renamedBody.expose(); + var expandedResult = expandToTermTree(renamedBody.token.inner, bodyContext); + var bodyTerms = expandedResult.terms; + if (expandedResult.restStx) { + // The expansion was halted prematurely. Just stop and + // return what we have so far, along with the rest of the syntax + renamedBody.token.inner = expandedResult.terms.concat(expandedResult.restStx); + if (Array.isArray(term.body)) { + term.body = renamedBody.token.inner; + } else { + term.body = renamedBody; + } + return term; + } + var renamedParams = _.map(paramNames, function (p) { + return p.renamedParam; + }); + var flatArgs; + if (paramSingleIdent) { + flatArgs = renamedParams[0]; + } else { + flatArgs = syn.makeDelim('()', joinSyntax(renamedParams, ','), term.params || null); + } + var expandedArgs = expand([flatArgs], bodyContext); + assert(expandedArgs.length === 1, 'should only get back one result'); + // stitch up the function with all the renamings + if (term.params) { + term.params = expandedArgs[0]; + } + bodyTerms = _.map(bodyTerms, function (bodyTerm) { + // add the definition context to the result of + // expansion (this makes sure that syntax objects + // introduced by expansion have the def context) + if (bodyTerm.isBlock) { + // we need to expand blocks before adding the defctx since + // blocks defer macro expansion. + var blockFinal = expandTermTreeToFinal(bodyTerm, expandedResult.context); + return blockFinal.addDefCtx(newDef); + } else { + var termWithCtx = bodyTerm.addDefCtx(newDef); + // finish expansion + return expandTermTreeToFinal(termWithCtx, expandedResult.context); + } + }); + if (term.isModule) { + bodyTerms = _.filter(bodyTerms, function (bodyTerm) { + if (bodyTerm.isExport) { + term.exports.push(bodyTerm); + return false; + } else { + return true; + } + }); + } + renamedBody.token.inner = bodyTerms; + if (Array.isArray(term.body)) { + term.body = renamedBody.token.inner; + } else { + term.body = renamedBody; + } + // and continue expand the rest + return term; + } + // the term is fine as is + return term; + } + // similar to `parse` in the honu paper + // ([Syntax], Map, Map) -> [TermTree] + function expand(stx, context) { + assert(context, 'must provide an expander context'); + var trees = expandToTermTree(stx, context); + var terms = _.map(trees.terms, function (term) { + return expandTermTreeToFinal(term, trees.context); + }); + if (trees.restStx) { + terms.push.apply(terms, trees.restStx); + } + return terms; + } + function makeExpanderContext(o) { + o = o || {}; + var env = o.env || new StringMap(); + if (!env.names) { + env.names = new StringMap(); + } + // read-only but can enumerate + return Object.create(Object.prototype, { + filename: { + value: o.filename, + writable: false, + enumerable: true, + configurable: false + }, + requireModule: { + value: o.requireModule, + writable: false, + enumerable: true, + configurable: false + }, + env: { + value: env, + writable: false, + enumerable: true, + configurable: false + }, + defscope: { + value: o.defscope, + writable: false, + enumerable: true, + configurable: false + }, + paramscope: { + value: o.paramscope, + writable: false, + enumerable: true, + configurable: false + }, + templateMap: { + value: o.templateMap || new StringMap(), + writable: false, + enumerable: true, + configurable: false + }, + patternMap: { + value: o.patternMap || new StringMap(), + writable: false, + enumerable: true, + configurable: false + }, + mark: { + value: o.mark, + writable: false, + enumerable: true, + configurable: false + } + }); + } + function makeTopLevelExpanderContext(options) { + var requireModule = options ? options.requireModule : undefined; + var filename = options ? options.filename : undefined; + return makeExpanderContext({ + filename: filename, + requireModule: requireModule + }); + } + // a hack to make the top level hygiene work out + function expandTopLevel(stx, moduleContexts, options) { + moduleContexts = moduleContexts || []; + maxExpands = (_.isNumber(options) ? options : options && options._maxExpands) || Infinity; + expandCount = 0; + var context = makeTopLevelExpanderContext(options); + var modBody = syn.makeDelim('{}', stx, null); + modBody = _.reduce(moduleContexts, function (acc, mod) { + context.env.extend(mod.env); + context.env.names.extend(mod.env.names); + return loadModuleExports(acc, context.env, mod.exports, mod.env); + }, modBody); + var res = expand([ + syn.makeIdent('module', null), + modBody + ], context); + res = res[0].destruct(); + return flatten(res[0].token.inner); + } + function expandModule(stx, moduleContexts, options) { + moduleContexts = moduleContexts || []; + maxExpands = Infinity; + expandCount = 0; + var context = makeTopLevelExpanderContext(options); + var modBody = syn.makeDelim('{}', stx, null); + modBody = _.reduce(moduleContexts, function (acc, mod) { + context.env.extend(mod.env); + context.env.names.extend(mod.env.names); + return loadModuleExports(acc, context.env, mod.exports, mod.env); + }, modBody); + builtinMode = true; + var moduleRes = expand([ + syn.makeIdent('module', null), + modBody + ], context); + builtinMode = false; + context.exports = _.map(moduleRes[0].exports, function (term) { + var nameStr, name; + if (term.name.token.type === parser.Token.Delimiter) { + nameStr = term.name.token.inner.map(unwrapSyntax).join(''); + name = syn.makeIdent(nameStr, term.name); + } else { + name = term.name; + nameStr = unwrapSyntax(name); + } + return { + oldExport: name, + newParam: syn.makeIdent(nameStr, null) + }; + }); + return context; + } + function loadModuleExports(stx, newEnv, exports$3, oldEnv) { + return _.reduce(exports$3, function (acc, param) { + var newName = fresh(); + var transformer = oldEnv.get(resolve(param.oldExport)); + if (transformer) { + newEnv.set(resolve(param.newParam.rename(param.newParam, newName)), transformer); + return acc.rename(param.newParam, newName); + } else { + return acc; + } + }, stx); + } + // break delimiter tree structure down to flat array of syntax objects + function flatten(stx) { + return _.reduce(stx, function (acc, stx$2) { + if (stx$2.token.type === parser.Token.Delimiter) { + var exposed = stx$2.expose(); + var openParen = syntaxFromToken({ + type: parser.Token.Punctuator, + value: stx$2.token.value[0], + range: stx$2.token.startRange, + sm_range: typeof stx$2.token.sm_startRange == 'undefined' ? stx$2.token.startRange : stx$2.token.sm_startRange, + lineNumber: stx$2.token.startLineNumber, + sm_lineNumber: typeof stx$2.token.sm_startLineNumber == 'undefined' ? stx$2.token.startLineNumber : stx$2.token.sm_startLineNumber, + lineStart: stx$2.token.startLineStart, + sm_lineStart: typeof stx$2.token.sm_startLineStart == 'undefined' ? stx$2.token.startLineStart : stx$2.token.sm_startLineStart + }, exposed); + var closeParen = syntaxFromToken({ + type: parser.Token.Punctuator, + value: stx$2.token.value[1], + range: stx$2.token.endRange, + sm_range: typeof stx$2.token.sm_endRange == 'undefined' ? stx$2.token.endRange : stx$2.token.sm_endRange, + lineNumber: stx$2.token.endLineNumber, + sm_lineNumber: typeof stx$2.token.sm_endLineNumber == 'undefined' ? stx$2.token.endLineNumber : stx$2.token.sm_endLineNumber, + lineStart: stx$2.token.endLineStart, + sm_lineStart: typeof stx$2.token.sm_endLineStart == 'undefined' ? stx$2.token.endLineStart : stx$2.token.sm_endLineStart + }, exposed); + if (stx$2.token.leadingComments) { + openParen.token.leadingComments = stx$2.token.leadingComments; + } + if (stx$2.token.trailingComments) { + openParen.token.trailingComments = stx$2.token.trailingComments; + } + acc.push(openParen); + push.apply(acc, flatten(exposed.token.inner)); + acc.push(closeParen); + return acc; + } + stx$2.token.sm_lineNumber = stx$2.token.sm_lineNumber ? stx$2.token.sm_lineNumber : stx$2.token.lineNumber; + stx$2.token.sm_lineStart = stx$2.token.sm_lineStart ? stx$2.token.sm_lineStart : stx$2.token.lineStart; + stx$2.token.sm_range = stx$2.token.sm_range ? stx$2.token.sm_range : stx$2.token.range; + acc.push(stx$2); + return acc; + }, []); + } + exports$2.StringMap = StringMap; + exports$2.enforest = enforest; + exports$2.expand = expandTopLevel; + exports$2.expandModule = expandModule; + exports$2.resolve = resolve; + exports$2.get_expression = get_expression; + exports$2.getName = getName; + exports$2.getMacroInEnv = getMacroInEnv; + exports$2.nameInEnv = nameInEnv; + exports$2.makeExpanderContext = makeExpanderContext; + exports$2.Expr = Expr; + exports$2.VariableStatement = VariableStatement; + exports$2.tokensToSyntax = syn.tokensToSyntax; + exports$2.syntaxToTokens = syn.syntaxToTokens; +})); +//# sourceMappingURL=expander.js.map \ No newline at end of file diff --git a/editor/scripts/jquery.js b/editor/scripts/jquery.js new file mode 100644 index 0000000..ebc6c18 --- /dev/null +++ b/editor/scripts/jquery.js @@ -0,0 +1,8829 @@ +/*! + * jQuery JavaScript Library v2.0.3 + * http://jquery.com/ + * + * Includes Sizzle.js + * http://sizzlejs.com/ + * + * Copyright 2005, 2013 jQuery Foundation, Inc. and other contributors + * Released under the MIT license + * http://jquery.org/license + * + * Date: 2013-07-03T13:30Z + */ +(function( window, undefined ) { + +// Can't do this because several apps including ASP.NET trace +// the stack via arguments.caller.callee and Firefox dies if +// you try to trace through "use strict" call chains. (#13335) +// Support: Firefox 18+ +//"use strict"; +var + // A central reference to the root jQuery(document) + rootjQuery, + + // The deferred used on DOM ready + readyList, + + // Support: IE9 + // For `typeof xmlNode.method` instead of `xmlNode.method !== undefined` + core_strundefined = typeof undefined, + + // Use the correct document accordingly with window argument (sandbox) + location = window.location, + document = window.document, + docElem = document.documentElement, + + // Map over jQuery in case of overwrite + _jQuery = window.jQuery, + + // Map over the $ in case of overwrite + _$ = window.$, + + // [[Class]] -> type pairs + class2type = {}, + + // List of deleted data cache ids, so we can reuse them + core_deletedIds = [], + + core_version = "2.0.3", + + // Save a reference to some core methods + core_concat = core_deletedIds.concat, + core_push = core_deletedIds.push, + core_slice = core_deletedIds.slice, + core_indexOf = core_deletedIds.indexOf, + core_toString = class2type.toString, + core_hasOwn = class2type.hasOwnProperty, + core_trim = core_version.trim, + + // Define a local copy of jQuery + jQuery = function( selector, context ) { + // The jQuery object is actually just the init constructor 'enhanced' + return new jQuery.fn.init( selector, context, rootjQuery ); + }, + + // Used for matching numbers + core_pnum = /[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source, + + // Used for splitting on whitespace + core_rnotwhite = /\S+/g, + + // A simple way to check for HTML strings + // Prioritize #id over to avoid XSS via location.hash (#9521) + // Strict HTML recognition (#11290: must start with <) + rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/, + + // Match a standalone tag + rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>|)$/, + + // Matches dashed string for camelizing + rmsPrefix = /^-ms-/, + rdashAlpha = /-([\da-z])/gi, + + // Used by jQuery.camelCase as callback to replace() + fcamelCase = function( all, letter ) { + return letter.toUpperCase(); + }, + + // The ready event handler and self cleanup method + completed = function() { + document.removeEventListener( "DOMContentLoaded", completed, false ); + window.removeEventListener( "load", completed, false ); + jQuery.ready(); + }; + +jQuery.fn = jQuery.prototype = { + // The current version of jQuery being used + jquery: core_version, + + constructor: jQuery, + init: function( selector, context, rootjQuery ) { + var match, elem; + + // HANDLE: $(""), $(null), $(undefined), $(false) + if ( !selector ) { + return this; + } + + // Handle HTML strings + if ( typeof selector === "string" ) { + if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) { + // Assume that strings that start and end with <> are HTML and skip the regex check + match = [ null, selector, null ]; + + } else { + match = rquickExpr.exec( selector ); + } + + // Match html or make sure no context is specified for #id + if ( match && (match[1] || !context) ) { + + // HANDLE: $(html) -> $(array) + if ( match[1] ) { + context = context instanceof jQuery ? context[0] : context; + + // scripts is true for back-compat + jQuery.merge( this, jQuery.parseHTML( + match[1], + context && context.nodeType ? context.ownerDocument || context : document, + true + ) ); + + // HANDLE: $(html, props) + if ( rsingleTag.test( match[1] ) && jQuery.isPlainObject( context ) ) { + for ( match in context ) { + // Properties of context are called as methods if possible + if ( jQuery.isFunction( this[ match ] ) ) { + this[ match ]( context[ match ] ); + + // ...and otherwise set as attributes + } else { + this.attr( match, context[ match ] ); + } + } + } + + return this; + + // HANDLE: $(#id) + } else { + elem = document.getElementById( match[2] ); + + // Check parentNode to catch when Blackberry 4.6 returns + // nodes that are no longer in the document #6963 + if ( elem && elem.parentNode ) { + // Inject the element directly into the jQuery object + this.length = 1; + this[0] = elem; + } + + this.context = document; + this.selector = selector; + return this; + } + + // HANDLE: $(expr, $(...)) + } else if ( !context || context.jquery ) { + return ( context || rootjQuery ).find( selector ); + + // HANDLE: $(expr, context) + // (which is just equivalent to: $(context).find(expr) + } else { + return this.constructor( context ).find( selector ); + } + + // HANDLE: $(DOMElement) + } else if ( selector.nodeType ) { + this.context = this[0] = selector; + this.length = 1; + return this; + + // HANDLE: $(function) + // Shortcut for document ready + } else if ( jQuery.isFunction( selector ) ) { + return rootjQuery.ready( selector ); + } + + if ( selector.selector !== undefined ) { + this.selector = selector.selector; + this.context = selector.context; + } + + return jQuery.makeArray( selector, this ); + }, + + // Start with an empty selector + selector: "", + + // The default length of a jQuery object is 0 + length: 0, + + toArray: function() { + return core_slice.call( this ); + }, + + // Get the Nth element in the matched element set OR + // Get the whole matched element set as a clean array + get: function( num ) { + return num == null ? + + // Return a 'clean' array + this.toArray() : + + // Return just the object + ( num < 0 ? this[ this.length + num ] : this[ num ] ); + }, + + // Take an array of elements and push it onto the stack + // (returning the new matched element set) + pushStack: function( elems ) { + + // Build a new jQuery matched element set + var ret = jQuery.merge( this.constructor(), elems ); + + // Add the old object onto the stack (as a reference) + ret.prevObject = this; + ret.context = this.context; + + // Return the newly-formed element set + return ret; + }, + + // Execute a callback for every element in the matched set. + // (You can seed the arguments with an array of args, but this is + // only used internally.) + each: function( callback, args ) { + return jQuery.each( this, callback, args ); + }, + + ready: function( fn ) { + // Add the callback + jQuery.ready.promise().done( fn ); + + return this; + }, + + slice: function() { + return this.pushStack( core_slice.apply( this, arguments ) ); + }, + + first: function() { + return this.eq( 0 ); + }, + + last: function() { + return this.eq( -1 ); + }, + + eq: function( i ) { + var len = this.length, + j = +i + ( i < 0 ? len : 0 ); + return this.pushStack( j >= 0 && j < len ? [ this[j] ] : [] ); + }, + + map: function( callback ) { + return this.pushStack( jQuery.map(this, function( elem, i ) { + return callback.call( elem, i, elem ); + })); + }, + + end: function() { + return this.prevObject || this.constructor(null); + }, + + // For internal use only. + // Behaves like an Array's method, not like a jQuery method. + push: core_push, + sort: [].sort, + splice: [].splice +}; + +// Give the init function the jQuery prototype for later instantiation +jQuery.fn.init.prototype = jQuery.fn; + +jQuery.extend = jQuery.fn.extend = function() { + var options, name, src, copy, copyIsArray, clone, + target = arguments[0] || {}, + i = 1, + length = arguments.length, + deep = false; + + // Handle a deep copy situation + if ( typeof target === "boolean" ) { + deep = target; + target = arguments[1] || {}; + // skip the boolean and the target + i = 2; + } + + // Handle case when target is a string or something (possible in deep copy) + if ( typeof target !== "object" && !jQuery.isFunction(target) ) { + target = {}; + } + + // extend jQuery itself if only one argument is passed + if ( length === i ) { + target = this; + --i; + } + + for ( ; i < length; i++ ) { + // Only deal with non-null/undefined values + if ( (options = arguments[ i ]) != null ) { + // Extend the base object + for ( name in options ) { + src = target[ name ]; + copy = options[ name ]; + + // Prevent never-ending loop + if ( target === copy ) { + continue; + } + + // Recurse if we're merging plain objects or arrays + if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) { + if ( copyIsArray ) { + copyIsArray = false; + clone = src && jQuery.isArray(src) ? src : []; + + } else { + clone = src && jQuery.isPlainObject(src) ? src : {}; + } + + // Never move original objects, clone them + target[ name ] = jQuery.extend( deep, clone, copy ); + + // Don't bring in undefined values + } else if ( copy !== undefined ) { + target[ name ] = copy; + } + } + } + } + + // Return the modified object + return target; +}; + +jQuery.extend({ + // Unique for each copy of jQuery on the page + expando: "jQuery" + ( core_version + Math.random() ).replace( /\D/g, "" ), + + noConflict: function( deep ) { + if ( window.$ === jQuery ) { + window.$ = _$; + } + + if ( deep && window.jQuery === jQuery ) { + window.jQuery = _jQuery; + } + + return jQuery; + }, + + // Is the DOM ready to be used? Set to true once it occurs. + isReady: false, + + // A counter to track how many items to wait for before + // the ready event fires. See #6781 + readyWait: 1, + + // Hold (or release) the ready event + holdReady: function( hold ) { + if ( hold ) { + jQuery.readyWait++; + } else { + jQuery.ready( true ); + } + }, + + // Handle when the DOM is ready + ready: function( wait ) { + + // Abort if there are pending holds or we're already ready + if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) { + return; + } + + // Remember that the DOM is ready + jQuery.isReady = true; + + // If a normal DOM Ready event fired, decrement, and wait if need be + if ( wait !== true && --jQuery.readyWait > 0 ) { + return; + } + + // If there are functions bound, to execute + readyList.resolveWith( document, [ jQuery ] ); + + // Trigger any bound ready events + if ( jQuery.fn.trigger ) { + jQuery( document ).trigger("ready").off("ready"); + } + }, + + // See test/unit/core.js for details concerning isFunction. + // Since version 1.3, DOM methods and functions like alert + // aren't supported. They return false on IE (#2968). + isFunction: function( obj ) { + return jQuery.type(obj) === "function"; + }, + + isArray: Array.isArray, + + isWindow: function( obj ) { + return obj != null && obj === obj.window; + }, + + isNumeric: function( obj ) { + return !isNaN( parseFloat(obj) ) && isFinite( obj ); + }, + + type: function( obj ) { + if ( obj == null ) { + return String( obj ); + } + // Support: Safari <= 5.1 (functionish RegExp) + return typeof obj === "object" || typeof obj === "function" ? + class2type[ core_toString.call(obj) ] || "object" : + typeof obj; + }, + + isPlainObject: function( obj ) { + // Not plain objects: + // - Any object or value whose internal [[Class]] property is not "[object Object]" + // - DOM nodes + // - window + if ( jQuery.type( obj ) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) { + return false; + } + + // Support: Firefox <20 + // The try/catch suppresses exceptions thrown when attempting to access + // the "constructor" property of certain host objects, ie. |window.location| + // https://bugzilla.mozilla.org/show_bug.cgi?id=814622 + try { + if ( obj.constructor && + !core_hasOwn.call( obj.constructor.prototype, "isPrototypeOf" ) ) { + return false; + } + } catch ( e ) { + return false; + } + + // If the function hasn't returned already, we're confident that + // |obj| is a plain object, created by {} or constructed with new Object + return true; + }, + + isEmptyObject: function( obj ) { + var name; + for ( name in obj ) { + return false; + } + return true; + }, + + error: function( msg ) { + throw new Error( msg ); + }, + + // data: string of html + // context (optional): If specified, the fragment will be created in this context, defaults to document + // keepScripts (optional): If true, will include scripts passed in the html string + parseHTML: function( data, context, keepScripts ) { + if ( !data || typeof data !== "string" ) { + return null; + } + if ( typeof context === "boolean" ) { + keepScripts = context; + context = false; + } + context = context || document; + + var parsed = rsingleTag.exec( data ), + scripts = !keepScripts && []; + + // Single tag + if ( parsed ) { + return [ context.createElement( parsed[1] ) ]; + } + + parsed = jQuery.buildFragment( [ data ], context, scripts ); + + if ( scripts ) { + jQuery( scripts ).remove(); + } + + return jQuery.merge( [], parsed.childNodes ); + }, + + parseJSON: JSON.parse, + + // Cross-browser xml parsing + parseXML: function( data ) { + var xml, tmp; + if ( !data || typeof data !== "string" ) { + return null; + } + + // Support: IE9 + try { + tmp = new DOMParser(); + xml = tmp.parseFromString( data , "text/xml" ); + } catch ( e ) { + xml = undefined; + } + + if ( !xml || xml.getElementsByTagName( "parsererror" ).length ) { + jQuery.error( "Invalid XML: " + data ); + } + return xml; + }, + + noop: function() {}, + + // Evaluates a script in a global context + globalEval: function( code ) { + var script, + indirect = eval; + + code = jQuery.trim( code ); + + if ( code ) { + // If the code includes a valid, prologue position + // strict mode pragma, execute code by injecting a + // script tag into the document. + if ( code.indexOf("use strict") === 1 ) { + script = document.createElement("script"); + script.text = code; + document.head.appendChild( script ).parentNode.removeChild( script ); + } else { + // Otherwise, avoid the DOM node creation, insertion + // and removal by using an indirect global eval + indirect( code ); + } + } + }, + + // Convert dashed to camelCase; used by the css and data modules + // Microsoft forgot to hump their vendor prefix (#9572) + camelCase: function( string ) { + return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase ); + }, + + nodeName: function( elem, name ) { + return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase(); + }, + + // args is for internal usage only + each: function( obj, callback, args ) { + var value, + i = 0, + length = obj.length, + isArray = isArraylike( obj ); + + if ( args ) { + if ( isArray ) { + for ( ; i < length; i++ ) { + value = callback.apply( obj[ i ], args ); + + if ( value === false ) { + break; + } + } + } else { + for ( i in obj ) { + value = callback.apply( obj[ i ], args ); + + if ( value === false ) { + break; + } + } + } + + // A special, fast, case for the most common use of each + } else { + if ( isArray ) { + for ( ; i < length; i++ ) { + value = callback.call( obj[ i ], i, obj[ i ] ); + + if ( value === false ) { + break; + } + } + } else { + for ( i in obj ) { + value = callback.call( obj[ i ], i, obj[ i ] ); + + if ( value === false ) { + break; + } + } + } + } + + return obj; + }, + + trim: function( text ) { + return text == null ? "" : core_trim.call( text ); + }, + + // results is for internal usage only + makeArray: function( arr, results ) { + var ret = results || []; + + if ( arr != null ) { + if ( isArraylike( Object(arr) ) ) { + jQuery.merge( ret, + typeof arr === "string" ? + [ arr ] : arr + ); + } else { + core_push.call( ret, arr ); + } + } + + return ret; + }, + + inArray: function( elem, arr, i ) { + return arr == null ? -1 : core_indexOf.call( arr, elem, i ); + }, + + merge: function( first, second ) { + var l = second.length, + i = first.length, + j = 0; + + if ( typeof l === "number" ) { + for ( ; j < l; j++ ) { + first[ i++ ] = second[ j ]; + } + } else { + while ( second[j] !== undefined ) { + first[ i++ ] = second[ j++ ]; + } + } + + first.length = i; + + return first; + }, + + grep: function( elems, callback, inv ) { + var retVal, + ret = [], + i = 0, + length = elems.length; + inv = !!inv; + + // Go through the array, only saving the items + // that pass the validator function + for ( ; i < length; i++ ) { + retVal = !!callback( elems[ i ], i ); + if ( inv !== retVal ) { + ret.push( elems[ i ] ); + } + } + + return ret; + }, + + // arg is for internal usage only + map: function( elems, callback, arg ) { + var value, + i = 0, + length = elems.length, + isArray = isArraylike( elems ), + ret = []; + + // Go through the array, translating each of the items to their + if ( isArray ) { + for ( ; i < length; i++ ) { + value = callback( elems[ i ], i, arg ); + + if ( value != null ) { + ret[ ret.length ] = value; + } + } + + // Go through every key on the object, + } else { + for ( i in elems ) { + value = callback( elems[ i ], i, arg ); + + if ( value != null ) { + ret[ ret.length ] = value; + } + } + } + + // Flatten any nested arrays + return core_concat.apply( [], ret ); + }, + + // A global GUID counter for objects + guid: 1, + + // Bind a function to a context, optionally partially applying any + // arguments. + proxy: function( fn, context ) { + var tmp, args, proxy; + + if ( typeof context === "string" ) { + tmp = fn[ context ]; + context = fn; + fn = tmp; + } + + // Quick check to determine if target is callable, in the spec + // this throws a TypeError, but we will just return undefined. + if ( !jQuery.isFunction( fn ) ) { + return undefined; + } + + // Simulated bind + args = core_slice.call( arguments, 2 ); + proxy = function() { + return fn.apply( context || this, args.concat( core_slice.call( arguments ) ) ); + }; + + // Set the guid of unique handler to the same of original handler, so it can be removed + proxy.guid = fn.guid = fn.guid || jQuery.guid++; + + return proxy; + }, + + // Multifunctional method to get and set values of a collection + // The value/s can optionally be executed if it's a function + access: function( elems, fn, key, value, chainable, emptyGet, raw ) { + var i = 0, + length = elems.length, + bulk = key == null; + + // Sets many values + if ( jQuery.type( key ) === "object" ) { + chainable = true; + for ( i in key ) { + jQuery.access( elems, fn, i, key[i], true, emptyGet, raw ); + } + + // Sets one value + } else if ( value !== undefined ) { + chainable = true; + + if ( !jQuery.isFunction( value ) ) { + raw = true; + } + + if ( bulk ) { + // Bulk operations run against the entire set + if ( raw ) { + fn.call( elems, value ); + fn = null; + + // ...except when executing function values + } else { + bulk = fn; + fn = function( elem, key, value ) { + return bulk.call( jQuery( elem ), value ); + }; + } + } + + if ( fn ) { + for ( ; i < length; i++ ) { + fn( elems[i], key, raw ? value : value.call( elems[i], i, fn( elems[i], key ) ) ); + } + } + } + + return chainable ? + elems : + + // Gets + bulk ? + fn.call( elems ) : + length ? fn( elems[0], key ) : emptyGet; + }, + + now: Date.now, + + // A method for quickly swapping in/out CSS properties to get correct calculations. + // Note: this method belongs to the css module but it's needed here for the support module. + // If support gets modularized, this method should be moved back to the css module. + swap: function( elem, options, callback, args ) { + var ret, name, + old = {}; + + // Remember the old values, and insert the new ones + for ( name in options ) { + old[ name ] = elem.style[ name ]; + elem.style[ name ] = options[ name ]; + } + + ret = callback.apply( elem, args || [] ); + + // Revert the old values + for ( name in options ) { + elem.style[ name ] = old[ name ]; + } + + return ret; + } +}); + +jQuery.ready.promise = function( obj ) { + if ( !readyList ) { + + readyList = jQuery.Deferred(); + + // Catch cases where $(document).ready() is called after the browser event has already occurred. + // we once tried to use readyState "interactive" here, but it caused issues like the one + // discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15 + if ( document.readyState === "complete" ) { + // Handle it asynchronously to allow scripts the opportunity to delay ready + setTimeout( jQuery.ready ); + + } else { + + // Use the handy event callback + document.addEventListener( "DOMContentLoaded", completed, false ); + + // A fallback to window.onload, that will always work + window.addEventListener( "load", completed, false ); + } + } + return readyList.promise( obj ); +}; + +// Populate the class2type map +jQuery.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(i, name) { + class2type[ "[object " + name + "]" ] = name.toLowerCase(); +}); + +function isArraylike( obj ) { + var length = obj.length, + type = jQuery.type( obj ); + + if ( jQuery.isWindow( obj ) ) { + return false; + } + + if ( obj.nodeType === 1 && length ) { + return true; + } + + return type === "array" || type !== "function" && + ( length === 0 || + typeof length === "number" && length > 0 && ( length - 1 ) in obj ); +} + +// All jQuery objects should point back to these +rootjQuery = jQuery(document); +/*! + * Sizzle CSS Selector Engine v1.9.4-pre + * http://sizzlejs.com/ + * + * Copyright 2013 jQuery Foundation, Inc. and other contributors + * Released under the MIT license + * http://jquery.org/license + * + * Date: 2013-06-03 + */ +(function( window, undefined ) { + +var i, + support, + cachedruns, + Expr, + getText, + isXML, + compile, + outermostContext, + sortInput, + + // Local document vars + setDocument, + document, + docElem, + documentIsHTML, + rbuggyQSA, + rbuggyMatches, + matches, + contains, + + // Instance-specific data + expando = "sizzle" + -(new Date()), + preferredDoc = window.document, + dirruns = 0, + done = 0, + classCache = createCache(), + tokenCache = createCache(), + compilerCache = createCache(), + hasDuplicate = false, + sortOrder = function( a, b ) { + if ( a === b ) { + hasDuplicate = true; + return 0; + } + return 0; + }, + + // General-purpose constants + strundefined = typeof undefined, + MAX_NEGATIVE = 1 << 31, + + // Instance methods + hasOwn = ({}).hasOwnProperty, + arr = [], + pop = arr.pop, + push_native = arr.push, + push = arr.push, + slice = arr.slice, + // Use a stripped-down indexOf if we can't use a native one + indexOf = arr.indexOf || function( elem ) { + var i = 0, + len = this.length; + for ( ; i < len; i++ ) { + if ( this[i] === elem ) { + return i; + } + } + return -1; + }, + + booleans = "checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped", + + // Regular expressions + + // Whitespace characters http://www.w3.org/TR/css3-selectors/#whitespace + whitespace = "[\\x20\\t\\r\\n\\f]", + // http://www.w3.org/TR/css3-syntax/#characters + characterEncoding = "(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+", + + // Loosely modeled on CSS identifier characters + // An unquoted value should be a CSS identifier http://www.w3.org/TR/css3-selectors/#attribute-selectors + // Proper syntax: http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier + identifier = characterEncoding.replace( "w", "w#" ), + + // Acceptable operators http://www.w3.org/TR/selectors/#attribute-selectors + attributes = "\\[" + whitespace + "*(" + characterEncoding + ")" + whitespace + + "*(?:([*^$|!~]?=)" + whitespace + "*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|(" + identifier + ")|)|)" + whitespace + "*\\]", + + // Prefer arguments quoted, + // then not containing pseudos/brackets, + // then attribute selectors/non-parenthetical expressions, + // then anything else + // These preferences are here to reduce the number of selectors + // needing tokenize in the PSEUDO preFilter + pseudos = ":(" + characterEncoding + ")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|" + attributes.replace( 3, 8 ) + ")*)|.*)\\)|)", + + // Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter + rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ), + + rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ), + rcombinators = new RegExp( "^" + whitespace + "*([>+~]|" + whitespace + ")" + whitespace + "*" ), + + rsibling = new RegExp( whitespace + "*[+~]" ), + rattributeQuotes = new RegExp( "=" + whitespace + "*([^\\]'\"]*)" + whitespace + "*\\]", "g" ), + + rpseudo = new RegExp( pseudos ), + ridentifier = new RegExp( "^" + identifier + "$" ), + + matchExpr = { + "ID": new RegExp( "^#(" + characterEncoding + ")" ), + "CLASS": new RegExp( "^\\.(" + characterEncoding + ")" ), + "TAG": new RegExp( "^(" + characterEncoding.replace( "w", "w*" ) + ")" ), + "ATTR": new RegExp( "^" + attributes ), + "PSEUDO": new RegExp( "^" + pseudos ), + "CHILD": new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace + + "*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace + + "*(\\d+)|))" + whitespace + "*\\)|)", "i" ), + "bool": new RegExp( "^(?:" + booleans + ")$", "i" ), + // For use in libraries implementing .is() + // We use this for POS matching in `select` + "needsContext": new RegExp( "^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + + whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" ) + }, + + rnative = /^[^{]+\{\s*\[native \w/, + + // Easily-parseable/retrievable ID or TAG or CLASS selectors + rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/, + + rinputs = /^(?:input|select|textarea|button)$/i, + rheader = /^h\d$/i, + + rescape = /'|\\/g, + + // CSS escapes http://www.w3.org/TR/CSS21/syndata.html#escaped-characters + runescape = new RegExp( "\\\\([\\da-f]{1,6}" + whitespace + "?|(" + whitespace + ")|.)", "ig" ), + funescape = function( _, escaped, escapedWhitespace ) { + var high = "0x" + escaped - 0x10000; + // NaN means non-codepoint + // Support: Firefox + // Workaround erroneous numeric interpretation of +"0x" + return high !== high || escapedWhitespace ? + escaped : + // BMP codepoint + high < 0 ? + String.fromCharCode( high + 0x10000 ) : + // Supplemental Plane codepoint (surrogate pair) + String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 ); + }; + +// Optimize for push.apply( _, NodeList ) +try { + push.apply( + (arr = slice.call( preferredDoc.childNodes )), + preferredDoc.childNodes + ); + // Support: Android<4.0 + // Detect silently failing push.apply + arr[ preferredDoc.childNodes.length ].nodeType; +} catch ( e ) { + push = { apply: arr.length ? + + // Leverage slice if possible + function( target, els ) { + push_native.apply( target, slice.call(els) ); + } : + + // Support: IE<9 + // Otherwise append directly + function( target, els ) { + var j = target.length, + i = 0; + // Can't trust NodeList.length + while ( (target[j++] = els[i++]) ) {} + target.length = j - 1; + } + }; +} + +function Sizzle( selector, context, results, seed ) { + var match, elem, m, nodeType, + // QSA vars + i, groups, old, nid, newContext, newSelector; + + if ( ( context ? context.ownerDocument || context : preferredDoc ) !== document ) { + setDocument( context ); + } + + context = context || document; + results = results || []; + + if ( !selector || typeof selector !== "string" ) { + return results; + } + + if ( (nodeType = context.nodeType) !== 1 && nodeType !== 9 ) { + return []; + } + + if ( documentIsHTML && !seed ) { + + // Shortcuts + if ( (match = rquickExpr.exec( selector )) ) { + // Speed-up: Sizzle("#ID") + if ( (m = match[1]) ) { + if ( nodeType === 9 ) { + elem = context.getElementById( m ); + // Check parentNode to catch when Blackberry 4.6 returns + // nodes that are no longer in the document #6963 + if ( elem && elem.parentNode ) { + // Handle the case where IE, Opera, and Webkit return items + // by name instead of ID + if ( elem.id === m ) { + results.push( elem ); + return results; + } + } else { + return results; + } + } else { + // Context is not a document + if ( context.ownerDocument && (elem = context.ownerDocument.getElementById( m )) && + contains( context, elem ) && elem.id === m ) { + results.push( elem ); + return results; + } + } + + // Speed-up: Sizzle("TAG") + } else if ( match[2] ) { + push.apply( results, context.getElementsByTagName( selector ) ); + return results; + + // Speed-up: Sizzle(".CLASS") + } else if ( (m = match[3]) && support.getElementsByClassName && context.getElementsByClassName ) { + push.apply( results, context.getElementsByClassName( m ) ); + return results; + } + } + + // QSA path + if ( support.qsa && (!rbuggyQSA || !rbuggyQSA.test( selector )) ) { + nid = old = expando; + newContext = context; + newSelector = nodeType === 9 && selector; + + // qSA works strangely on Element-rooted queries + // We can work around this by specifying an extra ID on the root + // and working up from there (Thanks to Andrew Dupont for the technique) + // IE 8 doesn't work on object elements + if ( nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) { + groups = tokenize( selector ); + + if ( (old = context.getAttribute("id")) ) { + nid = old.replace( rescape, "\\$&" ); + } else { + context.setAttribute( "id", nid ); + } + nid = "[id='" + nid + "'] "; + + i = groups.length; + while ( i-- ) { + groups[i] = nid + toSelector( groups[i] ); + } + newContext = rsibling.test( selector ) && context.parentNode || context; + newSelector = groups.join(","); + } + + if ( newSelector ) { + try { + push.apply( results, + newContext.querySelectorAll( newSelector ) + ); + return results; + } catch(qsaError) { + } finally { + if ( !old ) { + context.removeAttribute("id"); + } + } + } + } + } + + // All others + return select( selector.replace( rtrim, "$1" ), context, results, seed ); +} + +/** + * Create key-value caches of limited size + * @returns {Function(string, Object)} Returns the Object data after storing it on itself with + * property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength) + * deleting the oldest entry + */ +function createCache() { + var keys = []; + + function cache( key, value ) { + // Use (key + " ") to avoid collision with native prototype properties (see Issue #157) + if ( keys.push( key += " " ) > Expr.cacheLength ) { + // Only keep the most recent entries + delete cache[ keys.shift() ]; + } + return (cache[ key ] = value); + } + return cache; +} + +/** + * Mark a function for special use by Sizzle + * @param {Function} fn The function to mark + */ +function markFunction( fn ) { + fn[ expando ] = true; + return fn; +} + +/** + * Support testing using an element + * @param {Function} fn Passed the created div and expects a boolean result + */ +function assert( fn ) { + var div = document.createElement("div"); + + try { + return !!fn( div ); + } catch (e) { + return false; + } finally { + // Remove from its parent by default + if ( div.parentNode ) { + div.parentNode.removeChild( div ); + } + // release memory in IE + div = null; + } +} + +/** + * Adds the same handler for all of the specified attrs + * @param {String} attrs Pipe-separated list of attributes + * @param {Function} handler The method that will be applied + */ +function addHandle( attrs, handler ) { + var arr = attrs.split("|"), + i = attrs.length; + + while ( i-- ) { + Expr.attrHandle[ arr[i] ] = handler; + } +} + +/** + * Checks document order of two siblings + * @param {Element} a + * @param {Element} b + * @returns {Number} Returns less than 0 if a precedes b, greater than 0 if a follows b + */ +function siblingCheck( a, b ) { + var cur = b && a, + diff = cur && a.nodeType === 1 && b.nodeType === 1 && + ( ~b.sourceIndex || MAX_NEGATIVE ) - + ( ~a.sourceIndex || MAX_NEGATIVE ); + + // Use IE sourceIndex if available on both nodes + if ( diff ) { + return diff; + } + + // Check if b follows a + if ( cur ) { + while ( (cur = cur.nextSibling) ) { + if ( cur === b ) { + return -1; + } + } + } + + return a ? 1 : -1; +} + +/** + * Returns a function to use in pseudos for input types + * @param {String} type + */ +function createInputPseudo( type ) { + return function( elem ) { + var name = elem.nodeName.toLowerCase(); + return name === "input" && elem.type === type; + }; +} + +/** + * Returns a function to use in pseudos for buttons + * @param {String} type + */ +function createButtonPseudo( type ) { + return function( elem ) { + var name = elem.nodeName.toLowerCase(); + return (name === "input" || name === "button") && elem.type === type; + }; +} + +/** + * Returns a function to use in pseudos for positionals + * @param {Function} fn + */ +function createPositionalPseudo( fn ) { + return markFunction(function( argument ) { + argument = +argument; + return markFunction(function( seed, matches ) { + var j, + matchIndexes = fn( [], seed.length, argument ), + i = matchIndexes.length; + + // Match elements found at the specified indexes + while ( i-- ) { + if ( seed[ (j = matchIndexes[i]) ] ) { + seed[j] = !(matches[j] = seed[j]); + } + } + }); + }); +} + +/** + * Detect xml + * @param {Element|Object} elem An element or a document + */ +isXML = Sizzle.isXML = function( elem ) { + // documentElement is verified for cases where it doesn't yet exist + // (such as loading iframes in IE - #4833) + var documentElement = elem && (elem.ownerDocument || elem).documentElement; + return documentElement ? documentElement.nodeName !== "HTML" : false; +}; + +// Expose support vars for convenience +support = Sizzle.support = {}; + +/** + * Sets document-related variables once based on the current document + * @param {Element|Object} [doc] An element or document object to use to set the document + * @returns {Object} Returns the current document + */ +setDocument = Sizzle.setDocument = function( node ) { + var doc = node ? node.ownerDocument || node : preferredDoc, + parent = doc.defaultView; + + // If no document and documentElement is available, return + if ( doc === document || doc.nodeType !== 9 || !doc.documentElement ) { + return document; + } + + // Set our document + document = doc; + docElem = doc.documentElement; + + // Support tests + documentIsHTML = !isXML( doc ); + + // Support: IE>8 + // If iframe document is assigned to "document" variable and if iframe has been reloaded, + // IE will throw "permission denied" error when accessing "document" variable, see jQuery #13936 + // IE6-8 do not support the defaultView property so parent will be undefined + if ( parent && parent.attachEvent && parent !== parent.top ) { + parent.attachEvent( "onbeforeunload", function() { + setDocument(); + }); + } + + /* Attributes + ---------------------------------------------------------------------- */ + + // Support: IE<8 + // Verify that getAttribute really returns attributes and not properties (excepting IE8 booleans) + support.attributes = assert(function( div ) { + div.className = "i"; + return !div.getAttribute("className"); + }); + + /* getElement(s)By* + ---------------------------------------------------------------------- */ + + // Check if getElementsByTagName("*") returns only elements + support.getElementsByTagName = assert(function( div ) { + div.appendChild( doc.createComment("") ); + return !div.getElementsByTagName("*").length; + }); + + // Check if getElementsByClassName can be trusted + support.getElementsByClassName = assert(function( div ) { + div.innerHTML = "

"; + + // Support: Safari<4 + // Catch class over-caching + div.firstChild.className = "i"; + // Support: Opera<10 + // Catch gEBCN failure to find non-leading classes + return div.getElementsByClassName("i").length === 2; + }); + + // Support: IE<10 + // Check if getElementById returns elements by name + // The broken getElementById methods don't pick up programatically-set names, + // so use a roundabout getElementsByName test + support.getById = assert(function( div ) { + docElem.appendChild( div ).id = expando; + return !doc.getElementsByName || !doc.getElementsByName( expando ).length; + }); + + // ID find and filter + if ( support.getById ) { + Expr.find["ID"] = function( id, context ) { + if ( typeof context.getElementById !== strundefined && documentIsHTML ) { + var m = context.getElementById( id ); + // Check parentNode to catch when Blackberry 4.6 returns + // nodes that are no longer in the document #6963 + return m && m.parentNode ? [m] : []; + } + }; + Expr.filter["ID"] = function( id ) { + var attrId = id.replace( runescape, funescape ); + return function( elem ) { + return elem.getAttribute("id") === attrId; + }; + }; + } else { + // Support: IE6/7 + // getElementById is not reliable as a find shortcut + delete Expr.find["ID"]; + + Expr.filter["ID"] = function( id ) { + var attrId = id.replace( runescape, funescape ); + return function( elem ) { + var node = typeof elem.getAttributeNode !== strundefined && elem.getAttributeNode("id"); + return node && node.value === attrId; + }; + }; + } + + // Tag + Expr.find["TAG"] = support.getElementsByTagName ? + function( tag, context ) { + if ( typeof context.getElementsByTagName !== strundefined ) { + return context.getElementsByTagName( tag ); + } + } : + function( tag, context ) { + var elem, + tmp = [], + i = 0, + results = context.getElementsByTagName( tag ); + + // Filter out possible comments + if ( tag === "*" ) { + while ( (elem = results[i++]) ) { + if ( elem.nodeType === 1 ) { + tmp.push( elem ); + } + } + + return tmp; + } + return results; + }; + + // Class + Expr.find["CLASS"] = support.getElementsByClassName && function( className, context ) { + if ( typeof context.getElementsByClassName !== strundefined && documentIsHTML ) { + return context.getElementsByClassName( className ); + } + }; + + /* QSA/matchesSelector + ---------------------------------------------------------------------- */ + + // QSA and matchesSelector support + + // matchesSelector(:active) reports false when true (IE9/Opera 11.5) + rbuggyMatches = []; + + // qSa(:focus) reports false when true (Chrome 21) + // We allow this because of a bug in IE8/9 that throws an error + // whenever `document.activeElement` is accessed on an iframe + // So, we allow :focus to pass through QSA all the time to avoid the IE error + // See http://bugs.jquery.com/ticket/13378 + rbuggyQSA = []; + + if ( (support.qsa = rnative.test( doc.querySelectorAll )) ) { + // Build QSA regex + // Regex strategy adopted from Diego Perini + assert(function( div ) { + // Select is set to empty string on purpose + // This is to test IE's treatment of not explicitly + // setting a boolean content attribute, + // since its presence should be enough + // http://bugs.jquery.com/ticket/12359 + div.innerHTML = ""; + + // Support: IE8 + // Boolean attributes and "value" are not treated correctly + if ( !div.querySelectorAll("[selected]").length ) { + rbuggyQSA.push( "\\[" + whitespace + "*(?:value|" + booleans + ")" ); + } + + // Webkit/Opera - :checked should return selected option elements + // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked + // IE8 throws error here and will not see later tests + if ( !div.querySelectorAll(":checked").length ) { + rbuggyQSA.push(":checked"); + } + }); + + assert(function( div ) { + + // Support: Opera 10-12/IE8 + // ^= $= *= and empty values + // Should not select anything + // Support: Windows 8 Native Apps + // The type attribute is restricted during .innerHTML assignment + var input = doc.createElement("input"); + input.setAttribute( "type", "hidden" ); + div.appendChild( input ).setAttribute( "t", "" ); + + if ( div.querySelectorAll("[t^='']").length ) { + rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:''|\"\")" ); + } + + // FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled) + // IE8 throws error here and will not see later tests + if ( !div.querySelectorAll(":enabled").length ) { + rbuggyQSA.push( ":enabled", ":disabled" ); + } + + // Opera 10-11 does not throw on post-comma invalid pseudos + div.querySelectorAll("*,:x"); + rbuggyQSA.push(",.*:"); + }); + } + + if ( (support.matchesSelector = rnative.test( (matches = docElem.webkitMatchesSelector || + docElem.mozMatchesSelector || + docElem.oMatchesSelector || + docElem.msMatchesSelector) )) ) { + + assert(function( div ) { + // Check to see if it's possible to do matchesSelector + // on a disconnected node (IE 9) + support.disconnectedMatch = matches.call( div, "div" ); + + // This should fail with an exception + // Gecko does not error, returns false instead + matches.call( div, "[s!='']:x" ); + rbuggyMatches.push( "!=", pseudos ); + }); + } + + rbuggyQSA = rbuggyQSA.length && new RegExp( rbuggyQSA.join("|") ); + rbuggyMatches = rbuggyMatches.length && new RegExp( rbuggyMatches.join("|") ); + + /* Contains + ---------------------------------------------------------------------- */ + + // Element contains another + // Purposefully does not implement inclusive descendent + // As in, an element does not contain itself + contains = rnative.test( docElem.contains ) || docElem.compareDocumentPosition ? + function( a, b ) { + var adown = a.nodeType === 9 ? a.documentElement : a, + bup = b && b.parentNode; + return a === bup || !!( bup && bup.nodeType === 1 && ( + adown.contains ? + adown.contains( bup ) : + a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16 + )); + } : + function( a, b ) { + if ( b ) { + while ( (b = b.parentNode) ) { + if ( b === a ) { + return true; + } + } + } + return false; + }; + + /* Sorting + ---------------------------------------------------------------------- */ + + // Document order sorting + sortOrder = docElem.compareDocumentPosition ? + function( a, b ) { + + // Flag for duplicate removal + if ( a === b ) { + hasDuplicate = true; + return 0; + } + + var compare = b.compareDocumentPosition && a.compareDocumentPosition && a.compareDocumentPosition( b ); + + if ( compare ) { + // Disconnected nodes + if ( compare & 1 || + (!support.sortDetached && b.compareDocumentPosition( a ) === compare) ) { + + // Choose the first element that is related to our preferred document + if ( a === doc || contains(preferredDoc, a) ) { + return -1; + } + if ( b === doc || contains(preferredDoc, b) ) { + return 1; + } + + // Maintain original order + return sortInput ? + ( indexOf.call( sortInput, a ) - indexOf.call( sortInput, b ) ) : + 0; + } + + return compare & 4 ? -1 : 1; + } + + // Not directly comparable, sort on existence of method + return a.compareDocumentPosition ? -1 : 1; + } : + function( a, b ) { + var cur, + i = 0, + aup = a.parentNode, + bup = b.parentNode, + ap = [ a ], + bp = [ b ]; + + // Exit early if the nodes are identical + if ( a === b ) { + hasDuplicate = true; + return 0; + + // Parentless nodes are either documents or disconnected + } else if ( !aup || !bup ) { + return a === doc ? -1 : + b === doc ? 1 : + aup ? -1 : + bup ? 1 : + sortInput ? + ( indexOf.call( sortInput, a ) - indexOf.call( sortInput, b ) ) : + 0; + + // If the nodes are siblings, we can do a quick check + } else if ( aup === bup ) { + return siblingCheck( a, b ); + } + + // Otherwise we need full lists of their ancestors for comparison + cur = a; + while ( (cur = cur.parentNode) ) { + ap.unshift( cur ); + } + cur = b; + while ( (cur = cur.parentNode) ) { + bp.unshift( cur ); + } + + // Walk down the tree looking for a discrepancy + while ( ap[i] === bp[i] ) { + i++; + } + + return i ? + // Do a sibling check if the nodes have a common ancestor + siblingCheck( ap[i], bp[i] ) : + + // Otherwise nodes in our document sort first + ap[i] === preferredDoc ? -1 : + bp[i] === preferredDoc ? 1 : + 0; + }; + + return doc; +}; + +Sizzle.matches = function( expr, elements ) { + return Sizzle( expr, null, null, elements ); +}; + +Sizzle.matchesSelector = function( elem, expr ) { + // Set document vars if needed + if ( ( elem.ownerDocument || elem ) !== document ) { + setDocument( elem ); + } + + // Make sure that attribute selectors are quoted + expr = expr.replace( rattributeQuotes, "='$1']" ); + + if ( support.matchesSelector && documentIsHTML && + ( !rbuggyMatches || !rbuggyMatches.test( expr ) ) && + ( !rbuggyQSA || !rbuggyQSA.test( expr ) ) ) { + + try { + var ret = matches.call( elem, expr ); + + // IE 9's matchesSelector returns false on disconnected nodes + if ( ret || support.disconnectedMatch || + // As well, disconnected nodes are said to be in a document + // fragment in IE 9 + elem.document && elem.document.nodeType !== 11 ) { + return ret; + } + } catch(e) {} + } + + return Sizzle( expr, document, null, [elem] ).length > 0; +}; + +Sizzle.contains = function( context, elem ) { + // Set document vars if needed + if ( ( context.ownerDocument || context ) !== document ) { + setDocument( context ); + } + return contains( context, elem ); +}; + +Sizzle.attr = function( elem, name ) { + // Set document vars if needed + if ( ( elem.ownerDocument || elem ) !== document ) { + setDocument( elem ); + } + + var fn = Expr.attrHandle[ name.toLowerCase() ], + // Don't get fooled by Object.prototype properties (jQuery #13807) + val = fn && hasOwn.call( Expr.attrHandle, name.toLowerCase() ) ? + fn( elem, name, !documentIsHTML ) : + undefined; + + return val === undefined ? + support.attributes || !documentIsHTML ? + elem.getAttribute( name ) : + (val = elem.getAttributeNode(name)) && val.specified ? + val.value : + null : + val; +}; + +Sizzle.error = function( msg ) { + throw new Error( "Syntax error, unrecognized expression: " + msg ); +}; + +/** + * Document sorting and removing duplicates + * @param {ArrayLike} results + */ +Sizzle.uniqueSort = function( results ) { + var elem, + duplicates = [], + j = 0, + i = 0; + + // Unless we *know* we can detect duplicates, assume their presence + hasDuplicate = !support.detectDuplicates; + sortInput = !support.sortStable && results.slice( 0 ); + results.sort( sortOrder ); + + if ( hasDuplicate ) { + while ( (elem = results[i++]) ) { + if ( elem === results[ i ] ) { + j = duplicates.push( i ); + } + } + while ( j-- ) { + results.splice( duplicates[ j ], 1 ); + } + } + + return results; +}; + +/** + * Utility function for retrieving the text value of an array of DOM nodes + * @param {Array|Element} elem + */ +getText = Sizzle.getText = function( elem ) { + var node, + ret = "", + i = 0, + nodeType = elem.nodeType; + + if ( !nodeType ) { + // If no nodeType, this is expected to be an array + for ( ; (node = elem[i]); i++ ) { + // Do not traverse comment nodes + ret += getText( node ); + } + } else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) { + // Use textContent for elements + // innerText usage removed for consistency of new lines (see #11153) + if ( typeof elem.textContent === "string" ) { + return elem.textContent; + } else { + // Traverse its children + for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { + ret += getText( elem ); + } + } + } else if ( nodeType === 3 || nodeType === 4 ) { + return elem.nodeValue; + } + // Do not include comment or processing instruction nodes + + return ret; +}; + +Expr = Sizzle.selectors = { + + // Can be adjusted by the user + cacheLength: 50, + + createPseudo: markFunction, + + match: matchExpr, + + attrHandle: {}, + + find: {}, + + relative: { + ">": { dir: "parentNode", first: true }, + " ": { dir: "parentNode" }, + "+": { dir: "previousSibling", first: true }, + "~": { dir: "previousSibling" } + }, + + preFilter: { + "ATTR": function( match ) { + match[1] = match[1].replace( runescape, funescape ); + + // Move the given value to match[3] whether quoted or unquoted + match[3] = ( match[4] || match[5] || "" ).replace( runescape, funescape ); + + if ( match[2] === "~=" ) { + match[3] = " " + match[3] + " "; + } + + return match.slice( 0, 4 ); + }, + + "CHILD": function( match ) { + /* matches from matchExpr["CHILD"] + 1 type (only|nth|...) + 2 what (child|of-type) + 3 argument (even|odd|\d*|\d*n([+-]\d+)?|...) + 4 xn-component of xn+y argument ([+-]?\d*n|) + 5 sign of xn-component + 6 x of xn-component + 7 sign of y-component + 8 y of y-component + */ + match[1] = match[1].toLowerCase(); + + if ( match[1].slice( 0, 3 ) === "nth" ) { + // nth-* requires argument + if ( !match[3] ) { + Sizzle.error( match[0] ); + } + + // numeric x and y parameters for Expr.filter.CHILD + // remember that false/true cast respectively to 0/1 + match[4] = +( match[4] ? match[5] + (match[6] || 1) : 2 * ( match[3] === "even" || match[3] === "odd" ) ); + match[5] = +( ( match[7] + match[8] ) || match[3] === "odd" ); + + // other types prohibit arguments + } else if ( match[3] ) { + Sizzle.error( match[0] ); + } + + return match; + }, + + "PSEUDO": function( match ) { + var excess, + unquoted = !match[5] && match[2]; + + if ( matchExpr["CHILD"].test( match[0] ) ) { + return null; + } + + // Accept quoted arguments as-is + if ( match[3] && match[4] !== undefined ) { + match[2] = match[4]; + + // Strip excess characters from unquoted arguments + } else if ( unquoted && rpseudo.test( unquoted ) && + // Get excess from tokenize (recursively) + (excess = tokenize( unquoted, true )) && + // advance to the next closing parenthesis + (excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length) ) { + + // excess is a negative index + match[0] = match[0].slice( 0, excess ); + match[2] = unquoted.slice( 0, excess ); + } + + // Return only captures needed by the pseudo filter method (type and argument) + return match.slice( 0, 3 ); + } + }, + + filter: { + + "TAG": function( nodeNameSelector ) { + var nodeName = nodeNameSelector.replace( runescape, funescape ).toLowerCase(); + return nodeNameSelector === "*" ? + function() { return true; } : + function( elem ) { + return elem.nodeName && elem.nodeName.toLowerCase() === nodeName; + }; + }, + + "CLASS": function( className ) { + var pattern = classCache[ className + " " ]; + + return pattern || + (pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" )) && + classCache( className, function( elem ) { + return pattern.test( typeof elem.className === "string" && elem.className || typeof elem.getAttribute !== strundefined && elem.getAttribute("class") || "" ); + }); + }, + + "ATTR": function( name, operator, check ) { + return function( elem ) { + var result = Sizzle.attr( elem, name ); + + if ( result == null ) { + return operator === "!="; + } + if ( !operator ) { + return true; + } + + result += ""; + + return operator === "=" ? result === check : + operator === "!=" ? result !== check : + operator === "^=" ? check && result.indexOf( check ) === 0 : + operator === "*=" ? check && result.indexOf( check ) > -1 : + operator === "$=" ? check && result.slice( -check.length ) === check : + operator === "~=" ? ( " " + result + " " ).indexOf( check ) > -1 : + operator === "|=" ? result === check || result.slice( 0, check.length + 1 ) === check + "-" : + false; + }; + }, + + "CHILD": function( type, what, argument, first, last ) { + var simple = type.slice( 0, 3 ) !== "nth", + forward = type.slice( -4 ) !== "last", + ofType = what === "of-type"; + + return first === 1 && last === 0 ? + + // Shortcut for :nth-*(n) + function( elem ) { + return !!elem.parentNode; + } : + + function( elem, context, xml ) { + var cache, outerCache, node, diff, nodeIndex, start, + dir = simple !== forward ? "nextSibling" : "previousSibling", + parent = elem.parentNode, + name = ofType && elem.nodeName.toLowerCase(), + useCache = !xml && !ofType; + + if ( parent ) { + + // :(first|last|only)-(child|of-type) + if ( simple ) { + while ( dir ) { + node = elem; + while ( (node = node[ dir ]) ) { + if ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) { + return false; + } + } + // Reverse direction for :only-* (if we haven't yet done so) + start = dir = type === "only" && !start && "nextSibling"; + } + return true; + } + + start = [ forward ? parent.firstChild : parent.lastChild ]; + + // non-xml :nth-child(...) stores cache data on `parent` + if ( forward && useCache ) { + // Seek `elem` from a previously-cached index + outerCache = parent[ expando ] || (parent[ expando ] = {}); + cache = outerCache[ type ] || []; + nodeIndex = cache[0] === dirruns && cache[1]; + diff = cache[0] === dirruns && cache[2]; + node = nodeIndex && parent.childNodes[ nodeIndex ]; + + while ( (node = ++nodeIndex && node && node[ dir ] || + + // Fallback to seeking `elem` from the start + (diff = nodeIndex = 0) || start.pop()) ) { + + // When found, cache indexes on `parent` and break + if ( node.nodeType === 1 && ++diff && node === elem ) { + outerCache[ type ] = [ dirruns, nodeIndex, diff ]; + break; + } + } + + // Use previously-cached element index if available + } else if ( useCache && (cache = (elem[ expando ] || (elem[ expando ] = {}))[ type ]) && cache[0] === dirruns ) { + diff = cache[1]; + + // xml :nth-child(...) or :nth-last-child(...) or :nth(-last)?-of-type(...) + } else { + // Use the same loop as above to seek `elem` from the start + while ( (node = ++nodeIndex && node && node[ dir ] || + (diff = nodeIndex = 0) || start.pop()) ) { + + if ( ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) && ++diff ) { + // Cache the index of each encountered element + if ( useCache ) { + (node[ expando ] || (node[ expando ] = {}))[ type ] = [ dirruns, diff ]; + } + + if ( node === elem ) { + break; + } + } + } + } + + // Incorporate the offset, then check against cycle size + diff -= last; + return diff === first || ( diff % first === 0 && diff / first >= 0 ); + } + }; + }, + + "PSEUDO": function( pseudo, argument ) { + // pseudo-class names are case-insensitive + // http://www.w3.org/TR/selectors/#pseudo-classes + // Prioritize by case sensitivity in case custom pseudos are added with uppercase letters + // Remember that setFilters inherits from pseudos + var args, + fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] || + Sizzle.error( "unsupported pseudo: " + pseudo ); + + // The user may use createPseudo to indicate that + // arguments are needed to create the filter function + // just as Sizzle does + if ( fn[ expando ] ) { + return fn( argument ); + } + + // But maintain support for old signatures + if ( fn.length > 1 ) { + args = [ pseudo, pseudo, "", argument ]; + return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ? + markFunction(function( seed, matches ) { + var idx, + matched = fn( seed, argument ), + i = matched.length; + while ( i-- ) { + idx = indexOf.call( seed, matched[i] ); + seed[ idx ] = !( matches[ idx ] = matched[i] ); + } + }) : + function( elem ) { + return fn( elem, 0, args ); + }; + } + + return fn; + } + }, + + pseudos: { + // Potentially complex pseudos + "not": markFunction(function( selector ) { + // Trim the selector passed to compile + // to avoid treating leading and trailing + // spaces as combinators + var input = [], + results = [], + matcher = compile( selector.replace( rtrim, "$1" ) ); + + return matcher[ expando ] ? + markFunction(function( seed, matches, context, xml ) { + var elem, + unmatched = matcher( seed, null, xml, [] ), + i = seed.length; + + // Match elements unmatched by `matcher` + while ( i-- ) { + if ( (elem = unmatched[i]) ) { + seed[i] = !(matches[i] = elem); + } + } + }) : + function( elem, context, xml ) { + input[0] = elem; + matcher( input, null, xml, results ); + return !results.pop(); + }; + }), + + "has": markFunction(function( selector ) { + return function( elem ) { + return Sizzle( selector, elem ).length > 0; + }; + }), + + "contains": markFunction(function( text ) { + return function( elem ) { + return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1; + }; + }), + + // "Whether an element is represented by a :lang() selector + // is based solely on the element's language value + // being equal to the identifier C, + // or beginning with the identifier C immediately followed by "-". + // The matching of C against the element's language value is performed case-insensitively. + // The identifier C does not have to be a valid language name." + // http://www.w3.org/TR/selectors/#lang-pseudo + "lang": markFunction( function( lang ) { + // lang value must be a valid identifier + if ( !ridentifier.test(lang || "") ) { + Sizzle.error( "unsupported lang: " + lang ); + } + lang = lang.replace( runescape, funescape ).toLowerCase(); + return function( elem ) { + var elemLang; + do { + if ( (elemLang = documentIsHTML ? + elem.lang : + elem.getAttribute("xml:lang") || elem.getAttribute("lang")) ) { + + elemLang = elemLang.toLowerCase(); + return elemLang === lang || elemLang.indexOf( lang + "-" ) === 0; + } + } while ( (elem = elem.parentNode) && elem.nodeType === 1 ); + return false; + }; + }), + + // Miscellaneous + "target": function( elem ) { + var hash = window.location && window.location.hash; + return hash && hash.slice( 1 ) === elem.id; + }, + + "root": function( elem ) { + return elem === docElem; + }, + + "focus": function( elem ) { + return elem === document.activeElement && (!document.hasFocus || document.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex); + }, + + // Boolean properties + "enabled": function( elem ) { + return elem.disabled === false; + }, + + "disabled": function( elem ) { + return elem.disabled === true; + }, + + "checked": function( elem ) { + // In CSS3, :checked should return both checked and selected elements + // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked + var nodeName = elem.nodeName.toLowerCase(); + return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected); + }, + + "selected": function( elem ) { + // Accessing this property makes selected-by-default + // options in Safari work properly + if ( elem.parentNode ) { + elem.parentNode.selectedIndex; + } + + return elem.selected === true; + }, + + // Contents + "empty": function( elem ) { + // http://www.w3.org/TR/selectors/#empty-pseudo + // :empty is only affected by element nodes and content nodes(including text(3), cdata(4)), + // not comment, processing instructions, or others + // Thanks to Diego Perini for the nodeName shortcut + // Greater than "@" means alpha characters (specifically not starting with "#" or "?") + for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { + if ( elem.nodeName > "@" || elem.nodeType === 3 || elem.nodeType === 4 ) { + return false; + } + } + return true; + }, + + "parent": function( elem ) { + return !Expr.pseudos["empty"]( elem ); + }, + + // Element/input types + "header": function( elem ) { + return rheader.test( elem.nodeName ); + }, + + "input": function( elem ) { + return rinputs.test( elem.nodeName ); + }, + + "button": function( elem ) { + var name = elem.nodeName.toLowerCase(); + return name === "input" && elem.type === "button" || name === "button"; + }, + + "text": function( elem ) { + var attr; + // IE6 and 7 will map elem.type to 'text' for new HTML5 types (search, etc) + // use getAttribute instead to test this case + return elem.nodeName.toLowerCase() === "input" && + elem.type === "text" && + ( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === elem.type ); + }, + + // Position-in-collection + "first": createPositionalPseudo(function() { + return [ 0 ]; + }), + + "last": createPositionalPseudo(function( matchIndexes, length ) { + return [ length - 1 ]; + }), + + "eq": createPositionalPseudo(function( matchIndexes, length, argument ) { + return [ argument < 0 ? argument + length : argument ]; + }), + + "even": createPositionalPseudo(function( matchIndexes, length ) { + var i = 0; + for ( ; i < length; i += 2 ) { + matchIndexes.push( i ); + } + return matchIndexes; + }), + + "odd": createPositionalPseudo(function( matchIndexes, length ) { + var i = 1; + for ( ; i < length; i += 2 ) { + matchIndexes.push( i ); + } + return matchIndexes; + }), + + "lt": createPositionalPseudo(function( matchIndexes, length, argument ) { + var i = argument < 0 ? argument + length : argument; + for ( ; --i >= 0; ) { + matchIndexes.push( i ); + } + return matchIndexes; + }), + + "gt": createPositionalPseudo(function( matchIndexes, length, argument ) { + var i = argument < 0 ? argument + length : argument; + for ( ; ++i < length; ) { + matchIndexes.push( i ); + } + return matchIndexes; + }) + } +}; + +Expr.pseudos["nth"] = Expr.pseudos["eq"]; + +// Add button/input type pseudos +for ( i in { radio: true, checkbox: true, file: true, password: true, image: true } ) { + Expr.pseudos[ i ] = createInputPseudo( i ); +} +for ( i in { submit: true, reset: true } ) { + Expr.pseudos[ i ] = createButtonPseudo( i ); +} + +// Easy API for creating new setFilters +function setFilters() {} +setFilters.prototype = Expr.filters = Expr.pseudos; +Expr.setFilters = new setFilters(); + +function tokenize( selector, parseOnly ) { + var matched, match, tokens, type, + soFar, groups, preFilters, + cached = tokenCache[ selector + " " ]; + + if ( cached ) { + return parseOnly ? 0 : cached.slice( 0 ); + } + + soFar = selector; + groups = []; + preFilters = Expr.preFilter; + + while ( soFar ) { + + // Comma and first run + if ( !matched || (match = rcomma.exec( soFar )) ) { + if ( match ) { + // Don't consume trailing commas as valid + soFar = soFar.slice( match[0].length ) || soFar; + } + groups.push( tokens = [] ); + } + + matched = false; + + // Combinators + if ( (match = rcombinators.exec( soFar )) ) { + matched = match.shift(); + tokens.push({ + value: matched, + // Cast descendant combinators to space + type: match[0].replace( rtrim, " " ) + }); + soFar = soFar.slice( matched.length ); + } + + // Filters + for ( type in Expr.filter ) { + if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] || + (match = preFilters[ type ]( match ))) ) { + matched = match.shift(); + tokens.push({ + value: matched, + type: type, + matches: match + }); + soFar = soFar.slice( matched.length ); + } + } + + if ( !matched ) { + break; + } + } + + // Return the length of the invalid excess + // if we're just parsing + // Otherwise, throw an error or return tokens + return parseOnly ? + soFar.length : + soFar ? + Sizzle.error( selector ) : + // Cache the tokens + tokenCache( selector, groups ).slice( 0 ); +} + +function toSelector( tokens ) { + var i = 0, + len = tokens.length, + selector = ""; + for ( ; i < len; i++ ) { + selector += tokens[i].value; + } + return selector; +} + +function addCombinator( matcher, combinator, base ) { + var dir = combinator.dir, + checkNonElements = base && dir === "parentNode", + doneName = done++; + + return combinator.first ? + // Check against closest ancestor/preceding element + function( elem, context, xml ) { + while ( (elem = elem[ dir ]) ) { + if ( elem.nodeType === 1 || checkNonElements ) { + return matcher( elem, context, xml ); + } + } + } : + + // Check against all ancestor/preceding elements + function( elem, context, xml ) { + var data, cache, outerCache, + dirkey = dirruns + " " + doneName; + + // We can't set arbitrary data on XML nodes, so they don't benefit from dir caching + if ( xml ) { + while ( (elem = elem[ dir ]) ) { + if ( elem.nodeType === 1 || checkNonElements ) { + if ( matcher( elem, context, xml ) ) { + return true; + } + } + } + } else { + while ( (elem = elem[ dir ]) ) { + if ( elem.nodeType === 1 || checkNonElements ) { + outerCache = elem[ expando ] || (elem[ expando ] = {}); + if ( (cache = outerCache[ dir ]) && cache[0] === dirkey ) { + if ( (data = cache[1]) === true || data === cachedruns ) { + return data === true; + } + } else { + cache = outerCache[ dir ] = [ dirkey ]; + cache[1] = matcher( elem, context, xml ) || cachedruns; + if ( cache[1] === true ) { + return true; + } + } + } + } + } + }; +} + +function elementMatcher( matchers ) { + return matchers.length > 1 ? + function( elem, context, xml ) { + var i = matchers.length; + while ( i-- ) { + if ( !matchers[i]( elem, context, xml ) ) { + return false; + } + } + return true; + } : + matchers[0]; +} + +function condense( unmatched, map, filter, context, xml ) { + var elem, + newUnmatched = [], + i = 0, + len = unmatched.length, + mapped = map != null; + + for ( ; i < len; i++ ) { + if ( (elem = unmatched[i]) ) { + if ( !filter || filter( elem, context, xml ) ) { + newUnmatched.push( elem ); + if ( mapped ) { + map.push( i ); + } + } + } + } + + return newUnmatched; +} + +function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) { + if ( postFilter && !postFilter[ expando ] ) { + postFilter = setMatcher( postFilter ); + } + if ( postFinder && !postFinder[ expando ] ) { + postFinder = setMatcher( postFinder, postSelector ); + } + return markFunction(function( seed, results, context, xml ) { + var temp, i, elem, + preMap = [], + postMap = [], + preexisting = results.length, + + // Get initial elements from seed or context + elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [] ), + + // Prefilter to get matcher input, preserving a map for seed-results synchronization + matcherIn = preFilter && ( seed || !selector ) ? + condense( elems, preMap, preFilter, context, xml ) : + elems, + + matcherOut = matcher ? + // If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results, + postFinder || ( seed ? preFilter : preexisting || postFilter ) ? + + // ...intermediate processing is necessary + [] : + + // ...otherwise use results directly + results : + matcherIn; + + // Find primary matches + if ( matcher ) { + matcher( matcherIn, matcherOut, context, xml ); + } + + // Apply postFilter + if ( postFilter ) { + temp = condense( matcherOut, postMap ); + postFilter( temp, [], context, xml ); + + // Un-match failing elements by moving them back to matcherIn + i = temp.length; + while ( i-- ) { + if ( (elem = temp[i]) ) { + matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem); + } + } + } + + if ( seed ) { + if ( postFinder || preFilter ) { + if ( postFinder ) { + // Get the final matcherOut by condensing this intermediate into postFinder contexts + temp = []; + i = matcherOut.length; + while ( i-- ) { + if ( (elem = matcherOut[i]) ) { + // Restore matcherIn since elem is not yet a final match + temp.push( (matcherIn[i] = elem) ); + } + } + postFinder( null, (matcherOut = []), temp, xml ); + } + + // Move matched elements from seed to results to keep them synchronized + i = matcherOut.length; + while ( i-- ) { + if ( (elem = matcherOut[i]) && + (temp = postFinder ? indexOf.call( seed, elem ) : preMap[i]) > -1 ) { + + seed[temp] = !(results[temp] = elem); + } + } + } + + // Add elements to results, through postFinder if defined + } else { + matcherOut = condense( + matcherOut === results ? + matcherOut.splice( preexisting, matcherOut.length ) : + matcherOut + ); + if ( postFinder ) { + postFinder( null, results, matcherOut, xml ); + } else { + push.apply( results, matcherOut ); + } + } + }); +} + +function matcherFromTokens( tokens ) { + var checkContext, matcher, j, + len = tokens.length, + leadingRelative = Expr.relative[ tokens[0].type ], + implicitRelative = leadingRelative || Expr.relative[" "], + i = leadingRelative ? 1 : 0, + + // The foundational matcher ensures that elements are reachable from top-level context(s) + matchContext = addCombinator( function( elem ) { + return elem === checkContext; + }, implicitRelative, true ), + matchAnyContext = addCombinator( function( elem ) { + return indexOf.call( checkContext, elem ) > -1; + }, implicitRelative, true ), + matchers = [ function( elem, context, xml ) { + return ( !leadingRelative && ( xml || context !== outermostContext ) ) || ( + (checkContext = context).nodeType ? + matchContext( elem, context, xml ) : + matchAnyContext( elem, context, xml ) ); + } ]; + + for ( ; i < len; i++ ) { + if ( (matcher = Expr.relative[ tokens[i].type ]) ) { + matchers = [ addCombinator(elementMatcher( matchers ), matcher) ]; + } else { + matcher = Expr.filter[ tokens[i].type ].apply( null, tokens[i].matches ); + + // Return special upon seeing a positional matcher + if ( matcher[ expando ] ) { + // Find the next relative operator (if any) for proper handling + j = ++i; + for ( ; j < len; j++ ) { + if ( Expr.relative[ tokens[j].type ] ) { + break; + } + } + return setMatcher( + i > 1 && elementMatcher( matchers ), + i > 1 && toSelector( + // If the preceding token was a descendant combinator, insert an implicit any-element `*` + tokens.slice( 0, i - 1 ).concat({ value: tokens[ i - 2 ].type === " " ? "*" : "" }) + ).replace( rtrim, "$1" ), + matcher, + i < j && matcherFromTokens( tokens.slice( i, j ) ), + j < len && matcherFromTokens( (tokens = tokens.slice( j )) ), + j < len && toSelector( tokens ) + ); + } + matchers.push( matcher ); + } + } + + return elementMatcher( matchers ); +} + +function matcherFromGroupMatchers( elementMatchers, setMatchers ) { + // A counter to specify which element is currently being matched + var matcherCachedRuns = 0, + bySet = setMatchers.length > 0, + byElement = elementMatchers.length > 0, + superMatcher = function( seed, context, xml, results, expandContext ) { + var elem, j, matcher, + setMatched = [], + matchedCount = 0, + i = "0", + unmatched = seed && [], + outermost = expandContext != null, + contextBackup = outermostContext, + // We must always have either seed elements or context + elems = seed || byElement && Expr.find["TAG"]( "*", expandContext && context.parentNode || context ), + // Use integer dirruns iff this is the outermost matcher + dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.random() || 0.1); + + if ( outermost ) { + outermostContext = context !== document && context; + cachedruns = matcherCachedRuns; + } + + // Add elements passing elementMatchers directly to results + // Keep `i` a string if there are no elements so `matchedCount` will be "00" below + for ( ; (elem = elems[i]) != null; i++ ) { + if ( byElement && elem ) { + j = 0; + while ( (matcher = elementMatchers[j++]) ) { + if ( matcher( elem, context, xml ) ) { + results.push( elem ); + break; + } + } + if ( outermost ) { + dirruns = dirrunsUnique; + cachedruns = ++matcherCachedRuns; + } + } + + // Track unmatched elements for set filters + if ( bySet ) { + // They will have gone through all possible matchers + if ( (elem = !matcher && elem) ) { + matchedCount--; + } + + // Lengthen the array for every element, matched or not + if ( seed ) { + unmatched.push( elem ); + } + } + } + + // Apply set filters to unmatched elements + matchedCount += i; + if ( bySet && i !== matchedCount ) { + j = 0; + while ( (matcher = setMatchers[j++]) ) { + matcher( unmatched, setMatched, context, xml ); + } + + if ( seed ) { + // Reintegrate element matches to eliminate the need for sorting + if ( matchedCount > 0 ) { + while ( i-- ) { + if ( !(unmatched[i] || setMatched[i]) ) { + setMatched[i] = pop.call( results ); + } + } + } + + // Discard index placeholder values to get only actual matches + setMatched = condense( setMatched ); + } + + // Add matches to results + push.apply( results, setMatched ); + + // Seedless set matches succeeding multiple successful matchers stipulate sorting + if ( outermost && !seed && setMatched.length > 0 && + ( matchedCount + setMatchers.length ) > 1 ) { + + Sizzle.uniqueSort( results ); + } + } + + // Override manipulation of globals by nested matchers + if ( outermost ) { + dirruns = dirrunsUnique; + outermostContext = contextBackup; + } + + return unmatched; + }; + + return bySet ? + markFunction( superMatcher ) : + superMatcher; +} + +compile = Sizzle.compile = function( selector, group /* Internal Use Only */ ) { + var i, + setMatchers = [], + elementMatchers = [], + cached = compilerCache[ selector + " " ]; + + if ( !cached ) { + // Generate a function of recursive functions that can be used to check each element + if ( !group ) { + group = tokenize( selector ); + } + i = group.length; + while ( i-- ) { + cached = matcherFromTokens( group[i] ); + if ( cached[ expando ] ) { + setMatchers.push( cached ); + } else { + elementMatchers.push( cached ); + } + } + + // Cache the compiled function + cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) ); + } + return cached; +}; + +function multipleContexts( selector, contexts, results ) { + var i = 0, + len = contexts.length; + for ( ; i < len; i++ ) { + Sizzle( selector, contexts[i], results ); + } + return results; +} + +function select( selector, context, results, seed ) { + var i, tokens, token, type, find, + match = tokenize( selector ); + + if ( !seed ) { + // Try to minimize operations if there is only one group + if ( match.length === 1 ) { + + // Take a shortcut and set the context if the root selector is an ID + tokens = match[0] = match[0].slice( 0 ); + if ( tokens.length > 2 && (token = tokens[0]).type === "ID" && + support.getById && context.nodeType === 9 && documentIsHTML && + Expr.relative[ tokens[1].type ] ) { + + context = ( Expr.find["ID"]( token.matches[0].replace(runescape, funescape), context ) || [] )[0]; + if ( !context ) { + return results; + } + selector = selector.slice( tokens.shift().value.length ); + } + + // Fetch a seed set for right-to-left matching + i = matchExpr["needsContext"].test( selector ) ? 0 : tokens.length; + while ( i-- ) { + token = tokens[i]; + + // Abort if we hit a combinator + if ( Expr.relative[ (type = token.type) ] ) { + break; + } + if ( (find = Expr.find[ type ]) ) { + // Search, expanding context for leading sibling combinators + if ( (seed = find( + token.matches[0].replace( runescape, funescape ), + rsibling.test( tokens[0].type ) && context.parentNode || context + )) ) { + + // If seed is empty or no tokens remain, we can return early + tokens.splice( i, 1 ); + selector = seed.length && toSelector( tokens ); + if ( !selector ) { + push.apply( results, seed ); + return results; + } + + break; + } + } + } + } + } + + // Compile and execute a filtering function + // Provide `match` to avoid retokenization if we modified the selector above + compile( selector, match )( + seed, + context, + !documentIsHTML, + results, + rsibling.test( selector ) + ); + return results; +} + +// One-time assignments + +// Sort stability +support.sortStable = expando.split("").sort( sortOrder ).join("") === expando; + +// Support: Chrome<14 +// Always assume duplicates if they aren't passed to the comparison function +support.detectDuplicates = hasDuplicate; + +// Initialize against the default document +setDocument(); + +// Support: Webkit<537.32 - Safari 6.0.3/Chrome 25 (fixed in Chrome 27) +// Detached nodes confoundingly follow *each other* +support.sortDetached = assert(function( div1 ) { + // Should return 1, but returns 4 (following) + return div1.compareDocumentPosition( document.createElement("div") ) & 1; +}); + +// Support: IE<8 +// Prevent attribute/property "interpolation" +// http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx +if ( !assert(function( div ) { + div.innerHTML = ""; + return div.firstChild.getAttribute("href") === "#" ; +}) ) { + addHandle( "type|href|height|width", function( elem, name, isXML ) { + if ( !isXML ) { + return elem.getAttribute( name, name.toLowerCase() === "type" ? 1 : 2 ); + } + }); +} + +// Support: IE<9 +// Use defaultValue in place of getAttribute("value") +if ( !support.attributes || !assert(function( div ) { + div.innerHTML = ""; + div.firstChild.setAttribute( "value", "" ); + return div.firstChild.getAttribute( "value" ) === ""; +}) ) { + addHandle( "value", function( elem, name, isXML ) { + if ( !isXML && elem.nodeName.toLowerCase() === "input" ) { + return elem.defaultValue; + } + }); +} + +// Support: IE<9 +// Use getAttributeNode to fetch booleans when getAttribute lies +if ( !assert(function( div ) { + return div.getAttribute("disabled") == null; +}) ) { + addHandle( booleans, function( elem, name, isXML ) { + var val; + if ( !isXML ) { + return (val = elem.getAttributeNode( name )) && val.specified ? + val.value : + elem[ name ] === true ? name.toLowerCase() : null; + } + }); +} + +jQuery.find = Sizzle; +jQuery.expr = Sizzle.selectors; +jQuery.expr[":"] = jQuery.expr.pseudos; +jQuery.unique = Sizzle.uniqueSort; +jQuery.text = Sizzle.getText; +jQuery.isXMLDoc = Sizzle.isXML; +jQuery.contains = Sizzle.contains; + + +})( window ); +// String to Object options format cache +var optionsCache = {}; + +// Convert String-formatted options into Object-formatted ones and store in cache +function createOptions( options ) { + var object = optionsCache[ options ] = {}; + jQuery.each( options.match( core_rnotwhite ) || [], function( _, flag ) { + object[ flag ] = true; + }); + return object; +} + +/* + * Create a callback list using the following parameters: + * + * options: an optional list of space-separated options that will change how + * the callback list behaves or a more traditional option object + * + * By default a callback list will act like an event callback list and can be + * "fired" multiple times. + * + * Possible options: + * + * once: will ensure the callback list can only be fired once (like a Deferred) + * + * memory: will keep track of previous values and will call any callback added + * after the list has been fired right away with the latest "memorized" + * values (like a Deferred) + * + * unique: will ensure a callback can only be added once (no duplicate in the list) + * + * stopOnFalse: interrupt callings when a callback returns false + * + */ +jQuery.Callbacks = function( options ) { + + // Convert options from String-formatted to Object-formatted if needed + // (we check in cache first) + options = typeof options === "string" ? + ( optionsCache[ options ] || createOptions( options ) ) : + jQuery.extend( {}, options ); + + var // Last fire value (for non-forgettable lists) + memory, + // Flag to know if list was already fired + fired, + // Flag to know if list is currently firing + firing, + // First callback to fire (used internally by add and fireWith) + firingStart, + // End of the loop when firing + firingLength, + // Index of currently firing callback (modified by remove if needed) + firingIndex, + // Actual callback list + list = [], + // Stack of fire calls for repeatable lists + stack = !options.once && [], + // Fire callbacks + fire = function( data ) { + memory = options.memory && data; + fired = true; + firingIndex = firingStart || 0; + firingStart = 0; + firingLength = list.length; + firing = true; + for ( ; list && firingIndex < firingLength; firingIndex++ ) { + if ( list[ firingIndex ].apply( data[ 0 ], data[ 1 ] ) === false && options.stopOnFalse ) { + memory = false; // To prevent further calls using add + break; + } + } + firing = false; + if ( list ) { + if ( stack ) { + if ( stack.length ) { + fire( stack.shift() ); + } + } else if ( memory ) { + list = []; + } else { + self.disable(); + } + } + }, + // Actual Callbacks object + self = { + // Add a callback or a collection of callbacks to the list + add: function() { + if ( list ) { + // First, we save the current length + var start = list.length; + (function add( args ) { + jQuery.each( args, function( _, arg ) { + var type = jQuery.type( arg ); + if ( type === "function" ) { + if ( !options.unique || !self.has( arg ) ) { + list.push( arg ); + } + } else if ( arg && arg.length && type !== "string" ) { + // Inspect recursively + add( arg ); + } + }); + })( arguments ); + // Do we need to add the callbacks to the + // current firing batch? + if ( firing ) { + firingLength = list.length; + // With memory, if we're not firing then + // we should call right away + } else if ( memory ) { + firingStart = start; + fire( memory ); + } + } + return this; + }, + // Remove a callback from the list + remove: function() { + if ( list ) { + jQuery.each( arguments, function( _, arg ) { + var index; + while( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) { + list.splice( index, 1 ); + // Handle firing indexes + if ( firing ) { + if ( index <= firingLength ) { + firingLength--; + } + if ( index <= firingIndex ) { + firingIndex--; + } + } + } + }); + } + return this; + }, + // Check if a given callback is in the list. + // If no argument is given, return whether or not list has callbacks attached. + has: function( fn ) { + return fn ? jQuery.inArray( fn, list ) > -1 : !!( list && list.length ); + }, + // Remove all callbacks from the list + empty: function() { + list = []; + firingLength = 0; + return this; + }, + // Have the list do nothing anymore + disable: function() { + list = stack = memory = undefined; + return this; + }, + // Is it disabled? + disabled: function() { + return !list; + }, + // Lock the list in its current state + lock: function() { + stack = undefined; + if ( !memory ) { + self.disable(); + } + return this; + }, + // Is it locked? + locked: function() { + return !stack; + }, + // Call all callbacks with the given context and arguments + fireWith: function( context, args ) { + if ( list && ( !fired || stack ) ) { + args = args || []; + args = [ context, args.slice ? args.slice() : args ]; + if ( firing ) { + stack.push( args ); + } else { + fire( args ); + } + } + return this; + }, + // Call all the callbacks with the given arguments + fire: function() { + self.fireWith( this, arguments ); + return this; + }, + // To know if the callbacks have already been called at least once + fired: function() { + return !!fired; + } + }; + + return self; +}; +jQuery.extend({ + + Deferred: function( func ) { + var tuples = [ + // action, add listener, listener list, final state + [ "resolve", "done", jQuery.Callbacks("once memory"), "resolved" ], + [ "reject", "fail", jQuery.Callbacks("once memory"), "rejected" ], + [ "notify", "progress", jQuery.Callbacks("memory") ] + ], + state = "pending", + promise = { + state: function() { + return state; + }, + always: function() { + deferred.done( arguments ).fail( arguments ); + return this; + }, + then: function( /* fnDone, fnFail, fnProgress */ ) { + var fns = arguments; + return jQuery.Deferred(function( newDefer ) { + jQuery.each( tuples, function( i, tuple ) { + var action = tuple[ 0 ], + fn = jQuery.isFunction( fns[ i ] ) && fns[ i ]; + // deferred[ done | fail | progress ] for forwarding actions to newDefer + deferred[ tuple[1] ](function() { + var returned = fn && fn.apply( this, arguments ); + if ( returned && jQuery.isFunction( returned.promise ) ) { + returned.promise() + .done( newDefer.resolve ) + .fail( newDefer.reject ) + .progress( newDefer.notify ); + } else { + newDefer[ action + "With" ]( this === promise ? newDefer.promise() : this, fn ? [ returned ] : arguments ); + } + }); + }); + fns = null; + }).promise(); + }, + // Get a promise for this deferred + // If obj is provided, the promise aspect is added to the object + promise: function( obj ) { + return obj != null ? jQuery.extend( obj, promise ) : promise; + } + }, + deferred = {}; + + // Keep pipe for back-compat + promise.pipe = promise.then; + + // Add list-specific methods + jQuery.each( tuples, function( i, tuple ) { + var list = tuple[ 2 ], + stateString = tuple[ 3 ]; + + // promise[ done | fail | progress ] = list.add + promise[ tuple[1] ] = list.add; + + // Handle state + if ( stateString ) { + list.add(function() { + // state = [ resolved | rejected ] + state = stateString; + + // [ reject_list | resolve_list ].disable; progress_list.lock + }, tuples[ i ^ 1 ][ 2 ].disable, tuples[ 2 ][ 2 ].lock ); + } + + // deferred[ resolve | reject | notify ] + deferred[ tuple[0] ] = function() { + deferred[ tuple[0] + "With" ]( this === deferred ? promise : this, arguments ); + return this; + }; + deferred[ tuple[0] + "With" ] = list.fireWith; + }); + + // Make the deferred a promise + promise.promise( deferred ); + + // Call given func if any + if ( func ) { + func.call( deferred, deferred ); + } + + // All done! + return deferred; + }, + + // Deferred helper + when: function( subordinate /* , ..., subordinateN */ ) { + var i = 0, + resolveValues = core_slice.call( arguments ), + length = resolveValues.length, + + // the count of uncompleted subordinates + remaining = length !== 1 || ( subordinate && jQuery.isFunction( subordinate.promise ) ) ? length : 0, + + // the master Deferred. If resolveValues consist of only a single Deferred, just use that. + deferred = remaining === 1 ? subordinate : jQuery.Deferred(), + + // Update function for both resolve and progress values + updateFunc = function( i, contexts, values ) { + return function( value ) { + contexts[ i ] = this; + values[ i ] = arguments.length > 1 ? core_slice.call( arguments ) : value; + if( values === progressValues ) { + deferred.notifyWith( contexts, values ); + } else if ( !( --remaining ) ) { + deferred.resolveWith( contexts, values ); + } + }; + }, + + progressValues, progressContexts, resolveContexts; + + // add listeners to Deferred subordinates; treat others as resolved + if ( length > 1 ) { + progressValues = new Array( length ); + progressContexts = new Array( length ); + resolveContexts = new Array( length ); + for ( ; i < length; i++ ) { + if ( resolveValues[ i ] && jQuery.isFunction( resolveValues[ i ].promise ) ) { + resolveValues[ i ].promise() + .done( updateFunc( i, resolveContexts, resolveValues ) ) + .fail( deferred.reject ) + .progress( updateFunc( i, progressContexts, progressValues ) ); + } else { + --remaining; + } + } + } + + // if we're not waiting on anything, resolve the master + if ( !remaining ) { + deferred.resolveWith( resolveContexts, resolveValues ); + } + + return deferred.promise(); + } +}); +jQuery.support = (function( support ) { + var input = document.createElement("input"), + fragment = document.createDocumentFragment(), + div = document.createElement("div"), + select = document.createElement("select"), + opt = select.appendChild( document.createElement("option") ); + + // Finish early in limited environments + if ( !input.type ) { + return support; + } + + input.type = "checkbox"; + + // Support: Safari 5.1, iOS 5.1, Android 4.x, Android 2.3 + // Check the default checkbox/radio value ("" on old WebKit; "on" elsewhere) + support.checkOn = input.value !== ""; + + // Must access the parent to make an option select properly + // Support: IE9, IE10 + support.optSelected = opt.selected; + + // Will be defined later + support.reliableMarginRight = true; + support.boxSizingReliable = true; + support.pixelPosition = false; + + // Make sure checked status is properly cloned + // Support: IE9, IE10 + input.checked = true; + support.noCloneChecked = input.cloneNode( true ).checked; + + // Make sure that the options inside disabled selects aren't marked as disabled + // (WebKit marks them as disabled) + select.disabled = true; + support.optDisabled = !opt.disabled; + + // Check if an input maintains its value after becoming a radio + // Support: IE9, IE10 + input = document.createElement("input"); + input.value = "t"; + input.type = "radio"; + support.radioValue = input.value === "t"; + + // #11217 - WebKit loses check when the name is after the checked attribute + input.setAttribute( "checked", "t" ); + input.setAttribute( "name", "t" ); + + fragment.appendChild( input ); + + // Support: Safari 5.1, Android 4.x, Android 2.3 + // old WebKit doesn't clone checked state correctly in fragments + support.checkClone = fragment.cloneNode( true ).cloneNode( true ).lastChild.checked; + + // Support: Firefox, Chrome, Safari + // Beware of CSP restrictions (https://developer.mozilla.org/en/Security/CSP) + support.focusinBubbles = "onfocusin" in window; + + div.style.backgroundClip = "content-box"; + div.cloneNode( true ).style.backgroundClip = ""; + support.clearCloneStyle = div.style.backgroundClip === "content-box"; + + // Run tests that need a body at doc ready + jQuery(function() { + var container, marginDiv, + // Support: Firefox, Android 2.3 (Prefixed box-sizing versions). + divReset = "padding:0;margin:0;border:0;display:block;-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box", + body = document.getElementsByTagName("body")[ 0 ]; + + if ( !body ) { + // Return for frameset docs that don't have a body + return; + } + + container = document.createElement("div"); + container.style.cssText = "border:0;width:0;height:0;position:absolute;top:0;left:-9999px;margin-top:1px"; + + // Check box-sizing and margin behavior. + body.appendChild( container ).appendChild( div ); + div.innerHTML = ""; + // Support: Firefox, Android 2.3 (Prefixed box-sizing versions). + div.style.cssText = "-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%"; + + // Workaround failing boxSizing test due to offsetWidth returning wrong value + // with some non-1 values of body zoom, ticket #13543 + jQuery.swap( body, body.style.zoom != null ? { zoom: 1 } : {}, function() { + support.boxSizing = div.offsetWidth === 4; + }); + + // Use window.getComputedStyle because jsdom on node.js will break without it. + if ( window.getComputedStyle ) { + support.pixelPosition = ( window.getComputedStyle( div, null ) || {} ).top !== "1%"; + support.boxSizingReliable = ( window.getComputedStyle( div, null ) || { width: "4px" } ).width === "4px"; + + // Support: Android 2.3 + // Check if div with explicit width and no margin-right incorrectly + // gets computed margin-right based on width of container. (#3333) + // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right + marginDiv = div.appendChild( document.createElement("div") ); + marginDiv.style.cssText = div.style.cssText = divReset; + marginDiv.style.marginRight = marginDiv.style.width = "0"; + div.style.width = "1px"; + + support.reliableMarginRight = + !parseFloat( ( window.getComputedStyle( marginDiv, null ) || {} ).marginRight ); + } + + body.removeChild( container ); + }); + + return support; +})( {} ); + +/* + Implementation Summary + + 1. Enforce API surface and semantic compatibility with 1.9.x branch + 2. Improve the module's maintainability by reducing the storage + paths to a single mechanism. + 3. Use the same single mechanism to support "private" and "user" data. + 4. _Never_ expose "private" data to user code (TODO: Drop _data, _removeData) + 5. Avoid exposing implementation details on user objects (eg. expando properties) + 6. Provide a clear path for implementation upgrade to WeakMap in 2014 +*/ +var data_user, data_priv, + rbrace = /(?:\{[\s\S]*\}|\[[\s\S]*\])$/, + rmultiDash = /([A-Z])/g; + +function Data() { + // Support: Android < 4, + // Old WebKit does not have Object.preventExtensions/freeze method, + // return new empty object instead with no [[set]] accessor + Object.defineProperty( this.cache = {}, 0, { + get: function() { + return {}; + } + }); + + this.expando = jQuery.expando + Math.random(); +} + +Data.uid = 1; + +Data.accepts = function( owner ) { + // Accepts only: + // - Node + // - Node.ELEMENT_NODE + // - Node.DOCUMENT_NODE + // - Object + // - Any + return owner.nodeType ? + owner.nodeType === 1 || owner.nodeType === 9 : true; +}; + +Data.prototype = { + key: function( owner ) { + // We can accept data for non-element nodes in modern browsers, + // but we should not, see #8335. + // Always return the key for a frozen object. + if ( !Data.accepts( owner ) ) { + return 0; + } + + var descriptor = {}, + // Check if the owner object already has a cache key + unlock = owner[ this.expando ]; + + // If not, create one + if ( !unlock ) { + unlock = Data.uid++; + + // Secure it in a non-enumerable, non-writable property + try { + descriptor[ this.expando ] = { value: unlock }; + Object.defineProperties( owner, descriptor ); + + // Support: Android < 4 + // Fallback to a less secure definition + } catch ( e ) { + descriptor[ this.expando ] = unlock; + jQuery.extend( owner, descriptor ); + } + } + + // Ensure the cache object + if ( !this.cache[ unlock ] ) { + this.cache[ unlock ] = {}; + } + + return unlock; + }, + set: function( owner, data, value ) { + var prop, + // There may be an unlock assigned to this node, + // if there is no entry for this "owner", create one inline + // and set the unlock as though an owner entry had always existed + unlock = this.key( owner ), + cache = this.cache[ unlock ]; + + // Handle: [ owner, key, value ] args + if ( typeof data === "string" ) { + cache[ data ] = value; + + // Handle: [ owner, { properties } ] args + } else { + // Fresh assignments by object are shallow copied + if ( jQuery.isEmptyObject( cache ) ) { + jQuery.extend( this.cache[ unlock ], data ); + // Otherwise, copy the properties one-by-one to the cache object + } else { + for ( prop in data ) { + cache[ prop ] = data[ prop ]; + } + } + } + return cache; + }, + get: function( owner, key ) { + // Either a valid cache is found, or will be created. + // New caches will be created and the unlock returned, + // allowing direct access to the newly created + // empty data object. A valid owner object must be provided. + var cache = this.cache[ this.key( owner ) ]; + + return key === undefined ? + cache : cache[ key ]; + }, + access: function( owner, key, value ) { + var stored; + // In cases where either: + // + // 1. No key was specified + // 2. A string key was specified, but no value provided + // + // Take the "read" path and allow the get method to determine + // which value to return, respectively either: + // + // 1. The entire cache object + // 2. The data stored at the key + // + if ( key === undefined || + ((key && typeof key === "string") && value === undefined) ) { + + stored = this.get( owner, key ); + + return stored !== undefined ? + stored : this.get( owner, jQuery.camelCase(key) ); + } + + // [*]When the key is not a string, or both a key and value + // are specified, set or extend (existing objects) with either: + // + // 1. An object of properties + // 2. A key and value + // + this.set( owner, key, value ); + + // Since the "set" path can have two possible entry points + // return the expected data based on which path was taken[*] + return value !== undefined ? value : key; + }, + remove: function( owner, key ) { + var i, name, camel, + unlock = this.key( owner ), + cache = this.cache[ unlock ]; + + if ( key === undefined ) { + this.cache[ unlock ] = {}; + + } else { + // Support array or space separated string of keys + if ( jQuery.isArray( key ) ) { + // If "name" is an array of keys... + // When data is initially created, via ("key", "val") signature, + // keys will be converted to camelCase. + // Since there is no way to tell _how_ a key was added, remove + // both plain key and camelCase key. #12786 + // This will only penalize the array argument path. + name = key.concat( key.map( jQuery.camelCase ) ); + } else { + camel = jQuery.camelCase( key ); + // Try the string as a key before any manipulation + if ( key in cache ) { + name = [ key, camel ]; + } else { + // If a key with the spaces exists, use it. + // Otherwise, create an array by matching non-whitespace + name = camel; + name = name in cache ? + [ name ] : ( name.match( core_rnotwhite ) || [] ); + } + } + + i = name.length; + while ( i-- ) { + delete cache[ name[ i ] ]; + } + } + }, + hasData: function( owner ) { + return !jQuery.isEmptyObject( + this.cache[ owner[ this.expando ] ] || {} + ); + }, + discard: function( owner ) { + if ( owner[ this.expando ] ) { + delete this.cache[ owner[ this.expando ] ]; + } + } +}; + +// These may be used throughout the jQuery core codebase +data_user = new Data(); +data_priv = new Data(); + + +jQuery.extend({ + acceptData: Data.accepts, + + hasData: function( elem ) { + return data_user.hasData( elem ) || data_priv.hasData( elem ); + }, + + data: function( elem, name, data ) { + return data_user.access( elem, name, data ); + }, + + removeData: function( elem, name ) { + data_user.remove( elem, name ); + }, + + // TODO: Now that all calls to _data and _removeData have been replaced + // with direct calls to data_priv methods, these can be deprecated. + _data: function( elem, name, data ) { + return data_priv.access( elem, name, data ); + }, + + _removeData: function( elem, name ) { + data_priv.remove( elem, name ); + } +}); + +jQuery.fn.extend({ + data: function( key, value ) { + var attrs, name, + elem = this[ 0 ], + i = 0, + data = null; + + // Gets all values + if ( key === undefined ) { + if ( this.length ) { + data = data_user.get( elem ); + + if ( elem.nodeType === 1 && !data_priv.get( elem, "hasDataAttrs" ) ) { + attrs = elem.attributes; + for ( ; i < attrs.length; i++ ) { + name = attrs[ i ].name; + + if ( name.indexOf( "data-" ) === 0 ) { + name = jQuery.camelCase( name.slice(5) ); + dataAttr( elem, name, data[ name ] ); + } + } + data_priv.set( elem, "hasDataAttrs", true ); + } + } + + return data; + } + + // Sets multiple values + if ( typeof key === "object" ) { + return this.each(function() { + data_user.set( this, key ); + }); + } + + return jQuery.access( this, function( value ) { + var data, + camelKey = jQuery.camelCase( key ); + + // The calling jQuery object (element matches) is not empty + // (and therefore has an element appears at this[ 0 ]) and the + // `value` parameter was not undefined. An empty jQuery object + // will result in `undefined` for elem = this[ 0 ] which will + // throw an exception if an attempt to read a data cache is made. + if ( elem && value === undefined ) { + // Attempt to get data from the cache + // with the key as-is + data = data_user.get( elem, key ); + if ( data !== undefined ) { + return data; + } + + // Attempt to get data from the cache + // with the key camelized + data = data_user.get( elem, camelKey ); + if ( data !== undefined ) { + return data; + } + + // Attempt to "discover" the data in + // HTML5 custom data-* attrs + data = dataAttr( elem, camelKey, undefined ); + if ( data !== undefined ) { + return data; + } + + // We tried really hard, but the data doesn't exist. + return; + } + + // Set the data... + this.each(function() { + // First, attempt to store a copy or reference of any + // data that might've been store with a camelCased key. + var data = data_user.get( this, camelKey ); + + // For HTML5 data-* attribute interop, we have to + // store property names with dashes in a camelCase form. + // This might not apply to all properties...* + data_user.set( this, camelKey, value ); + + // *... In the case of properties that might _actually_ + // have dashes, we need to also store a copy of that + // unchanged property. + if ( key.indexOf("-") !== -1 && data !== undefined ) { + data_user.set( this, key, value ); + } + }); + }, null, value, arguments.length > 1, null, true ); + }, + + removeData: function( key ) { + return this.each(function() { + data_user.remove( this, key ); + }); + } +}); + +function dataAttr( elem, key, data ) { + var name; + + // If nothing was found internally, try to fetch any + // data from the HTML5 data-* attribute + if ( data === undefined && elem.nodeType === 1 ) { + name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase(); + data = elem.getAttribute( name ); + + if ( typeof data === "string" ) { + try { + data = data === "true" ? true : + data === "false" ? false : + data === "null" ? null : + // Only convert to a number if it doesn't change the string + +data + "" === data ? +data : + rbrace.test( data ) ? JSON.parse( data ) : + data; + } catch( e ) {} + + // Make sure we set the data so it isn't changed later + data_user.set( elem, key, data ); + } else { + data = undefined; + } + } + return data; +} +jQuery.extend({ + queue: function( elem, type, data ) { + var queue; + + if ( elem ) { + type = ( type || "fx" ) + "queue"; + queue = data_priv.get( elem, type ); + + // Speed up dequeue by getting out quickly if this is just a lookup + if ( data ) { + if ( !queue || jQuery.isArray( data ) ) { + queue = data_priv.access( elem, type, jQuery.makeArray(data) ); + } else { + queue.push( data ); + } + } + return queue || []; + } + }, + + dequeue: function( elem, type ) { + type = type || "fx"; + + var queue = jQuery.queue( elem, type ), + startLength = queue.length, + fn = queue.shift(), + hooks = jQuery._queueHooks( elem, type ), + next = function() { + jQuery.dequeue( elem, type ); + }; + + // If the fx queue is dequeued, always remove the progress sentinel + if ( fn === "inprogress" ) { + fn = queue.shift(); + startLength--; + } + + if ( fn ) { + + // Add a progress sentinel to prevent the fx queue from being + // automatically dequeued + if ( type === "fx" ) { + queue.unshift( "inprogress" ); + } + + // clear up the last queue stop function + delete hooks.stop; + fn.call( elem, next, hooks ); + } + + if ( !startLength && hooks ) { + hooks.empty.fire(); + } + }, + + // not intended for public consumption - generates a queueHooks object, or returns the current one + _queueHooks: function( elem, type ) { + var key = type + "queueHooks"; + return data_priv.get( elem, key ) || data_priv.access( elem, key, { + empty: jQuery.Callbacks("once memory").add(function() { + data_priv.remove( elem, [ type + "queue", key ] ); + }) + }); + } +}); + +jQuery.fn.extend({ + queue: function( type, data ) { + var setter = 2; + + if ( typeof type !== "string" ) { + data = type; + type = "fx"; + setter--; + } + + if ( arguments.length < setter ) { + return jQuery.queue( this[0], type ); + } + + return data === undefined ? + this : + this.each(function() { + var queue = jQuery.queue( this, type, data ); + + // ensure a hooks for this queue + jQuery._queueHooks( this, type ); + + if ( type === "fx" && queue[0] !== "inprogress" ) { + jQuery.dequeue( this, type ); + } + }); + }, + dequeue: function( type ) { + return this.each(function() { + jQuery.dequeue( this, type ); + }); + }, + // Based off of the plugin by Clint Helfers, with permission. + // http://blindsignals.com/index.php/2009/07/jquery-delay/ + delay: function( time, type ) { + time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time; + type = type || "fx"; + + return this.queue( type, function( next, hooks ) { + var timeout = setTimeout( next, time ); + hooks.stop = function() { + clearTimeout( timeout ); + }; + }); + }, + clearQueue: function( type ) { + return this.queue( type || "fx", [] ); + }, + // Get a promise resolved when queues of a certain type + // are emptied (fx is the type by default) + promise: function( type, obj ) { + var tmp, + count = 1, + defer = jQuery.Deferred(), + elements = this, + i = this.length, + resolve = function() { + if ( !( --count ) ) { + defer.resolveWith( elements, [ elements ] ); + } + }; + + if ( typeof type !== "string" ) { + obj = type; + type = undefined; + } + type = type || "fx"; + + while( i-- ) { + tmp = data_priv.get( elements[ i ], type + "queueHooks" ); + if ( tmp && tmp.empty ) { + count++; + tmp.empty.add( resolve ); + } + } + resolve(); + return defer.promise( obj ); + } +}); +var nodeHook, boolHook, + rclass = /[\t\r\n\f]/g, + rreturn = /\r/g, + rfocusable = /^(?:input|select|textarea|button)$/i; + +jQuery.fn.extend({ + attr: function( name, value ) { + return jQuery.access( this, jQuery.attr, name, value, arguments.length > 1 ); + }, + + removeAttr: function( name ) { + return this.each(function() { + jQuery.removeAttr( this, name ); + }); + }, + + prop: function( name, value ) { + return jQuery.access( this, jQuery.prop, name, value, arguments.length > 1 ); + }, + + removeProp: function( name ) { + return this.each(function() { + delete this[ jQuery.propFix[ name ] || name ]; + }); + }, + + addClass: function( value ) { + var classes, elem, cur, clazz, j, + i = 0, + len = this.length, + proceed = typeof value === "string" && value; + + if ( jQuery.isFunction( value ) ) { + return this.each(function( j ) { + jQuery( this ).addClass( value.call( this, j, this.className ) ); + }); + } + + if ( proceed ) { + // The disjunction here is for better compressibility (see removeClass) + classes = ( value || "" ).match( core_rnotwhite ) || []; + + for ( ; i < len; i++ ) { + elem = this[ i ]; + cur = elem.nodeType === 1 && ( elem.className ? + ( " " + elem.className + " " ).replace( rclass, " " ) : + " " + ); + + if ( cur ) { + j = 0; + while ( (clazz = classes[j++]) ) { + if ( cur.indexOf( " " + clazz + " " ) < 0 ) { + cur += clazz + " "; + } + } + elem.className = jQuery.trim( cur ); + + } + } + } + + return this; + }, + + removeClass: function( value ) { + var classes, elem, cur, clazz, j, + i = 0, + len = this.length, + proceed = arguments.length === 0 || typeof value === "string" && value; + + if ( jQuery.isFunction( value ) ) { + return this.each(function( j ) { + jQuery( this ).removeClass( value.call( this, j, this.className ) ); + }); + } + if ( proceed ) { + classes = ( value || "" ).match( core_rnotwhite ) || []; + + for ( ; i < len; i++ ) { + elem = this[ i ]; + // This expression is here for better compressibility (see addClass) + cur = elem.nodeType === 1 && ( elem.className ? + ( " " + elem.className + " " ).replace( rclass, " " ) : + "" + ); + + if ( cur ) { + j = 0; + while ( (clazz = classes[j++]) ) { + // Remove *all* instances + while ( cur.indexOf( " " + clazz + " " ) >= 0 ) { + cur = cur.replace( " " + clazz + " ", " " ); + } + } + elem.className = value ? jQuery.trim( cur ) : ""; + } + } + } + + return this; + }, + + toggleClass: function( value, stateVal ) { + var type = typeof value; + + if ( typeof stateVal === "boolean" && type === "string" ) { + return stateVal ? this.addClass( value ) : this.removeClass( value ); + } + + if ( jQuery.isFunction( value ) ) { + return this.each(function( i ) { + jQuery( this ).toggleClass( value.call(this, i, this.className, stateVal), stateVal ); + }); + } + + return this.each(function() { + if ( type === "string" ) { + // toggle individual class names + var className, + i = 0, + self = jQuery( this ), + classNames = value.match( core_rnotwhite ) || []; + + while ( (className = classNames[ i++ ]) ) { + // check each className given, space separated list + if ( self.hasClass( className ) ) { + self.removeClass( className ); + } else { + self.addClass( className ); + } + } + + // Toggle whole class name + } else if ( type === core_strundefined || type === "boolean" ) { + if ( this.className ) { + // store className if set + data_priv.set( this, "__className__", this.className ); + } + + // If the element has a class name or if we're passed "false", + // then remove the whole classname (if there was one, the above saved it). + // Otherwise bring back whatever was previously saved (if anything), + // falling back to the empty string if nothing was stored. + this.className = this.className || value === false ? "" : data_priv.get( this, "__className__" ) || ""; + } + }); + }, + + hasClass: function( selector ) { + var className = " " + selector + " ", + i = 0, + l = this.length; + for ( ; i < l; i++ ) { + if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) >= 0 ) { + return true; + } + } + + return false; + }, + + val: function( value ) { + var hooks, ret, isFunction, + elem = this[0]; + + if ( !arguments.length ) { + if ( elem ) { + hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ]; + + if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) { + return ret; + } + + ret = elem.value; + + return typeof ret === "string" ? + // handle most common string cases + ret.replace(rreturn, "") : + // handle cases where value is null/undef or number + ret == null ? "" : ret; + } + + return; + } + + isFunction = jQuery.isFunction( value ); + + return this.each(function( i ) { + var val; + + if ( this.nodeType !== 1 ) { + return; + } + + if ( isFunction ) { + val = value.call( this, i, jQuery( this ).val() ); + } else { + val = value; + } + + // Treat null/undefined as ""; convert numbers to string + if ( val == null ) { + val = ""; + } else if ( typeof val === "number" ) { + val += ""; + } else if ( jQuery.isArray( val ) ) { + val = jQuery.map(val, function ( value ) { + return value == null ? "" : value + ""; + }); + } + + hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ]; + + // If set returns undefined, fall back to normal setting + if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) { + this.value = val; + } + }); + } +}); + +jQuery.extend({ + valHooks: { + option: { + get: function( elem ) { + // attributes.value is undefined in Blackberry 4.7 but + // uses .value. See #6932 + var val = elem.attributes.value; + return !val || val.specified ? elem.value : elem.text; + } + }, + select: { + get: function( elem ) { + var value, option, + options = elem.options, + index = elem.selectedIndex, + one = elem.type === "select-one" || index < 0, + values = one ? null : [], + max = one ? index + 1 : options.length, + i = index < 0 ? + max : + one ? index : 0; + + // Loop through all the selected options + for ( ; i < max; i++ ) { + option = options[ i ]; + + // IE6-9 doesn't update selected after form reset (#2551) + if ( ( option.selected || i === index ) && + // Don't return options that are disabled or in a disabled optgroup + ( jQuery.support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null ) && + ( !option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" ) ) ) { + + // Get the specific value for the option + value = jQuery( option ).val(); + + // We don't need an array for one selects + if ( one ) { + return value; + } + + // Multi-Selects return an array + values.push( value ); + } + } + + return values; + }, + + set: function( elem, value ) { + var optionSet, option, + options = elem.options, + values = jQuery.makeArray( value ), + i = options.length; + + while ( i-- ) { + option = options[ i ]; + if ( (option.selected = jQuery.inArray( jQuery(option).val(), values ) >= 0) ) { + optionSet = true; + } + } + + // force browsers to behave consistently when non-matching value is set + if ( !optionSet ) { + elem.selectedIndex = -1; + } + return values; + } + } + }, + + attr: function( elem, name, value ) { + var hooks, ret, + nType = elem.nodeType; + + // don't get/set attributes on text, comment and attribute nodes + if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { + return; + } + + // Fallback to prop when attributes are not supported + if ( typeof elem.getAttribute === core_strundefined ) { + return jQuery.prop( elem, name, value ); + } + + // All attributes are lowercase + // Grab necessary hook if one is defined + if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) { + name = name.toLowerCase(); + hooks = jQuery.attrHooks[ name ] || + ( jQuery.expr.match.bool.test( name ) ? boolHook : nodeHook ); + } + + if ( value !== undefined ) { + + if ( value === null ) { + jQuery.removeAttr( elem, name ); + + } else if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) { + return ret; + + } else { + elem.setAttribute( name, value + "" ); + return value; + } + + } else if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) { + return ret; + + } else { + ret = jQuery.find.attr( elem, name ); + + // Non-existent attributes return null, we normalize to undefined + return ret == null ? + undefined : + ret; + } + }, + + removeAttr: function( elem, value ) { + var name, propName, + i = 0, + attrNames = value && value.match( core_rnotwhite ); + + if ( attrNames && elem.nodeType === 1 ) { + while ( (name = attrNames[i++]) ) { + propName = jQuery.propFix[ name ] || name; + + // Boolean attributes get special treatment (#10870) + if ( jQuery.expr.match.bool.test( name ) ) { + // Set corresponding property to false + elem[ propName ] = false; + } + + elem.removeAttribute( name ); + } + } + }, + + attrHooks: { + type: { + set: function( elem, value ) { + if ( !jQuery.support.radioValue && value === "radio" && jQuery.nodeName(elem, "input") ) { + // Setting the type on a radio button after the value resets the value in IE6-9 + // Reset value to default in case type is set after value during creation + var val = elem.value; + elem.setAttribute( "type", value ); + if ( val ) { + elem.value = val; + } + return value; + } + } + } + }, + + propFix: { + "for": "htmlFor", + "class": "className" + }, + + prop: function( elem, name, value ) { + var ret, hooks, notxml, + nType = elem.nodeType; + + // don't get/set properties on text, comment and attribute nodes + if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { + return; + } + + notxml = nType !== 1 || !jQuery.isXMLDoc( elem ); + + if ( notxml ) { + // Fix name and attach hooks + name = jQuery.propFix[ name ] || name; + hooks = jQuery.propHooks[ name ]; + } + + if ( value !== undefined ) { + return hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ? + ret : + ( elem[ name ] = value ); + + } else { + return hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ? + ret : + elem[ name ]; + } + }, + + propHooks: { + tabIndex: { + get: function( elem ) { + return elem.hasAttribute( "tabindex" ) || rfocusable.test( elem.nodeName ) || elem.href ? + elem.tabIndex : + -1; + } + } + } +}); + +// Hooks for boolean attributes +boolHook = { + set: function( elem, value, name ) { + if ( value === false ) { + // Remove boolean attributes when set to false + jQuery.removeAttr( elem, name ); + } else { + elem.setAttribute( name, name ); + } + return name; + } +}; +jQuery.each( jQuery.expr.match.bool.source.match( /\w+/g ), function( i, name ) { + var getter = jQuery.expr.attrHandle[ name ] || jQuery.find.attr; + + jQuery.expr.attrHandle[ name ] = function( elem, name, isXML ) { + var fn = jQuery.expr.attrHandle[ name ], + ret = isXML ? + undefined : + /* jshint eqeqeq: false */ + // Temporarily disable this handler to check existence + (jQuery.expr.attrHandle[ name ] = undefined) != + getter( elem, name, isXML ) ? + + name.toLowerCase() : + null; + + // Restore handler + jQuery.expr.attrHandle[ name ] = fn; + + return ret; + }; +}); + +// Support: IE9+ +// Selectedness for an option in an optgroup can be inaccurate +if ( !jQuery.support.optSelected ) { + jQuery.propHooks.selected = { + get: function( elem ) { + var parent = elem.parentNode; + if ( parent && parent.parentNode ) { + parent.parentNode.selectedIndex; + } + return null; + } + }; +} + +jQuery.each([ + "tabIndex", + "readOnly", + "maxLength", + "cellSpacing", + "cellPadding", + "rowSpan", + "colSpan", + "useMap", + "frameBorder", + "contentEditable" +], function() { + jQuery.propFix[ this.toLowerCase() ] = this; +}); + +// Radios and checkboxes getter/setter +jQuery.each([ "radio", "checkbox" ], function() { + jQuery.valHooks[ this ] = { + set: function( elem, value ) { + if ( jQuery.isArray( value ) ) { + return ( elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0 ); + } + } + }; + if ( !jQuery.support.checkOn ) { + jQuery.valHooks[ this ].get = function( elem ) { + // Support: Webkit + // "" is returned instead of "on" if a value isn't specified + return elem.getAttribute("value") === null ? "on" : elem.value; + }; + } +}); +var rkeyEvent = /^key/, + rmouseEvent = /^(?:mouse|contextmenu)|click/, + rfocusMorph = /^(?:focusinfocus|focusoutblur)$/, + rtypenamespace = /^([^.]*)(?:\.(.+)|)$/; + +function returnTrue() { + return true; +} + +function returnFalse() { + return false; +} + +function safeActiveElement() { + try { + return document.activeElement; + } catch ( err ) { } +} + +/* + * Helper functions for managing events -- not part of the public interface. + * Props to Dean Edwards' addEvent library for many of the ideas. + */ +jQuery.event = { + + global: {}, + + add: function( elem, types, handler, data, selector ) { + + var handleObjIn, eventHandle, tmp, + events, t, handleObj, + special, handlers, type, namespaces, origType, + elemData = data_priv.get( elem ); + + // Don't attach events to noData or text/comment nodes (but allow plain objects) + if ( !elemData ) { + return; + } + + // Caller can pass in an object of custom data in lieu of the handler + if ( handler.handler ) { + handleObjIn = handler; + handler = handleObjIn.handler; + selector = handleObjIn.selector; + } + + // Make sure that the handler has a unique ID, used to find/remove it later + if ( !handler.guid ) { + handler.guid = jQuery.guid++; + } + + // Init the element's event structure and main handler, if this is the first + if ( !(events = elemData.events) ) { + events = elemData.events = {}; + } + if ( !(eventHandle = elemData.handle) ) { + eventHandle = elemData.handle = function( e ) { + // Discard the second event of a jQuery.event.trigger() and + // when an event is called after a page has unloaded + return typeof jQuery !== core_strundefined && (!e || jQuery.event.triggered !== e.type) ? + jQuery.event.dispatch.apply( eventHandle.elem, arguments ) : + undefined; + }; + // Add elem as a property of the handle fn to prevent a memory leak with IE non-native events + eventHandle.elem = elem; + } + + // Handle multiple events separated by a space + types = ( types || "" ).match( core_rnotwhite ) || [""]; + t = types.length; + while ( t-- ) { + tmp = rtypenamespace.exec( types[t] ) || []; + type = origType = tmp[1]; + namespaces = ( tmp[2] || "" ).split( "." ).sort(); + + // There *must* be a type, no attaching namespace-only handlers + if ( !type ) { + continue; + } + + // If event changes its type, use the special event handlers for the changed type + special = jQuery.event.special[ type ] || {}; + + // If selector defined, determine special event api type, otherwise given type + type = ( selector ? special.delegateType : special.bindType ) || type; + + // Update special based on newly reset type + special = jQuery.event.special[ type ] || {}; + + // handleObj is passed to all event handlers + handleObj = jQuery.extend({ + type: type, + origType: origType, + data: data, + handler: handler, + guid: handler.guid, + selector: selector, + needsContext: selector && jQuery.expr.match.needsContext.test( selector ), + namespace: namespaces.join(".") + }, handleObjIn ); + + // Init the event handler queue if we're the first + if ( !(handlers = events[ type ]) ) { + handlers = events[ type ] = []; + handlers.delegateCount = 0; + + // Only use addEventListener if the special events handler returns false + if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) { + if ( elem.addEventListener ) { + elem.addEventListener( type, eventHandle, false ); + } + } + } + + if ( special.add ) { + special.add.call( elem, handleObj ); + + if ( !handleObj.handler.guid ) { + handleObj.handler.guid = handler.guid; + } + } + + // Add to the element's handler list, delegates in front + if ( selector ) { + handlers.splice( handlers.delegateCount++, 0, handleObj ); + } else { + handlers.push( handleObj ); + } + + // Keep track of which events have ever been used, for event optimization + jQuery.event.global[ type ] = true; + } + + // Nullify elem to prevent memory leaks in IE + elem = null; + }, + + // Detach an event or set of events from an element + remove: function( elem, types, handler, selector, mappedTypes ) { + + var j, origCount, tmp, + events, t, handleObj, + special, handlers, type, namespaces, origType, + elemData = data_priv.hasData( elem ) && data_priv.get( elem ); + + if ( !elemData || !(events = elemData.events) ) { + return; + } + + // Once for each type.namespace in types; type may be omitted + types = ( types || "" ).match( core_rnotwhite ) || [""]; + t = types.length; + while ( t-- ) { + tmp = rtypenamespace.exec( types[t] ) || []; + type = origType = tmp[1]; + namespaces = ( tmp[2] || "" ).split( "." ).sort(); + + // Unbind all events (on this namespace, if provided) for the element + if ( !type ) { + for ( type in events ) { + jQuery.event.remove( elem, type + types[ t ], handler, selector, true ); + } + continue; + } + + special = jQuery.event.special[ type ] || {}; + type = ( selector ? special.delegateType : special.bindType ) || type; + handlers = events[ type ] || []; + tmp = tmp[2] && new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ); + + // Remove matching events + origCount = j = handlers.length; + while ( j-- ) { + handleObj = handlers[ j ]; + + if ( ( mappedTypes || origType === handleObj.origType ) && + ( !handler || handler.guid === handleObj.guid ) && + ( !tmp || tmp.test( handleObj.namespace ) ) && + ( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) { + handlers.splice( j, 1 ); + + if ( handleObj.selector ) { + handlers.delegateCount--; + } + if ( special.remove ) { + special.remove.call( elem, handleObj ); + } + } + } + + // Remove generic event handler if we removed something and no more handlers exist + // (avoids potential for endless recursion during removal of special event handlers) + if ( origCount && !handlers.length ) { + if ( !special.teardown || special.teardown.call( elem, namespaces, elemData.handle ) === false ) { + jQuery.removeEvent( elem, type, elemData.handle ); + } + + delete events[ type ]; + } + } + + // Remove the expando if it's no longer used + if ( jQuery.isEmptyObject( events ) ) { + delete elemData.handle; + data_priv.remove( elem, "events" ); + } + }, + + trigger: function( event, data, elem, onlyHandlers ) { + + var i, cur, tmp, bubbleType, ontype, handle, special, + eventPath = [ elem || document ], + type = core_hasOwn.call( event, "type" ) ? event.type : event, + namespaces = core_hasOwn.call( event, "namespace" ) ? event.namespace.split(".") : []; + + cur = tmp = elem = elem || document; + + // Don't do events on text and comment nodes + if ( elem.nodeType === 3 || elem.nodeType === 8 ) { + return; + } + + // focus/blur morphs to focusin/out; ensure we're not firing them right now + if ( rfocusMorph.test( type + jQuery.event.triggered ) ) { + return; + } + + if ( type.indexOf(".") >= 0 ) { + // Namespaced trigger; create a regexp to match event type in handle() + namespaces = type.split("."); + type = namespaces.shift(); + namespaces.sort(); + } + ontype = type.indexOf(":") < 0 && "on" + type; + + // Caller can pass in a jQuery.Event object, Object, or just an event type string + event = event[ jQuery.expando ] ? + event : + new jQuery.Event( type, typeof event === "object" && event ); + + // Trigger bitmask: & 1 for native handlers; & 2 for jQuery (always true) + event.isTrigger = onlyHandlers ? 2 : 3; + event.namespace = namespaces.join("."); + event.namespace_re = event.namespace ? + new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ) : + null; + + // Clean up the event in case it is being reused + event.result = undefined; + if ( !event.target ) { + event.target = elem; + } + + // Clone any incoming data and prepend the event, creating the handler arg list + data = data == null ? + [ event ] : + jQuery.makeArray( data, [ event ] ); + + // Allow special events to draw outside the lines + special = jQuery.event.special[ type ] || {}; + if ( !onlyHandlers && special.trigger && special.trigger.apply( elem, data ) === false ) { + return; + } + + // Determine event propagation path in advance, per W3C events spec (#9951) + // Bubble up to document, then to window; watch for a global ownerDocument var (#9724) + if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) { + + bubbleType = special.delegateType || type; + if ( !rfocusMorph.test( bubbleType + type ) ) { + cur = cur.parentNode; + } + for ( ; cur; cur = cur.parentNode ) { + eventPath.push( cur ); + tmp = cur; + } + + // Only add window if we got to document (e.g., not plain obj or detached DOM) + if ( tmp === (elem.ownerDocument || document) ) { + eventPath.push( tmp.defaultView || tmp.parentWindow || window ); + } + } + + // Fire handlers on the event path + i = 0; + while ( (cur = eventPath[i++]) && !event.isPropagationStopped() ) { + + event.type = i > 1 ? + bubbleType : + special.bindType || type; + + // jQuery handler + handle = ( data_priv.get( cur, "events" ) || {} )[ event.type ] && data_priv.get( cur, "handle" ); + if ( handle ) { + handle.apply( cur, data ); + } + + // Native handler + handle = ontype && cur[ ontype ]; + if ( handle && jQuery.acceptData( cur ) && handle.apply && handle.apply( cur, data ) === false ) { + event.preventDefault(); + } + } + event.type = type; + + // If nobody prevented the default action, do it now + if ( !onlyHandlers && !event.isDefaultPrevented() ) { + + if ( (!special._default || special._default.apply( eventPath.pop(), data ) === false) && + jQuery.acceptData( elem ) ) { + + // Call a native DOM method on the target with the same name name as the event. + // Don't do default actions on window, that's where global variables be (#6170) + if ( ontype && jQuery.isFunction( elem[ type ] ) && !jQuery.isWindow( elem ) ) { + + // Don't re-trigger an onFOO event when we call its FOO() method + tmp = elem[ ontype ]; + + if ( tmp ) { + elem[ ontype ] = null; + } + + // Prevent re-triggering of the same event, since we already bubbled it above + jQuery.event.triggered = type; + elem[ type ](); + jQuery.event.triggered = undefined; + + if ( tmp ) { + elem[ ontype ] = tmp; + } + } + } + } + + return event.result; + }, + + dispatch: function( event ) { + + // Make a writable jQuery.Event from the native event object + event = jQuery.event.fix( event ); + + var i, j, ret, matched, handleObj, + handlerQueue = [], + args = core_slice.call( arguments ), + handlers = ( data_priv.get( this, "events" ) || {} )[ event.type ] || [], + special = jQuery.event.special[ event.type ] || {}; + + // Use the fix-ed jQuery.Event rather than the (read-only) native event + args[0] = event; + event.delegateTarget = this; + + // Call the preDispatch hook for the mapped type, and let it bail if desired + if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) { + return; + } + + // Determine handlers + handlerQueue = jQuery.event.handlers.call( this, event, handlers ); + + // Run delegates first; they may want to stop propagation beneath us + i = 0; + while ( (matched = handlerQueue[ i++ ]) && !event.isPropagationStopped() ) { + event.currentTarget = matched.elem; + + j = 0; + while ( (handleObj = matched.handlers[ j++ ]) && !event.isImmediatePropagationStopped() ) { + + // Triggered event must either 1) have no namespace, or + // 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace). + if ( !event.namespace_re || event.namespace_re.test( handleObj.namespace ) ) { + + event.handleObj = handleObj; + event.data = handleObj.data; + + ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler ) + .apply( matched.elem, args ); + + if ( ret !== undefined ) { + if ( (event.result = ret) === false ) { + event.preventDefault(); + event.stopPropagation(); + } + } + } + } + } + + // Call the postDispatch hook for the mapped type + if ( special.postDispatch ) { + special.postDispatch.call( this, event ); + } + + return event.result; + }, + + handlers: function( event, handlers ) { + var i, matches, sel, handleObj, + handlerQueue = [], + delegateCount = handlers.delegateCount, + cur = event.target; + + // Find delegate handlers + // Black-hole SVG instance trees (#13180) + // Avoid non-left-click bubbling in Firefox (#3861) + if ( delegateCount && cur.nodeType && (!event.button || event.type !== "click") ) { + + for ( ; cur !== this; cur = cur.parentNode || this ) { + + // Don't process clicks on disabled elements (#6911, #8165, #11382, #11764) + if ( cur.disabled !== true || event.type !== "click" ) { + matches = []; + for ( i = 0; i < delegateCount; i++ ) { + handleObj = handlers[ i ]; + + // Don't conflict with Object.prototype properties (#13203) + sel = handleObj.selector + " "; + + if ( matches[ sel ] === undefined ) { + matches[ sel ] = handleObj.needsContext ? + jQuery( sel, this ).index( cur ) >= 0 : + jQuery.find( sel, this, null, [ cur ] ).length; + } + if ( matches[ sel ] ) { + matches.push( handleObj ); + } + } + if ( matches.length ) { + handlerQueue.push({ elem: cur, handlers: matches }); + } + } + } + } + + // Add the remaining (directly-bound) handlers + if ( delegateCount < handlers.length ) { + handlerQueue.push({ elem: this, handlers: handlers.slice( delegateCount ) }); + } + + return handlerQueue; + }, + + // Includes some event props shared by KeyEvent and MouseEvent + props: "altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "), + + fixHooks: {}, + + keyHooks: { + props: "char charCode key keyCode".split(" "), + filter: function( event, original ) { + + // Add which for key events + if ( event.which == null ) { + event.which = original.charCode != null ? original.charCode : original.keyCode; + } + + return event; + } + }, + + mouseHooks: { + props: "button buttons clientX clientY offsetX offsetY pageX pageY screenX screenY toElement".split(" "), + filter: function( event, original ) { + var eventDoc, doc, body, + button = original.button; + + // Calculate pageX/Y if missing and clientX/Y available + if ( event.pageX == null && original.clientX != null ) { + eventDoc = event.target.ownerDocument || document; + doc = eventDoc.documentElement; + body = eventDoc.body; + + event.pageX = original.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 ); + event.pageY = original.clientY + ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - ( doc && doc.clientTop || body && body.clientTop || 0 ); + } + + // Add which for click: 1 === left; 2 === middle; 3 === right + // Note: button is not normalized, so don't use it + if ( !event.which && button !== undefined ) { + event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) ); + } + + return event; + } + }, + + fix: function( event ) { + if ( event[ jQuery.expando ] ) { + return event; + } + + // Create a writable copy of the event object and normalize some properties + var i, prop, copy, + type = event.type, + originalEvent = event, + fixHook = this.fixHooks[ type ]; + + if ( !fixHook ) { + this.fixHooks[ type ] = fixHook = + rmouseEvent.test( type ) ? this.mouseHooks : + rkeyEvent.test( type ) ? this.keyHooks : + {}; + } + copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props; + + event = new jQuery.Event( originalEvent ); + + i = copy.length; + while ( i-- ) { + prop = copy[ i ]; + event[ prop ] = originalEvent[ prop ]; + } + + // Support: Cordova 2.5 (WebKit) (#13255) + // All events should have a target; Cordova deviceready doesn't + if ( !event.target ) { + event.target = document; + } + + // Support: Safari 6.0+, Chrome < 28 + // Target should not be a text node (#504, #13143) + if ( event.target.nodeType === 3 ) { + event.target = event.target.parentNode; + } + + return fixHook.filter? fixHook.filter( event, originalEvent ) : event; + }, + + special: { + load: { + // Prevent triggered image.load events from bubbling to window.load + noBubble: true + }, + focus: { + // Fire native event if possible so blur/focus sequence is correct + trigger: function() { + if ( this !== safeActiveElement() && this.focus ) { + this.focus(); + return false; + } + }, + delegateType: "focusin" + }, + blur: { + trigger: function() { + if ( this === safeActiveElement() && this.blur ) { + this.blur(); + return false; + } + }, + delegateType: "focusout" + }, + click: { + // For checkbox, fire native event so checked state will be right + trigger: function() { + if ( this.type === "checkbox" && this.click && jQuery.nodeName( this, "input" ) ) { + this.click(); + return false; + } + }, + + // For cross-browser consistency, don't fire native .click() on links + _default: function( event ) { + return jQuery.nodeName( event.target, "a" ); + } + }, + + beforeunload: { + postDispatch: function( event ) { + + // Support: Firefox 20+ + // Firefox doesn't alert if the returnValue field is not set. + if ( event.result !== undefined ) { + event.originalEvent.returnValue = event.result; + } + } + } + }, + + simulate: function( type, elem, event, bubble ) { + // Piggyback on a donor event to simulate a different one. + // Fake originalEvent to avoid donor's stopPropagation, but if the + // simulated event prevents default then we do the same on the donor. + var e = jQuery.extend( + new jQuery.Event(), + event, + { + type: type, + isSimulated: true, + originalEvent: {} + } + ); + if ( bubble ) { + jQuery.event.trigger( e, null, elem ); + } else { + jQuery.event.dispatch.call( elem, e ); + } + if ( e.isDefaultPrevented() ) { + event.preventDefault(); + } + } +}; + +jQuery.removeEvent = function( elem, type, handle ) { + if ( elem.removeEventListener ) { + elem.removeEventListener( type, handle, false ); + } +}; + +jQuery.Event = function( src, props ) { + // Allow instantiation without the 'new' keyword + if ( !(this instanceof jQuery.Event) ) { + return new jQuery.Event( src, props ); + } + + // Event object + if ( src && src.type ) { + this.originalEvent = src; + this.type = src.type; + + // Events bubbling up the document may have been marked as prevented + // by a handler lower down the tree; reflect the correct value. + this.isDefaultPrevented = ( src.defaultPrevented || + src.getPreventDefault && src.getPreventDefault() ) ? returnTrue : returnFalse; + + // Event type + } else { + this.type = src; + } + + // Put explicitly provided properties onto the event object + if ( props ) { + jQuery.extend( this, props ); + } + + // Create a timestamp if incoming event doesn't have one + this.timeStamp = src && src.timeStamp || jQuery.now(); + + // Mark it as fixed + this[ jQuery.expando ] = true; +}; + +// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding +// http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html +jQuery.Event.prototype = { + isDefaultPrevented: returnFalse, + isPropagationStopped: returnFalse, + isImmediatePropagationStopped: returnFalse, + + preventDefault: function() { + var e = this.originalEvent; + + this.isDefaultPrevented = returnTrue; + + if ( e && e.preventDefault ) { + e.preventDefault(); + } + }, + stopPropagation: function() { + var e = this.originalEvent; + + this.isPropagationStopped = returnTrue; + + if ( e && e.stopPropagation ) { + e.stopPropagation(); + } + }, + stopImmediatePropagation: function() { + this.isImmediatePropagationStopped = returnTrue; + this.stopPropagation(); + } +}; + +// Create mouseenter/leave events using mouseover/out and event-time checks +// Support: Chrome 15+ +jQuery.each({ + mouseenter: "mouseover", + mouseleave: "mouseout" +}, function( orig, fix ) { + jQuery.event.special[ orig ] = { + delegateType: fix, + bindType: fix, + + handle: function( event ) { + var ret, + target = this, + related = event.relatedTarget, + handleObj = event.handleObj; + + // For mousenter/leave call the handler if related is outside the target. + // NB: No relatedTarget if the mouse left/entered the browser window + if ( !related || (related !== target && !jQuery.contains( target, related )) ) { + event.type = handleObj.origType; + ret = handleObj.handler.apply( this, arguments ); + event.type = fix; + } + return ret; + } + }; +}); + +// Create "bubbling" focus and blur events +// Support: Firefox, Chrome, Safari +if ( !jQuery.support.focusinBubbles ) { + jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) { + + // Attach a single capturing handler while someone wants focusin/focusout + var attaches = 0, + handler = function( event ) { + jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true ); + }; + + jQuery.event.special[ fix ] = { + setup: function() { + if ( attaches++ === 0 ) { + document.addEventListener( orig, handler, true ); + } + }, + teardown: function() { + if ( --attaches === 0 ) { + document.removeEventListener( orig, handler, true ); + } + } + }; + }); +} + +jQuery.fn.extend({ + + on: function( types, selector, data, fn, /*INTERNAL*/ one ) { + var origFn, type; + + // Types can be a map of types/handlers + if ( typeof types === "object" ) { + // ( types-Object, selector, data ) + if ( typeof selector !== "string" ) { + // ( types-Object, data ) + data = data || selector; + selector = undefined; + } + for ( type in types ) { + this.on( type, selector, data, types[ type ], one ); + } + return this; + } + + if ( data == null && fn == null ) { + // ( types, fn ) + fn = selector; + data = selector = undefined; + } else if ( fn == null ) { + if ( typeof selector === "string" ) { + // ( types, selector, fn ) + fn = data; + data = undefined; + } else { + // ( types, data, fn ) + fn = data; + data = selector; + selector = undefined; + } + } + if ( fn === false ) { + fn = returnFalse; + } else if ( !fn ) { + return this; + } + + if ( one === 1 ) { + origFn = fn; + fn = function( event ) { + // Can use an empty set, since event contains the info + jQuery().off( event ); + return origFn.apply( this, arguments ); + }; + // Use same guid so caller can remove using origFn + fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ ); + } + return this.each( function() { + jQuery.event.add( this, types, fn, data, selector ); + }); + }, + one: function( types, selector, data, fn ) { + return this.on( types, selector, data, fn, 1 ); + }, + off: function( types, selector, fn ) { + var handleObj, type; + if ( types && types.preventDefault && types.handleObj ) { + // ( event ) dispatched jQuery.Event + handleObj = types.handleObj; + jQuery( types.delegateTarget ).off( + handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType, + handleObj.selector, + handleObj.handler + ); + return this; + } + if ( typeof types === "object" ) { + // ( types-object [, selector] ) + for ( type in types ) { + this.off( type, selector, types[ type ] ); + } + return this; + } + if ( selector === false || typeof selector === "function" ) { + // ( types [, fn] ) + fn = selector; + selector = undefined; + } + if ( fn === false ) { + fn = returnFalse; + } + return this.each(function() { + jQuery.event.remove( this, types, fn, selector ); + }); + }, + + trigger: function( type, data ) { + return this.each(function() { + jQuery.event.trigger( type, data, this ); + }); + }, + triggerHandler: function( type, data ) { + var elem = this[0]; + if ( elem ) { + return jQuery.event.trigger( type, data, elem, true ); + } + } +}); +var isSimple = /^.[^:#\[\.,]*$/, + rparentsprev = /^(?:parents|prev(?:Until|All))/, + rneedsContext = jQuery.expr.match.needsContext, + // methods guaranteed to produce a unique set when starting from a unique set + guaranteedUnique = { + children: true, + contents: true, + next: true, + prev: true + }; + +jQuery.fn.extend({ + find: function( selector ) { + var i, + ret = [], + self = this, + len = self.length; + + if ( typeof selector !== "string" ) { + return this.pushStack( jQuery( selector ).filter(function() { + for ( i = 0; i < len; i++ ) { + if ( jQuery.contains( self[ i ], this ) ) { + return true; + } + } + }) ); + } + + for ( i = 0; i < len; i++ ) { + jQuery.find( selector, self[ i ], ret ); + } + + // Needed because $( selector, context ) becomes $( context ).find( selector ) + ret = this.pushStack( len > 1 ? jQuery.unique( ret ) : ret ); + ret.selector = this.selector ? this.selector + " " + selector : selector; + return ret; + }, + + has: function( target ) { + var targets = jQuery( target, this ), + l = targets.length; + + return this.filter(function() { + var i = 0; + for ( ; i < l; i++ ) { + if ( jQuery.contains( this, targets[i] ) ) { + return true; + } + } + }); + }, + + not: function( selector ) { + return this.pushStack( winnow(this, selector || [], true) ); + }, + + filter: function( selector ) { + return this.pushStack( winnow(this, selector || [], false) ); + }, + + is: function( selector ) { + return !!winnow( + this, + + // If this is a positional/relative selector, check membership in the returned set + // so $("p:first").is("p:last") won't return true for a doc with two "p". + typeof selector === "string" && rneedsContext.test( selector ) ? + jQuery( selector ) : + selector || [], + false + ).length; + }, + + closest: function( selectors, context ) { + var cur, + i = 0, + l = this.length, + matched = [], + pos = ( rneedsContext.test( selectors ) || typeof selectors !== "string" ) ? + jQuery( selectors, context || this.context ) : + 0; + + for ( ; i < l; i++ ) { + for ( cur = this[i]; cur && cur !== context; cur = cur.parentNode ) { + // Always skip document fragments + if ( cur.nodeType < 11 && (pos ? + pos.index(cur) > -1 : + + // Don't pass non-elements to Sizzle + cur.nodeType === 1 && + jQuery.find.matchesSelector(cur, selectors)) ) { + + cur = matched.push( cur ); + break; + } + } + } + + return this.pushStack( matched.length > 1 ? jQuery.unique( matched ) : matched ); + }, + + // Determine the position of an element within + // the matched set of elements + index: function( elem ) { + + // No argument, return index in parent + if ( !elem ) { + return ( this[ 0 ] && this[ 0 ].parentNode ) ? this.first().prevAll().length : -1; + } + + // index in selector + if ( typeof elem === "string" ) { + return core_indexOf.call( jQuery( elem ), this[ 0 ] ); + } + + // Locate the position of the desired element + return core_indexOf.call( this, + + // If it receives a jQuery object, the first element is used + elem.jquery ? elem[ 0 ] : elem + ); + }, + + add: function( selector, context ) { + var set = typeof selector === "string" ? + jQuery( selector, context ) : + jQuery.makeArray( selector && selector.nodeType ? [ selector ] : selector ), + all = jQuery.merge( this.get(), set ); + + return this.pushStack( jQuery.unique(all) ); + }, + + addBack: function( selector ) { + return this.add( selector == null ? + this.prevObject : this.prevObject.filter(selector) + ); + } +}); + +function sibling( cur, dir ) { + while ( (cur = cur[dir]) && cur.nodeType !== 1 ) {} + + return cur; +} + +jQuery.each({ + parent: function( elem ) { + var parent = elem.parentNode; + return parent && parent.nodeType !== 11 ? parent : null; + }, + parents: function( elem ) { + return jQuery.dir( elem, "parentNode" ); + }, + parentsUntil: function( elem, i, until ) { + return jQuery.dir( elem, "parentNode", until ); + }, + next: function( elem ) { + return sibling( elem, "nextSibling" ); + }, + prev: function( elem ) { + return sibling( elem, "previousSibling" ); + }, + nextAll: function( elem ) { + return jQuery.dir( elem, "nextSibling" ); + }, + prevAll: function( elem ) { + return jQuery.dir( elem, "previousSibling" ); + }, + nextUntil: function( elem, i, until ) { + return jQuery.dir( elem, "nextSibling", until ); + }, + prevUntil: function( elem, i, until ) { + return jQuery.dir( elem, "previousSibling", until ); + }, + siblings: function( elem ) { + return jQuery.sibling( ( elem.parentNode || {} ).firstChild, elem ); + }, + children: function( elem ) { + return jQuery.sibling( elem.firstChild ); + }, + contents: function( elem ) { + return elem.contentDocument || jQuery.merge( [], elem.childNodes ); + } +}, function( name, fn ) { + jQuery.fn[ name ] = function( until, selector ) { + var matched = jQuery.map( this, fn, until ); + + if ( name.slice( -5 ) !== "Until" ) { + selector = until; + } + + if ( selector && typeof selector === "string" ) { + matched = jQuery.filter( selector, matched ); + } + + if ( this.length > 1 ) { + // Remove duplicates + if ( !guaranteedUnique[ name ] ) { + jQuery.unique( matched ); + } + + // Reverse order for parents* and prev-derivatives + if ( rparentsprev.test( name ) ) { + matched.reverse(); + } + } + + return this.pushStack( matched ); + }; +}); + +jQuery.extend({ + filter: function( expr, elems, not ) { + var elem = elems[ 0 ]; + + if ( not ) { + expr = ":not(" + expr + ")"; + } + + return elems.length === 1 && elem.nodeType === 1 ? + jQuery.find.matchesSelector( elem, expr ) ? [ elem ] : [] : + jQuery.find.matches( expr, jQuery.grep( elems, function( elem ) { + return elem.nodeType === 1; + })); + }, + + dir: function( elem, dir, until ) { + var matched = [], + truncate = until !== undefined; + + while ( (elem = elem[ dir ]) && elem.nodeType !== 9 ) { + if ( elem.nodeType === 1 ) { + if ( truncate && jQuery( elem ).is( until ) ) { + break; + } + matched.push( elem ); + } + } + return matched; + }, + + sibling: function( n, elem ) { + var matched = []; + + for ( ; n; n = n.nextSibling ) { + if ( n.nodeType === 1 && n !== elem ) { + matched.push( n ); + } + } + + return matched; + } +}); + +// Implement the identical functionality for filter and not +function winnow( elements, qualifier, not ) { + if ( jQuery.isFunction( qualifier ) ) { + return jQuery.grep( elements, function( elem, i ) { + /* jshint -W018 */ + return !!qualifier.call( elem, i, elem ) !== not; + }); + + } + + if ( qualifier.nodeType ) { + return jQuery.grep( elements, function( elem ) { + return ( elem === qualifier ) !== not; + }); + + } + + if ( typeof qualifier === "string" ) { + if ( isSimple.test( qualifier ) ) { + return jQuery.filter( qualifier, elements, not ); + } + + qualifier = jQuery.filter( qualifier, elements ); + } + + return jQuery.grep( elements, function( elem ) { + return ( core_indexOf.call( qualifier, elem ) >= 0 ) !== not; + }); +} +var rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi, + rtagName = /<([\w:]+)/, + rhtml = /<|&#?\w+;/, + rnoInnerhtml = /<(?:script|style|link)/i, + manipulation_rcheckableType = /^(?:checkbox|radio)$/i, + // checked="checked" or checked + rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i, + rscriptType = /^$|\/(?:java|ecma)script/i, + rscriptTypeMasked = /^true\/(.*)/, + rcleanScript = /^\s*\s*$/g, + + // We have to close these tags to support XHTML (#13200) + wrapMap = { + + // Support: IE 9 + option: [ 1, "" ], + + thead: [ 1, "", "
" ], + col: [ 2, "", "
" ], + tr: [ 2, "", "
" ], + td: [ 3, "", "
" ], + + _default: [ 0, "", "" ] + }; + +// Support: IE 9 +wrapMap.optgroup = wrapMap.option; + +wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; +wrapMap.th = wrapMap.td; + +jQuery.fn.extend({ + text: function( value ) { + return jQuery.access( this, function( value ) { + return value === undefined ? + jQuery.text( this ) : + this.empty().append( ( this[ 0 ] && this[ 0 ].ownerDocument || document ).createTextNode( value ) ); + }, null, value, arguments.length ); + }, + + append: function() { + return this.domManip( arguments, function( elem ) { + if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { + var target = manipulationTarget( this, elem ); + target.appendChild( elem ); + } + }); + }, + + prepend: function() { + return this.domManip( arguments, function( elem ) { + if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { + var target = manipulationTarget( this, elem ); + target.insertBefore( elem, target.firstChild ); + } + }); + }, + + before: function() { + return this.domManip( arguments, function( elem ) { + if ( this.parentNode ) { + this.parentNode.insertBefore( elem, this ); + } + }); + }, + + after: function() { + return this.domManip( arguments, function( elem ) { + if ( this.parentNode ) { + this.parentNode.insertBefore( elem, this.nextSibling ); + } + }); + }, + + // keepData is for internal use only--do not document + remove: function( selector, keepData ) { + var elem, + elems = selector ? jQuery.filter( selector, this ) : this, + i = 0; + + for ( ; (elem = elems[i]) != null; i++ ) { + if ( !keepData && elem.nodeType === 1 ) { + jQuery.cleanData( getAll( elem ) ); + } + + if ( elem.parentNode ) { + if ( keepData && jQuery.contains( elem.ownerDocument, elem ) ) { + setGlobalEval( getAll( elem, "script" ) ); + } + elem.parentNode.removeChild( elem ); + } + } + + return this; + }, + + empty: function() { + var elem, + i = 0; + + for ( ; (elem = this[i]) != null; i++ ) { + if ( elem.nodeType === 1 ) { + + // Prevent memory leaks + jQuery.cleanData( getAll( elem, false ) ); + + // Remove any remaining nodes + elem.textContent = ""; + } + } + + return this; + }, + + clone: function( dataAndEvents, deepDataAndEvents ) { + dataAndEvents = dataAndEvents == null ? false : dataAndEvents; + deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents; + + return this.map( function () { + return jQuery.clone( this, dataAndEvents, deepDataAndEvents ); + }); + }, + + html: function( value ) { + return jQuery.access( this, function( value ) { + var elem = this[ 0 ] || {}, + i = 0, + l = this.length; + + if ( value === undefined && elem.nodeType === 1 ) { + return elem.innerHTML; + } + + // See if we can take a shortcut and just use innerHTML + if ( typeof value === "string" && !rnoInnerhtml.test( value ) && + !wrapMap[ ( rtagName.exec( value ) || [ "", "" ] )[ 1 ].toLowerCase() ] ) { + + value = value.replace( rxhtmlTag, "<$1>" ); + + try { + for ( ; i < l; i++ ) { + elem = this[ i ] || {}; + + // Remove element nodes and prevent memory leaks + if ( elem.nodeType === 1 ) { + jQuery.cleanData( getAll( elem, false ) ); + elem.innerHTML = value; + } + } + + elem = 0; + + // If using innerHTML throws an exception, use the fallback method + } catch( e ) {} + } + + if ( elem ) { + this.empty().append( value ); + } + }, null, value, arguments.length ); + }, + + replaceWith: function() { + var + // Snapshot the DOM in case .domManip sweeps something relevant into its fragment + args = jQuery.map( this, function( elem ) { + return [ elem.nextSibling, elem.parentNode ]; + }), + i = 0; + + // Make the changes, replacing each context element with the new content + this.domManip( arguments, function( elem ) { + var next = args[ i++ ], + parent = args[ i++ ]; + + if ( parent ) { + // Don't use the snapshot next if it has moved (#13810) + if ( next && next.parentNode !== parent ) { + next = this.nextSibling; + } + jQuery( this ).remove(); + parent.insertBefore( elem, next ); + } + // Allow new content to include elements from the context set + }, true ); + + // Force removal if there was no new content (e.g., from empty arguments) + return i ? this : this.remove(); + }, + + detach: function( selector ) { + return this.remove( selector, true ); + }, + + domManip: function( args, callback, allowIntersection ) { + + // Flatten any nested arrays + args = core_concat.apply( [], args ); + + var fragment, first, scripts, hasScripts, node, doc, + i = 0, + l = this.length, + set = this, + iNoClone = l - 1, + value = args[ 0 ], + isFunction = jQuery.isFunction( value ); + + // We can't cloneNode fragments that contain checked, in WebKit + if ( isFunction || !( l <= 1 || typeof value !== "string" || jQuery.support.checkClone || !rchecked.test( value ) ) ) { + return this.each(function( index ) { + var self = set.eq( index ); + if ( isFunction ) { + args[ 0 ] = value.call( this, index, self.html() ); + } + self.domManip( args, callback, allowIntersection ); + }); + } + + if ( l ) { + fragment = jQuery.buildFragment( args, this[ 0 ].ownerDocument, false, !allowIntersection && this ); + first = fragment.firstChild; + + if ( fragment.childNodes.length === 1 ) { + fragment = first; + } + + if ( first ) { + scripts = jQuery.map( getAll( fragment, "script" ), disableScript ); + hasScripts = scripts.length; + + // Use the original fragment for the last item instead of the first because it can end up + // being emptied incorrectly in certain situations (#8070). + for ( ; i < l; i++ ) { + node = fragment; + + if ( i !== iNoClone ) { + node = jQuery.clone( node, true, true ); + + // Keep references to cloned scripts for later restoration + if ( hasScripts ) { + // Support: QtWebKit + // jQuery.merge because core_push.apply(_, arraylike) throws + jQuery.merge( scripts, getAll( node, "script" ) ); + } + } + + callback.call( this[ i ], node, i ); + } + + if ( hasScripts ) { + doc = scripts[ scripts.length - 1 ].ownerDocument; + + // Reenable scripts + jQuery.map( scripts, restoreScript ); + + // Evaluate executable scripts on first document insertion + for ( i = 0; i < hasScripts; i++ ) { + node = scripts[ i ]; + if ( rscriptType.test( node.type || "" ) && + !data_priv.access( node, "globalEval" ) && jQuery.contains( doc, node ) ) { + + if ( node.src ) { + // Hope ajax is available... + jQuery._evalUrl( node.src ); + } else { + jQuery.globalEval( node.textContent.replace( rcleanScript, "" ) ); + } + } + } + } + } + } + + return this; + } +}); + +jQuery.each({ + appendTo: "append", + prependTo: "prepend", + insertBefore: "before", + insertAfter: "after", + replaceAll: "replaceWith" +}, function( name, original ) { + jQuery.fn[ name ] = function( selector ) { + var elems, + ret = [], + insert = jQuery( selector ), + last = insert.length - 1, + i = 0; + + for ( ; i <= last; i++ ) { + elems = i === last ? this : this.clone( true ); + jQuery( insert[ i ] )[ original ]( elems ); + + // Support: QtWebKit + // .get() because core_push.apply(_, arraylike) throws + core_push.apply( ret, elems.get() ); + } + + return this.pushStack( ret ); + }; +}); + +jQuery.extend({ + clone: function( elem, dataAndEvents, deepDataAndEvents ) { + var i, l, srcElements, destElements, + clone = elem.cloneNode( true ), + inPage = jQuery.contains( elem.ownerDocument, elem ); + + // Support: IE >= 9 + // Fix Cloning issues + if ( !jQuery.support.noCloneChecked && ( elem.nodeType === 1 || elem.nodeType === 11 ) && !jQuery.isXMLDoc( elem ) ) { + + // We eschew Sizzle here for performance reasons: http://jsperf.com/getall-vs-sizzle/2 + destElements = getAll( clone ); + srcElements = getAll( elem ); + + for ( i = 0, l = srcElements.length; i < l; i++ ) { + fixInput( srcElements[ i ], destElements[ i ] ); + } + } + + // Copy the events from the original to the clone + if ( dataAndEvents ) { + if ( deepDataAndEvents ) { + srcElements = srcElements || getAll( elem ); + destElements = destElements || getAll( clone ); + + for ( i = 0, l = srcElements.length; i < l; i++ ) { + cloneCopyEvent( srcElements[ i ], destElements[ i ] ); + } + } else { + cloneCopyEvent( elem, clone ); + } + } + + // Preserve script evaluation history + destElements = getAll( clone, "script" ); + if ( destElements.length > 0 ) { + setGlobalEval( destElements, !inPage && getAll( elem, "script" ) ); + } + + // Return the cloned set + return clone; + }, + + buildFragment: function( elems, context, scripts, selection ) { + var elem, tmp, tag, wrap, contains, j, + i = 0, + l = elems.length, + fragment = context.createDocumentFragment(), + nodes = []; + + for ( ; i < l; i++ ) { + elem = elems[ i ]; + + if ( elem || elem === 0 ) { + + // Add nodes directly + if ( jQuery.type( elem ) === "object" ) { + // Support: QtWebKit + // jQuery.merge because core_push.apply(_, arraylike) throws + jQuery.merge( nodes, elem.nodeType ? [ elem ] : elem ); + + // Convert non-html into a text node + } else if ( !rhtml.test( elem ) ) { + nodes.push( context.createTextNode( elem ) ); + + // Convert html into DOM nodes + } else { + tmp = tmp || fragment.appendChild( context.createElement("div") ); + + // Deserialize a standard representation + tag = ( rtagName.exec( elem ) || ["", ""] )[ 1 ].toLowerCase(); + wrap = wrapMap[ tag ] || wrapMap._default; + tmp.innerHTML = wrap[ 1 ] + elem.replace( rxhtmlTag, "<$1>" ) + wrap[ 2 ]; + + // Descend through wrappers to the right content + j = wrap[ 0 ]; + while ( j-- ) { + tmp = tmp.lastChild; + } + + // Support: QtWebKit + // jQuery.merge because core_push.apply(_, arraylike) throws + jQuery.merge( nodes, tmp.childNodes ); + + // Remember the top-level container + tmp = fragment.firstChild; + + // Fixes #12346 + // Support: Webkit, IE + tmp.textContent = ""; + } + } + } + + // Remove wrapper from fragment + fragment.textContent = ""; + + i = 0; + while ( (elem = nodes[ i++ ]) ) { + + // #4087 - If origin and destination elements are the same, and this is + // that element, do not do anything + if ( selection && jQuery.inArray( elem, selection ) !== -1 ) { + continue; + } + + contains = jQuery.contains( elem.ownerDocument, elem ); + + // Append to fragment + tmp = getAll( fragment.appendChild( elem ), "script" ); + + // Preserve script evaluation history + if ( contains ) { + setGlobalEval( tmp ); + } + + // Capture executables + if ( scripts ) { + j = 0; + while ( (elem = tmp[ j++ ]) ) { + if ( rscriptType.test( elem.type || "" ) ) { + scripts.push( elem ); + } + } + } + } + + return fragment; + }, + + cleanData: function( elems ) { + var data, elem, events, type, key, j, + special = jQuery.event.special, + i = 0; + + for ( ; (elem = elems[ i ]) !== undefined; i++ ) { + if ( Data.accepts( elem ) ) { + key = elem[ data_priv.expando ]; + + if ( key && (data = data_priv.cache[ key ]) ) { + events = Object.keys( data.events || {} ); + if ( events.length ) { + for ( j = 0; (type = events[j]) !== undefined; j++ ) { + if ( special[ type ] ) { + jQuery.event.remove( elem, type ); + + // This is a shortcut to avoid jQuery.event.remove's overhead + } else { + jQuery.removeEvent( elem, type, data.handle ); + } + } + } + if ( data_priv.cache[ key ] ) { + // Discard any remaining `private` data + delete data_priv.cache[ key ]; + } + } + } + // Discard any remaining `user` data + delete data_user.cache[ elem[ data_user.expando ] ]; + } + }, + + _evalUrl: function( url ) { + return jQuery.ajax({ + url: url, + type: "GET", + dataType: "script", + async: false, + global: false, + "throws": true + }); + } +}); + +// Support: 1.x compatibility +// Manipulating tables requires a tbody +function manipulationTarget( elem, content ) { + return jQuery.nodeName( elem, "table" ) && + jQuery.nodeName( content.nodeType === 1 ? content : content.firstChild, "tr" ) ? + + elem.getElementsByTagName("tbody")[0] || + elem.appendChild( elem.ownerDocument.createElement("tbody") ) : + elem; +} + +// Replace/restore the type attribute of script elements for safe DOM manipulation +function disableScript( elem ) { + elem.type = (elem.getAttribute("type") !== null) + "/" + elem.type; + return elem; +} +function restoreScript( elem ) { + var match = rscriptTypeMasked.exec( elem.type ); + + if ( match ) { + elem.type = match[ 1 ]; + } else { + elem.removeAttribute("type"); + } + + return elem; +} + +// Mark scripts as having already been evaluated +function setGlobalEval( elems, refElements ) { + var l = elems.length, + i = 0; + + for ( ; i < l; i++ ) { + data_priv.set( + elems[ i ], "globalEval", !refElements || data_priv.get( refElements[ i ], "globalEval" ) + ); + } +} + +function cloneCopyEvent( src, dest ) { + var i, l, type, pdataOld, pdataCur, udataOld, udataCur, events; + + if ( dest.nodeType !== 1 ) { + return; + } + + // 1. Copy private data: events, handlers, etc. + if ( data_priv.hasData( src ) ) { + pdataOld = data_priv.access( src ); + pdataCur = data_priv.set( dest, pdataOld ); + events = pdataOld.events; + + if ( events ) { + delete pdataCur.handle; + pdataCur.events = {}; + + for ( type in events ) { + for ( i = 0, l = events[ type ].length; i < l; i++ ) { + jQuery.event.add( dest, type, events[ type ][ i ] ); + } + } + } + } + + // 2. Copy user data + if ( data_user.hasData( src ) ) { + udataOld = data_user.access( src ); + udataCur = jQuery.extend( {}, udataOld ); + + data_user.set( dest, udataCur ); + } +} + + +function getAll( context, tag ) { + var ret = context.getElementsByTagName ? context.getElementsByTagName( tag || "*" ) : + context.querySelectorAll ? context.querySelectorAll( tag || "*" ) : + []; + + return tag === undefined || tag && jQuery.nodeName( context, tag ) ? + jQuery.merge( [ context ], ret ) : + ret; +} + +// Support: IE >= 9 +function fixInput( src, dest ) { + var nodeName = dest.nodeName.toLowerCase(); + + // Fails to persist the checked state of a cloned checkbox or radio button. + if ( nodeName === "input" && manipulation_rcheckableType.test( src.type ) ) { + dest.checked = src.checked; + + // Fails to return the selected option to the default selected state when cloning options + } else if ( nodeName === "input" || nodeName === "textarea" ) { + dest.defaultValue = src.defaultValue; + } +} +jQuery.fn.extend({ + wrapAll: function( html ) { + var wrap; + + if ( jQuery.isFunction( html ) ) { + return this.each(function( i ) { + jQuery( this ).wrapAll( html.call(this, i) ); + }); + } + + if ( this[ 0 ] ) { + + // The elements to wrap the target around + wrap = jQuery( html, this[ 0 ].ownerDocument ).eq( 0 ).clone( true ); + + if ( this[ 0 ].parentNode ) { + wrap.insertBefore( this[ 0 ] ); + } + + wrap.map(function() { + var elem = this; + + while ( elem.firstElementChild ) { + elem = elem.firstElementChild; + } + + return elem; + }).append( this ); + } + + return this; + }, + + wrapInner: function( html ) { + if ( jQuery.isFunction( html ) ) { + return this.each(function( i ) { + jQuery( this ).wrapInner( html.call(this, i) ); + }); + } + + return this.each(function() { + var self = jQuery( this ), + contents = self.contents(); + + if ( contents.length ) { + contents.wrapAll( html ); + + } else { + self.append( html ); + } + }); + }, + + wrap: function( html ) { + var isFunction = jQuery.isFunction( html ); + + return this.each(function( i ) { + jQuery( this ).wrapAll( isFunction ? html.call(this, i) : html ); + }); + }, + + unwrap: function() { + return this.parent().each(function() { + if ( !jQuery.nodeName( this, "body" ) ) { + jQuery( this ).replaceWith( this.childNodes ); + } + }).end(); + } +}); +var curCSS, iframe, + // swappable if display is none or starts with table except "table", "table-cell", or "table-caption" + // see here for display values: https://developer.mozilla.org/en-US/docs/CSS/display + rdisplayswap = /^(none|table(?!-c[ea]).+)/, + rmargin = /^margin/, + rnumsplit = new RegExp( "^(" + core_pnum + ")(.*)$", "i" ), + rnumnonpx = new RegExp( "^(" + core_pnum + ")(?!px)[a-z%]+$", "i" ), + rrelNum = new RegExp( "^([+-])=(" + core_pnum + ")", "i" ), + elemdisplay = { BODY: "block" }, + + cssShow = { position: "absolute", visibility: "hidden", display: "block" }, + cssNormalTransform = { + letterSpacing: 0, + fontWeight: 400 + }, + + cssExpand = [ "Top", "Right", "Bottom", "Left" ], + cssPrefixes = [ "Webkit", "O", "Moz", "ms" ]; + +// return a css property mapped to a potentially vendor prefixed property +function vendorPropName( style, name ) { + + // shortcut for names that are not vendor prefixed + if ( name in style ) { + return name; + } + + // check for vendor prefixed names + var capName = name.charAt(0).toUpperCase() + name.slice(1), + origName = name, + i = cssPrefixes.length; + + while ( i-- ) { + name = cssPrefixes[ i ] + capName; + if ( name in style ) { + return name; + } + } + + return origName; +} + +function isHidden( elem, el ) { + // isHidden might be called from jQuery#filter function; + // in that case, element will be second argument + elem = el || elem; + return jQuery.css( elem, "display" ) === "none" || !jQuery.contains( elem.ownerDocument, elem ); +} + +// NOTE: we've included the "window" in window.getComputedStyle +// because jsdom on node.js will break without it. +function getStyles( elem ) { + return window.getComputedStyle( elem, null ); +} + +function showHide( elements, show ) { + var display, elem, hidden, + values = [], + index = 0, + length = elements.length; + + for ( ; index < length; index++ ) { + elem = elements[ index ]; + if ( !elem.style ) { + continue; + } + + values[ index ] = data_priv.get( elem, "olddisplay" ); + display = elem.style.display; + if ( show ) { + // Reset the inline display of this element to learn if it is + // being hidden by cascaded rules or not + if ( !values[ index ] && display === "none" ) { + elem.style.display = ""; + } + + // Set elements which have been overridden with display: none + // in a stylesheet to whatever the default browser style is + // for such an element + if ( elem.style.display === "" && isHidden( elem ) ) { + values[ index ] = data_priv.access( elem, "olddisplay", css_defaultDisplay(elem.nodeName) ); + } + } else { + + if ( !values[ index ] ) { + hidden = isHidden( elem ); + + if ( display && display !== "none" || !hidden ) { + data_priv.set( elem, "olddisplay", hidden ? display : jQuery.css(elem, "display") ); + } + } + } + } + + // Set the display of most of the elements in a second loop + // to avoid the constant reflow + for ( index = 0; index < length; index++ ) { + elem = elements[ index ]; + if ( !elem.style ) { + continue; + } + if ( !show || elem.style.display === "none" || elem.style.display === "" ) { + elem.style.display = show ? values[ index ] || "" : "none"; + } + } + + return elements; +} + +jQuery.fn.extend({ + css: function( name, value ) { + return jQuery.access( this, function( elem, name, value ) { + var styles, len, + map = {}, + i = 0; + + if ( jQuery.isArray( name ) ) { + styles = getStyles( elem ); + len = name.length; + + for ( ; i < len; i++ ) { + map[ name[ i ] ] = jQuery.css( elem, name[ i ], false, styles ); + } + + return map; + } + + return value !== undefined ? + jQuery.style( elem, name, value ) : + jQuery.css( elem, name ); + }, name, value, arguments.length > 1 ); + }, + show: function() { + return showHide( this, true ); + }, + hide: function() { + return showHide( this ); + }, + toggle: function( state ) { + if ( typeof state === "boolean" ) { + return state ? this.show() : this.hide(); + } + + return this.each(function() { + if ( isHidden( this ) ) { + jQuery( this ).show(); + } else { + jQuery( this ).hide(); + } + }); + } +}); + +jQuery.extend({ + // Add in style property hooks for overriding the default + // behavior of getting and setting a style property + cssHooks: { + opacity: { + get: function( elem, computed ) { + if ( computed ) { + // We should always get a number back from opacity + var ret = curCSS( elem, "opacity" ); + return ret === "" ? "1" : ret; + } + } + } + }, + + // Don't automatically add "px" to these possibly-unitless properties + cssNumber: { + "columnCount": true, + "fillOpacity": true, + "fontWeight": true, + "lineHeight": true, + "opacity": true, + "order": true, + "orphans": true, + "widows": true, + "zIndex": true, + "zoom": true + }, + + // Add in properties whose names you wish to fix before + // setting or getting the value + cssProps: { + // normalize float css property + "float": "cssFloat" + }, + + // Get and set the style property on a DOM Node + style: function( elem, name, value, extra ) { + // Don't set styles on text and comment nodes + if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) { + return; + } + + // Make sure that we're working with the right name + var ret, type, hooks, + origName = jQuery.camelCase( name ), + style = elem.style; + + name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( style, origName ) ); + + // gets hook for the prefixed version + // followed by the unprefixed version + hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; + + // Check if we're setting a value + if ( value !== undefined ) { + type = typeof value; + + // convert relative number strings (+= or -=) to relative numbers. #7345 + if ( type === "string" && (ret = rrelNum.exec( value )) ) { + value = ( ret[1] + 1 ) * ret[2] + parseFloat( jQuery.css( elem, name ) ); + // Fixes bug #9237 + type = "number"; + } + + // Make sure that NaN and null values aren't set. See: #7116 + if ( value == null || type === "number" && isNaN( value ) ) { + return; + } + + // If a number was passed in, add 'px' to the (except for certain CSS properties) + if ( type === "number" && !jQuery.cssNumber[ origName ] ) { + value += "px"; + } + + // Fixes #8908, it can be done more correctly by specifying setters in cssHooks, + // but it would mean to define eight (for every problematic property) identical functions + if ( !jQuery.support.clearCloneStyle && value === "" && name.indexOf("background") === 0 ) { + style[ name ] = "inherit"; + } + + // If a hook was provided, use that value, otherwise just set the specified value + if ( !hooks || !("set" in hooks) || (value = hooks.set( elem, value, extra )) !== undefined ) { + style[ name ] = value; + } + + } else { + // If a hook was provided get the non-computed value from there + if ( hooks && "get" in hooks && (ret = hooks.get( elem, false, extra )) !== undefined ) { + return ret; + } + + // Otherwise just get the value from the style object + return style[ name ]; + } + }, + + css: function( elem, name, extra, styles ) { + var val, num, hooks, + origName = jQuery.camelCase( name ); + + // Make sure that we're working with the right name + name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( elem.style, origName ) ); + + // gets hook for the prefixed version + // followed by the unprefixed version + hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; + + // If a hook was provided get the computed value from there + if ( hooks && "get" in hooks ) { + val = hooks.get( elem, true, extra ); + } + + // Otherwise, if a way to get the computed value exists, use that + if ( val === undefined ) { + val = curCSS( elem, name, styles ); + } + + //convert "normal" to computed value + if ( val === "normal" && name in cssNormalTransform ) { + val = cssNormalTransform[ name ]; + } + + // Return, converting to number if forced or a qualifier was provided and val looks numeric + if ( extra === "" || extra ) { + num = parseFloat( val ); + return extra === true || jQuery.isNumeric( num ) ? num || 0 : val; + } + return val; + } +}); + +curCSS = function( elem, name, _computed ) { + var width, minWidth, maxWidth, + computed = _computed || getStyles( elem ), + + // Support: IE9 + // getPropertyValue is only needed for .css('filter') in IE9, see #12537 + ret = computed ? computed.getPropertyValue( name ) || computed[ name ] : undefined, + style = elem.style; + + if ( computed ) { + + if ( ret === "" && !jQuery.contains( elem.ownerDocument, elem ) ) { + ret = jQuery.style( elem, name ); + } + + // Support: Safari 5.1 + // A tribute to the "awesome hack by Dean Edwards" + // Safari 5.1.7 (at least) returns percentage for a larger set of values, but width seems to be reliably pixels + // this is against the CSSOM draft spec: http://dev.w3.org/csswg/cssom/#resolved-values + if ( rnumnonpx.test( ret ) && rmargin.test( name ) ) { + + // Remember the original values + width = style.width; + minWidth = style.minWidth; + maxWidth = style.maxWidth; + + // Put in the new values to get a computed value out + style.minWidth = style.maxWidth = style.width = ret; + ret = computed.width; + + // Revert the changed values + style.width = width; + style.minWidth = minWidth; + style.maxWidth = maxWidth; + } + } + + return ret; +}; + + +function setPositiveNumber( elem, value, subtract ) { + var matches = rnumsplit.exec( value ); + return matches ? + // Guard against undefined "subtract", e.g., when used as in cssHooks + Math.max( 0, matches[ 1 ] - ( subtract || 0 ) ) + ( matches[ 2 ] || "px" ) : + value; +} + +function augmentWidthOrHeight( elem, name, extra, isBorderBox, styles ) { + var i = extra === ( isBorderBox ? "border" : "content" ) ? + // If we already have the right measurement, avoid augmentation + 4 : + // Otherwise initialize for horizontal or vertical properties + name === "width" ? 1 : 0, + + val = 0; + + for ( ; i < 4; i += 2 ) { + // both box models exclude margin, so add it if we want it + if ( extra === "margin" ) { + val += jQuery.css( elem, extra + cssExpand[ i ], true, styles ); + } + + if ( isBorderBox ) { + // border-box includes padding, so remove it if we want content + if ( extra === "content" ) { + val -= jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); + } + + // at this point, extra isn't border nor margin, so remove border + if ( extra !== "margin" ) { + val -= jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); + } + } else { + // at this point, extra isn't content, so add padding + val += jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); + + // at this point, extra isn't content nor padding, so add border + if ( extra !== "padding" ) { + val += jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); + } + } + } + + return val; +} + +function getWidthOrHeight( elem, name, extra ) { + + // Start with offset property, which is equivalent to the border-box value + var valueIsBorderBox = true, + val = name === "width" ? elem.offsetWidth : elem.offsetHeight, + styles = getStyles( elem ), + isBorderBox = jQuery.support.boxSizing && jQuery.css( elem, "boxSizing", false, styles ) === "border-box"; + + // some non-html elements return undefined for offsetWidth, so check for null/undefined + // svg - https://bugzilla.mozilla.org/show_bug.cgi?id=649285 + // MathML - https://bugzilla.mozilla.org/show_bug.cgi?id=491668 + if ( val <= 0 || val == null ) { + // Fall back to computed then uncomputed css if necessary + val = curCSS( elem, name, styles ); + if ( val < 0 || val == null ) { + val = elem.style[ name ]; + } + + // Computed unit is not pixels. Stop here and return. + if ( rnumnonpx.test(val) ) { + return val; + } + + // we need the check for style in case a browser which returns unreliable values + // for getComputedStyle silently falls back to the reliable elem.style + valueIsBorderBox = isBorderBox && ( jQuery.support.boxSizingReliable || val === elem.style[ name ] ); + + // Normalize "", auto, and prepare for extra + val = parseFloat( val ) || 0; + } + + // use the active box-sizing model to add/subtract irrelevant styles + return ( val + + augmentWidthOrHeight( + elem, + name, + extra || ( isBorderBox ? "border" : "content" ), + valueIsBorderBox, + styles + ) + ) + "px"; +} + +// Try to determine the default display value of an element +function css_defaultDisplay( nodeName ) { + var doc = document, + display = elemdisplay[ nodeName ]; + + if ( !display ) { + display = actualDisplay( nodeName, doc ); + + // If the simple way fails, read from inside an iframe + if ( display === "none" || !display ) { + // Use the already-created iframe if possible + iframe = ( iframe || + jQuery("