UNPKG

665 kBJavaScriptView Raw
1/**
2 * Modules in this bundle
3 * @license
4 *
5 * espower:
6 * license: MIT (http://opensource.org/licenses/MIT)
7 * author: Takuto Wada <takuto.wada@gmail.com>
8 * contributors: James Talmage
9 * homepage: https://github.com/power-assert-js/espower
10 * version: 1.3.0
11 *
12 * amdefine:
13 * license: BSD-3-Clause AND MIT
14 * author: James Burke <jrburke@gmail.com>
15 * maintainers: jrburke <jrburke@gmail.com>
16 * homepage: http://github.com/jrburke/amdefine
17 * version: 1.0.0
18 *
19 * array-filter:
20 * license: MIT (http://opensource.org/licenses/MIT)
21 * author: Julian Gruber <mail@juliangruber.com>
22 * maintainers: juliangruber <julian@juliangruber.com>
23 * homepage: https://github.com/juliangruber/array-filter
24 * version: 1.0.0
25 *
26 * array-find:
27 * license: MIT (http://opensource.org/licenses/MIT)
28 * author: Stefan Duberg <stefanduberg@gmail.com>
29 * maintainers: dubban <stefanduberg@me.com>
30 * homepage: https://github.com/stefanduberg/array-find
31 * version: 1.0.0
32 *
33 * array-foreach:
34 * license: MIT (http://opensource.org/licenses/MIT)
35 * author: Takuto Wada <takuto.wada@gmail.com>
36 * maintainers: twada <takuto.wada@gmail.com>
37 * homepage: https://github.com/twada/array-foreach
38 * version: 1.0.2
39 *
40 * array-map:
41 * license: MIT (http://opensource.org/licenses/MIT)
42 * author: James Halliday <mail@substack.net>
43 * maintainers: substack <mail@substack.net>
44 * homepage: https://github.com/substack/array-map
45 * version: 0.0.0
46 *
47 * array-reduce:
48 * license: MIT (http://opensource.org/licenses/MIT)
49 * author: James Halliday <mail@substack.net>
50 * maintainers: substack <mail@substack.net>
51 * homepage: https://github.com/substack/array-reduce
52 * version: 0.0.0
53 *
54 * core-js:
55 * license: MIT (http://opensource.org/licenses/MIT)
56 * maintainers: zloirock <zloirock@zloirock.ru>
57 * homepage: https://github.com/zloirock/core-js#readme
58 * version: 2.4.0
59 *
60 * deep-equal:
61 * license: MIT (http://opensource.org/licenses/MIT)
62 * author: James Halliday <mail@substack.net>
63 * maintainers: substack <mail@substack.net>
64 * homepage: https://github.com/substack/node-deep-equal#readme
65 * version: 1.0.1
66 *
67 * escallmatch:
68 * license: MIT (http://opensource.org/licenses/MIT)
69 * author: Takuto Wada <takuto.wada@gmail.com>
70 * maintainers: twada <takuto.wada@gmail.com>
71 * homepage: https://github.com/twada/escallmatch
72 * version: 1.4.2
73 *
74 * escodegen:
75 * license: BSD-2-Clause (http://opensource.org/licenses/BSD-2-Clause)
76 * maintainers: constellation <utatane.tea@gmail.com>, michaelficarra <npm@michael.ficarra.me>
77 * homepage: http://github.com/estools/escodegen
78 * version: 1.8.0
79 *
80 * espower-location-detector:
81 * license: MIT (http://opensource.org/licenses/MIT)
82 * author: Takuto Wada <takuto.wada@gmail.com>
83 * maintainers: twada <takuto.wada@gmail.com>
84 * homepage: https://github.com/twada/espower-location-detector
85 * version: 0.1.2
86 *
87 * esprima:
88 * license: BSD-2-Clause (http://opensource.org/licenses/BSD-2-Clause)
89 * author: Ariya Hidayat <ariya.hidayat@gmail.com>
90 * maintainers: ariya <ariya.hidayat@gmail.com>
91 * homepage: http://esprima.org
92 * version: 2.7.2
93 *
94 * espurify:
95 * license: MIT (http://opensource.org/licenses/MIT)
96 * author: Takuto Wada <takuto.wada@gmail.com>
97 * maintainers: twada <takuto.wada@gmail.com>
98 * homepage: https://github.com/estools/espurify
99 * version: 1.6.0
100 *
101 * estraverse:
102 * license: BSD-2-Clause (http://opensource.org/licenses/BSD-2-Clause)
103 * maintainers: constellation <utatane.tea@gmail.com>, michaelficarra <npm@michael.ficarra.me>, nzakas <nicholas@nczconsulting.com>
104 * homepage: https://github.com/estools/estraverse
105 * version: 4.2.0
106 *
107 * esutils:
108 * licenses: BSD (http://opensource.org/licenses/BSD-2-Clause)
109 * maintainers: constellation <utatane.tea@gmail.com>, michaelficarra <npm@michael.ficarra.me>
110 * homepage: https://github.com/estools/esutils
111 * version: 2.0.2
112 *
113 * indexof:
114 * maintainers: tjholowaychuk <tj@vision-media.ca>
115 * version: 0.0.1
116 *
117 * is-url:
118 * license: MIT (http://opensource.org/licenses/MIT)
119 * maintainers: segmentio <friends@segment.io>, zeke <zeke@sikelianos.com>
120 * homepage: https://github.com/segmentio/is-url
121 * version: 1.2.1
122 *
123 * isarray:
124 * license: MIT (http://opensource.org/licenses/MIT)
125 * author: Julian Gruber <mail@juliangruber.com>
126 * maintainers: juliangruber <julian@juliangruber.com>
127 * homepage: https://github.com/juliangruber/isarray
128 * version: 1.0.0
129 *
130 * path-browserify:
131 * license: MIT (http://opensource.org/licenses/MIT)
132 * author: James Halliday <mail@substack.net>
133 * maintainers: substack <mail@substack.net>
134 * homepage: https://github.com/substack/path-browserify
135 * version: 0.0.0
136 *
137 * path-is-absolute:
138 * license: MIT (http://opensource.org/licenses/MIT)
139 * author: Sindre Sorhus <sindresorhus@gmail.com>
140 * maintainers: sindresorhus <sindresorhus@gmail.com>
141 * homepage: https://github.com/sindresorhus/path-is-absolute
142 * version: 1.0.0
143 *
144 * process:
145 * license: MIT (http://opensource.org/licenses/MIT)
146 * author: Roman Shtylman <shtylman@gmail.com>
147 * maintainers: coolaj86 <coolaj86@gmail.com>, cwmma <calvin.metcalf@gmail.com>, defunctzombie <shtylman@gmail.com>
148 * homepage: https://github.com/shtylman/node-process#readme
149 * version: 0.11.5
150 *
151 * source-map:
152 * licenses: BSD (http://opensource.org/licenses/BSD-2-Clause)
153 * author: Nick Fitzgerald <nfitzgerald@mozilla.com>
154 * maintainers: mozilla-devtools <mozilla-developer-tools@googlegroups.com>, mozilla <dherman@mozilla.com>, nickfitzgerald <fitzgen@gmail.com>
155 * contributors: Tobias Koppers <tobias.koppers@googlemail.com>, Duncan Beevers <duncan@dweebd.com>, Stephen Crane <scrane@mozilla.com>, Ryan Seddon <seddon.ryan@gmail.com>, Miles Elam <miles.elam@deem.com>, Mihai Bazon <mihai.bazon@gmail.com>, Michael Ficarra <github.public.email@michael.ficarra.me>, Todd Wolfson <todd@twolfson.com>, Alexander Solovyov <alexander@solovyov.net>, Felix Gnass <fgnass@gmail.com>, Conrad Irwin <conrad.irwin@gmail.com>, usrbincc <usrbincc@yahoo.com>, David Glasser <glasser@davidglasser.net>, Chase Douglas <chase@newrelic.com>, Evan Wallace <evan.exe@gmail.com>, Heather Arthur <fayearthur@gmail.com>, Hugh Kennedy <hughskennedy@gmail.com>, David Glasser <glasser@davidglasser.net>, Simon Lydell <simon.lydell@gmail.com>, Jmeas Smith <jellyes2@gmail.com>, Michael Z Goddard <mzgoddard@gmail.com>, azu <azu@users.noreply.github.com>, John Gozde <john@gozde.ca>, Adam Kirkton <akirkton@truefitinnovation.com>, Chris Montgomery <christopher.montgomery@dowjones.com>, J. Ryan Stinnett <jryans@gmail.com>, Jack Herrington <jherrington@walmartlabs.com>, Chris Truter <jeffpalentine@gmail.com>, Daniel Espeset <daniel@danielespeset.com>, Jamie Wong <jamie.lf.wong@gmail.com>
156 * homepage: https://github.com/mozilla/source-map
157 * version: 0.2.0
158 *
159 * type-name:
160 * license: MIT (http://opensource.org/licenses/MIT)
161 * author: Takuto Wada <takuto.wada@gmail.com>
162 * maintainers: twada <takuto.wada@gmail.com>
163 * contributors: azu, Yosuke Furukawa
164 * homepage: https://github.com/twada/type-name
165 * version: 2.0.1
166 *
167 * xtend:
168 * license: MIT (http://opensource.org/licenses/MIT)
169 * author: Raynos <raynos2@gmail.com>
170 * maintainers: raynos <raynos2@gmail.com>
171 * contributors: Jake Verbaten, Matt Esch
172 * homepage: https://github.com/Raynos/xtend
173 * version: 4.0.1
174 *
175 * This header is generated by licensify (https://github.com/twada/licensify)
176 */
177(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.espower = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw (f.code="MODULE_NOT_FOUND", f)}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){
178/**
179 * espower - Power Assert feature instrumentor based on the ECMAScript AST.
180 *
181 * https://github.com/power-assert-js/espower
182 *
183 * Copyright (c) 2013-2016 Takuto Wada
184 * Licensed under the MIT license.
185 * https://github.com/power-assert-js/espower/blob/master/MIT-LICENSE.txt
186 */
187'use strict';
188
189var defaultOptions = _dereq_('./lib/default-options');
190var Instrumentor = _dereq_('./lib/instrumentor');
191var extend = _dereq_('xtend');
192
193/**
194 * Instrument power assert feature into code. ECMAScript AST in, ECMAScript AST out.
195 * @param {object} originalAst JavaScript ECMAScript JS AST to instrument (directly modified if destructive option is truthy)
196 * @param {object} options Instrumentation options.
197 * @returns {object} instrumented AST
198 * @throws {EspowerError} if `originalAst` is already instrumented
199 * @throws {EspowerError} if `originalAst` does not contain location information
200 * @throws {EspowerError} if `options` is not valid
201 */
202function espower (originalAst, options) {
203 var instrumentor = new Instrumentor(extend(defaultOptions(), options));
204 return instrumentor.instrument(originalAst);
205}
206
207espower.defaultOptions = defaultOptions;
208espower.Instrumentor = Instrumentor;
209espower.AssertionVisitor = _dereq_('./lib/assertion-visitor');
210espower.EspowerError = _dereq_('./lib/espower-error');
211module.exports = espower;
212
213},{"./lib/assertion-visitor":2,"./lib/default-options":4,"./lib/espower-error":5,"./lib/instrumentor":6,"xtend":115}],2:[function(_dereq_,module,exports){
214'use strict';
215
216var estraverse = _dereq_('estraverse');
217var escodegen = _dereq_('escodegen');
218var espurify = _dereq_('espurify');
219var espurifyWithRaw = espurify.customize({extra: 'raw'});
220var isArray = _dereq_('isarray');
221var deepEqual = _dereq_('deep-equal');
222var syntax = estraverse.Syntax;
223var EspowerLocationDetector = _dereq_('espower-location-detector');
224var EspowerError = _dereq_('./espower-error');
225var toBeSkipped = _dereq_('./rules/to-be-skipped');
226var toBeCaptured = _dereq_('./rules/to-be-captured');
227var canonicalCodeOptions = {
228 format: {
229 indent: {
230 style: ''
231 },
232 newline: ''
233 },
234 verbatim: 'x-verbatim-espower'
235};
236
237function AssertionVisitor (matcher, options) {
238 this.matcher = matcher;
239 this.options = options || {};
240 this.locationDetector = new EspowerLocationDetector(this.options);
241 this.currentArgumentPath = null;
242 this.argumentModified = false;
243}
244
245AssertionVisitor.prototype.enter = function (controller) {
246 this.assertionPath = [].concat(controller.path());
247 var currentNode = controller.current();
248 this.canonicalCode = this.generateCanonicalCode(currentNode);
249 this.powerAssertCalleeObject = this.guessPowerAssertCalleeObjectFor(currentNode.callee);
250 this.location = this.locationDetector.locationFor(currentNode);
251 var enclosingFunc = findEnclosingFunction(controller.parents());
252 this.withinGenerator = enclosingFunc && enclosingFunc.generator;
253 this.withinAsync = enclosingFunc && enclosingFunc.async;
254};
255
256AssertionVisitor.prototype.enterArgument = function (controller) {
257 var currentNode = controller.current();
258 var parentNode = getParentNode(controller);
259 var argMatchResult = this.matcher.matchArgument(currentNode, parentNode);
260 if (!argMatchResult) {
261 return undefined;
262 }
263 if (argMatchResult.name === 'message' && argMatchResult.kind === 'optional') {
264 // skip optional message argument
265 return undefined;
266 }
267 this.verifyNotInstrumented(currentNode);
268 // entering target argument
269 this.currentArgumentPath = [].concat(controller.path());
270 return undefined;
271};
272
273AssertionVisitor.prototype.leave = function (controller) {
274 // nothing to do now
275};
276
277AssertionVisitor.prototype.leaveArgument = function (resultTree) {
278 try {
279 return this.argumentModified ? this.captureArgument(resultTree) : resultTree;
280 } finally {
281 this.currentArgumentPath = null;
282 this.argumentModified = false;
283 }
284};
285
286AssertionVisitor.prototype.captureNode = function (controller) {
287 this.argumentModified = true;
288 var currentNode = controller.current();
289 var path = controller.path();
290 var n = newNodeWithLocationCopyOf(currentNode);
291 var relativeEsPath = path.slice(this.assertionPath.length);
292 var newCalleeObject = updateLocRecursively(espurify(this.powerAssertCalleeObject), n, this.options.visitorKeys);
293 return n({
294 type: syntax.CallExpression,
295 callee: n({
296 type: syntax.MemberExpression,
297 computed: false,
298 object: newCalleeObject,
299 property: n({
300 type: syntax.Identifier,
301 name: '_capt'
302 })
303 }),
304 arguments: [
305 currentNode,
306 n({
307 type: syntax.Literal,
308 value: relativeEsPath.join('/')
309 })
310 ]
311 });
312};
313
314AssertionVisitor.prototype.toBeSkipped = function (controller) {
315 var currentNode = controller.current();
316 var parentNode = getParentNode(controller);
317 var currentKey = getCurrentKey(controller);
318 return toBeSkipped(currentNode, parentNode, currentKey);
319};
320
321AssertionVisitor.prototype.toBeCaptured = function (controller) {
322 var currentNode = controller.current();
323 var parentNode = getParentNode(controller);
324 var currentKey = getCurrentKey(controller);
325 return toBeCaptured(currentNode, parentNode, currentKey);
326};
327
328AssertionVisitor.prototype.isCapturingArgument = function () {
329 return !!this.currentArgumentPath;
330};
331
332AssertionVisitor.prototype.isLeavingAssertion = function (controller) {
333 return isPathIdentical(this.assertionPath, controller.path());
334};
335
336AssertionVisitor.prototype.isLeavingArgument = function (controller) {
337 return isPathIdentical(this.currentArgumentPath, controller.path());
338};
339
340// internal
341
342AssertionVisitor.prototype.generateCanonicalCode = function (node) {
343 var visitorKeys = this.options.visitorKeys;
344 var ast = espurifyWithRaw(node);
345 var visitor = {
346 leave: function (currentNode, parentNode) {
347 if (currentNode.type === syntax.Literal && typeof currentNode.raw !== 'undefined') {
348 currentNode['x-verbatim-espower'] = {
349 content : currentNode.raw,
350 precedence : escodegen.Precedence.Primary
351 };
352 return currentNode;
353 } else {
354 return undefined;
355 }
356 }
357 };
358 if (visitorKeys) {
359 visitor.keys = visitorKeys;
360 }
361 estraverse.replace(ast, visitor);
362 return escodegen.generate(ast, canonicalCodeOptions);
363};
364
365AssertionVisitor.prototype.captureArgument = function (node) {
366 var n = newNodeWithLocationCopyOf(node);
367 var props = [];
368 var newCalleeObject = updateLocRecursively(espurify(this.powerAssertCalleeObject), n, this.options.visitorKeys);
369 addLiteralTo(props, n, 'content', this.canonicalCode);
370 addLiteralTo(props, n, 'filepath', this.location.source);
371 addLiteralTo(props, n, 'line', this.location.line);
372 if (this.withinAsync) {
373 addLiteralTo(props, n, 'async', true);
374 }
375 if (this.withinGenerator) {
376 addLiteralTo(props, n, 'generator', true);
377 }
378 return n({
379 type: syntax.CallExpression,
380 callee: n({
381 type: syntax.MemberExpression,
382 computed: false,
383 object: newCalleeObject,
384 property: n({
385 type: syntax.Identifier,
386 name: '_expr'
387 })
388 }),
389 arguments: [node].concat(n({
390 type: syntax.ObjectExpression,
391 properties: props
392 }))
393 });
394};
395
396AssertionVisitor.prototype.verifyNotInstrumented = function (currentNode) {
397 if (currentNode.type !== syntax.CallExpression) {
398 return;
399 }
400 if (currentNode.callee.type !== syntax.MemberExpression) {
401 return;
402 }
403 var prop = currentNode.callee.property;
404 if (prop.type === syntax.Identifier && prop.name === '_expr') {
405 if (astEqual(currentNode.callee.object, this.powerAssertCalleeObject)) {
406 var errorMessage = 'Attempted to transform AST twice.';
407 if (this.options.path) {
408 errorMessage += ' path: ' + this.options.path;
409 }
410 throw new EspowerError(errorMessage, this.verifyNotInstrumented);
411 }
412 }
413};
414
415AssertionVisitor.prototype.guessPowerAssertCalleeObjectFor = function (node) {
416 switch(node.type) {
417 case syntax.Identifier:
418 return node;
419 case syntax.MemberExpression:
420 return node.object; // Returns browser.assert when browser.assert.element(selector)
421 }
422 return null;
423};
424
425function addLiteralTo (props, createNode, name, value) {
426 if (typeof value !== 'undefined') {
427 addToProps(props, createNode, name, createNode({
428 type: syntax.Literal,
429 value: value
430 }));
431 }
432}
433
434function addToProps (props, createNode, name, value) {
435 props.push(createNode({
436 type: syntax.Property,
437 key: createNode({
438 type: syntax.Identifier,
439 name: name
440 }),
441 value: value,
442 method: false,
443 shorthand: false,
444 computed: false,
445 kind: 'init'
446 }));
447}
448
449function updateLocRecursively (node, n, visitorKeys) {
450 var visitor = {
451 leave: function (currentNode, parentNode) {
452 return n(currentNode);
453 }
454 };
455 if (visitorKeys) {
456 visitor.keys = visitorKeys;
457 }
458 estraverse.replace(node, visitor);
459 return node;
460}
461
462function isPathIdentical (path1, path2) {
463 if (!path1 || !path2) {
464 return false;
465 }
466 return path1.join('/') === path2.join('/');
467}
468
469function newNodeWithLocationCopyOf (original) {
470 return function (newNode) {
471 if (typeof original.loc !== 'undefined') {
472 var newLoc = {
473 start: {
474 line: original.loc.start.line,
475 column: original.loc.start.column
476 },
477 end: {
478 line: original.loc.end.line,
479 column: original.loc.end.column
480 }
481 };
482 if (typeof original.loc.source !== 'undefined') {
483 newLoc.source = original.loc.source;
484 }
485 newNode.loc = newLoc;
486 }
487 if (isArray(original.range)) {
488 newNode.range = [original.range[0], original.range[1]];
489 }
490 return newNode;
491 };
492}
493
494function astEqual (ast1, ast2) {
495 return deepEqual(espurify(ast1), espurify(ast2));
496}
497
498function isFunction (node) {
499 switch(node.type) {
500 case syntax.FunctionDeclaration:
501 case syntax.FunctionExpression:
502 case syntax.ArrowFunctionExpression:
503 return true;
504 }
505 return false;
506}
507
508function findEnclosingFunction (parents) {
509 for (var i = parents.length - 1; i >= 0; i--) {
510 if (isFunction(parents[i])) {
511 return parents[i];
512 }
513 }
514 return null;
515}
516
517function getParentNode (controller) {
518 var parents = controller.parents();
519 return parents[parents.length - 1];
520}
521
522function getCurrentKey (controller) {
523 var path = controller.path();
524 return path ? path[path.length - 1] : null;
525}
526
527module.exports = AssertionVisitor;
528
529},{"./espower-error":5,"./rules/to-be-captured":8,"./rules/to-be-skipped":9,"deep-equal":64,"escodegen":68,"espower-location-detector":83,"espurify":87,"estraverse":91,"isarray":99}],3:[function(_dereq_,module,exports){
530/**
531 * Copyright (C) 2012 Yusuke Suzuki (twitter: @Constellation) and other contributors.
532 * Released under the BSD license.
533 * https://github.com/Constellation/esmangle/blob/master/LICENSE.BSD
534 */
535'use strict';
536
537var isArray = _dereq_('isarray');
538
539function deepCopyInternal (obj, result) {
540 var key, val;
541 for (key in obj) {
542 if (key.lastIndexOf('_', 0) === 0) {
543 continue;
544 }
545 if (obj.hasOwnProperty(key)) {
546 val = obj[key];
547 if (typeof val === 'object' && val !== null) {
548 if (val instanceof RegExp) {
549 val = new RegExp(val);
550 } else {
551 val = deepCopyInternal(val, isArray(val) ? [] : {});
552 }
553 }
554 result[key] = val;
555 }
556 }
557 return result;
558}
559
560function deepCopy (obj) {
561 return deepCopyInternal(obj, isArray(obj) ? [] : {});
562}
563
564module.exports = deepCopy;
565
566},{"isarray":99}],4:[function(_dereq_,module,exports){
567'use strict';
568
569module.exports = function defaultOptions () {
570 return {
571 destructive: false,
572 patterns: [
573 'assert(value, [message])',
574 'assert.ok(value, [message])',
575 'assert.equal(actual, expected, [message])',
576 'assert.notEqual(actual, expected, [message])',
577 'assert.strictEqual(actual, expected, [message])',
578 'assert.notStrictEqual(actual, expected, [message])',
579 'assert.deepEqual(actual, expected, [message])',
580 'assert.notDeepEqual(actual, expected, [message])',
581 'assert.deepStrictEqual(actual, expected, [message])',
582 'assert.notDeepStrictEqual(actual, expected, [message])'
583 ]
584 };
585};
586
587},{}],5:[function(_dereq_,module,exports){
588'use strict';
589
590function EspowerError (message, stackStartFunction) {
591 if (Error.captureStackTrace) { // V8
592 Error.captureStackTrace(this, stackStartFunction);
593 } else {
594 var _err = new Error();
595 var _stack = _err.stack;
596 if (!_stack) { // IE10
597 try {
598 throw _err;
599 } catch (e) {
600 _stack = e.stack;
601 }
602 }
603 this.stack = _stack;
604 }
605 this.message = '[espower] ' + message;
606}
607EspowerError.prototype = Object.create(Error.prototype);
608EspowerError.prototype.constructor = EspowerError;
609EspowerError.prototype.name = 'EspowerError';
610
611module.exports = EspowerError;
612
613},{}],6:[function(_dereq_,module,exports){
614'use strict';
615
616var estraverse = _dereq_('estraverse');
617var syntax = estraverse.Syntax;
618var escallmatch = _dereq_('escallmatch');
619var cloneAst = _dereq_('./clone-ast');
620var AssertionVisitor = _dereq_('./assertion-visitor');
621var EspowerError = _dereq_('./espower-error');
622var typeName = _dereq_('type-name');
623var find = _dereq_('array-find');
624
625function Instrumentor (options) {
626 verifyOptionPrerequisites(options);
627 this.options = options;
628 this.matchers = options.patterns.map(function (pattern) { return escallmatch(pattern, options); });
629}
630
631Instrumentor.prototype.instrument = function (ast) {
632 verifyAstPrerequisites(ast, this.options);
633 var that = this;
634 var assertionVisitor;
635 var skipping = false;
636 var result = (this.options.destructive) ? ast : cloneAst(ast);
637 var visitor = {
638 enter: function (currentNode, parentNode) {
639 var controller = this;
640 var path = controller.path();
641 var currentKey = path ? path[path.length - 1] : null;
642 if (assertionVisitor) {
643 if (assertionVisitor.toBeSkipped(controller)) {
644 skipping = true;
645 return controller.skip();
646 }
647 if (!assertionVisitor.isCapturingArgument() && !isCalleeOfParentCallExpression(parentNode, currentKey)) {
648 return assertionVisitor.enterArgument(controller);
649 }
650 } else if (currentNode.type === syntax.CallExpression) {
651 var matcher = find(that.matchers, function (matcher) { return matcher.test(currentNode); });
652 if (matcher) {
653 // entering target assertion
654 assertionVisitor = new AssertionVisitor(matcher, that.options);
655 assertionVisitor.enter(controller);
656 return undefined;
657 }
658 }
659 return undefined;
660 },
661 leave: function (currentNode, parentNode) {
662 var controller = this;
663 var resultTree = currentNode;
664 if (!assertionVisitor) {
665 return undefined;
666 }
667 if (skipping) {
668 skipping = false;
669 return undefined;
670 }
671 if (assertionVisitor.isLeavingAssertion(controller)) {
672 assertionVisitor.leave(controller);
673 assertionVisitor = null;
674 return undefined;
675 }
676 if (!assertionVisitor.isCapturingArgument()) {
677 return undefined;
678 }
679 if (assertionVisitor.toBeCaptured(controller)) {
680 resultTree = assertionVisitor.captureNode(controller);
681 }
682 if (assertionVisitor.isLeavingArgument(controller)) {
683 return assertionVisitor.leaveArgument(resultTree);
684 }
685 return resultTree;
686 }
687 };
688 if (this.options.visitorKeys) {
689 visitor.keys = this.options.visitorKeys;
690 }
691 estraverse.replace(result, visitor);
692 return result;
693};
694
695function isCalleeOfParentCallExpression (parentNode, currentKey) {
696 return parentNode.type === syntax.CallExpression && currentKey === 'callee';
697}
698
699function verifyAstPrerequisites (ast, options) {
700 var errorMessage;
701 if (typeof ast.loc === 'undefined') {
702 errorMessage = 'ECMAScript AST should contain location information.';
703 if (options.path) {
704 errorMessage += ' path: ' + options.path;
705 }
706 throw new EspowerError(errorMessage, verifyAstPrerequisites);
707 }
708}
709
710function verifyOptionPrerequisites (options) {
711 if (typeName(options.destructive) !== 'boolean') {
712 throw new EspowerError('options.destructive should be a boolean value.', verifyOptionPrerequisites);
713 }
714 if (typeName(options.patterns) !== 'Array') {
715 throw new EspowerError('options.patterns should be an array.', verifyOptionPrerequisites);
716 }
717}
718
719module.exports = Instrumentor;
720
721},{"./assertion-visitor":2,"./clone-ast":3,"./espower-error":5,"array-find":12,"escallmatch":67,"estraverse":91,"type-name":114}],7:[function(_dereq_,module,exports){
722'use strict';
723
724var estraverse = _dereq_('estraverse');
725var syntax = estraverse.Syntax;
726
727module.exports = [
728 syntax.Identifier,
729 syntax.MemberExpression,
730 syntax.CallExpression,
731 syntax.UnaryExpression,
732 syntax.BinaryExpression,
733 syntax.LogicalExpression,
734 syntax.AssignmentExpression,
735 syntax.ObjectExpression,
736 syntax.NewExpression,
737 syntax.ArrayExpression,
738 syntax.ConditionalExpression,
739 syntax.UpdateExpression,
740 syntax.SequenceExpression,
741 syntax.TemplateLiteral,
742 syntax.TaggedTemplateExpression,
743 syntax.SpreadElement,
744 syntax.YieldExpression,
745 syntax.AwaitExpression,
746 syntax.Property
747];
748
749},{"estraverse":91}],8:[function(_dereq_,module,exports){
750'use strict';
751
752var estraverse = _dereq_('estraverse');
753var syntax = estraverse.Syntax;
754var caputuringTargetTypes = [
755 // syntax.Property,
756 syntax.ObjectExpression,
757 syntax.ArrayExpression,
758 syntax.SequenceExpression,
759 // syntax.ConditionalExpression,
760 syntax.Identifier,
761 syntax.MemberExpression,
762 syntax.CallExpression,
763 syntax.UnaryExpression,
764 syntax.BinaryExpression,
765 syntax.LogicalExpression,
766 syntax.AssignmentExpression,
767 syntax.NewExpression,
768 syntax.UpdateExpression,
769 syntax.YieldExpression,
770 syntax.AwaitExpression,
771 syntax.TemplateLiteral,
772 syntax.TaggedTemplateExpression
773];
774
775function isCaputuringTargetType (currentNode) {
776 return caputuringTargetTypes.indexOf(currentNode.type) !== -1;
777}
778
779function isCalleeOfParent(parentNode, currentKey) {
780 return (parentNode.type === syntax.CallExpression || parentNode.type === syntax.NewExpression) && currentKey === 'callee';
781}
782
783function isChildOfTaggedTemplateExpression(parentNode) {
784 return parentNode.type === syntax.TaggedTemplateExpression;
785}
786
787function isYieldOrAwaitArgument(parentNode, currentKey) {
788 // capture the yielded/await result, not the promise
789 return (parentNode.type === syntax.YieldExpression || parentNode.type === syntax.AwaitExpression) && currentKey === 'argument';
790}
791
792module.exports = function toBeCaptured (currentNode, parentNode, currentKey) {
793 return isCaputuringTargetType(currentNode) &&
794 !isYieldOrAwaitArgument(parentNode, currentKey) &&
795 !isCalleeOfParent(parentNode, currentKey) &&
796 !isChildOfTaggedTemplateExpression(parentNode);
797};
798
799},{"estraverse":91}],9:[function(_dereq_,module,exports){
800'use strict';
801
802var estraverse = _dereq_('estraverse');
803var syntax = estraverse.Syntax;
804var supportedNodeTypes = _dereq_('./supported-node-types');
805
806function isLeftHandSideOfAssignment(parentNode, currentKey) {
807 // Do not instrument left due to 'Invalid left-hand side in assignment'
808 return parentNode.type === syntax.AssignmentExpression && currentKey === 'left';
809}
810
811function isChildOfObjectLiteral (parentNode) {
812 return parentNode.type === syntax.Property && parentNode.kind === 'init';
813}
814
815function isObjectLiteralKey (parentNode, currentKey) {
816 return isChildOfObjectLiteral(parentNode) && currentKey === 'key';
817}
818
819function isObjectLiteralValue (parentNode, currentKey) {
820 return isChildOfObjectLiteral(parentNode) && currentKey === 'value';
821}
822
823function isNonComputedObjectLiteralKey(parentNode, currentKey) {
824 // Do not instrument non-computed Object literal key
825 return isObjectLiteralKey(parentNode, currentKey) && !parentNode.computed;
826}
827
828function isShorthandedValueOfObjectLiteral(parentNode, currentKey) {
829 // Do not instrument shorthanded Object literal value
830 return isObjectLiteralValue(parentNode, currentKey) && parentNode.shorthand;
831}
832
833function isUpdateExpression(parentNode) {
834 // Just wrap UpdateExpression, not digging in.
835 return parentNode.type === syntax.UpdateExpression;
836}
837
838function isCallExpressionWithNonComputedMemberExpression(currentNode, parentNode, currentKey) {
839 // Do not instrument non-computed property of MemberExpression within CallExpression.
840 return currentNode.type === syntax.Identifier && parentNode.type === syntax.MemberExpression && !parentNode.computed && currentKey === 'property';
841}
842
843function isTypeOfOrDeleteUnaryExpression(currentNode, parentNode, currentKey) {
844 // 'typeof Identifier' or 'delete Identifier' is not instrumented
845 return currentNode.type === syntax.Identifier && parentNode.type === syntax.UnaryExpression && (parentNode.operator === 'typeof' || parentNode.operator === 'delete') && currentKey === 'argument';
846}
847
848function isSupportedNodeType (node) {
849 return supportedNodeTypes.indexOf(node.type) !== -1;
850}
851
852module.exports = function toBeSkipped (currentNode, parentNode, currentKey) {
853 return !isSupportedNodeType(currentNode) ||
854 isLeftHandSideOfAssignment(parentNode, currentKey) ||
855 isNonComputedObjectLiteralKey(parentNode, currentKey) ||
856 isShorthandedValueOfObjectLiteral(parentNode, currentKey) ||
857 isUpdateExpression(parentNode) ||
858 isCallExpressionWithNonComputedMemberExpression(currentNode, parentNode, currentKey) ||
859 isTypeOfOrDeleteUnaryExpression(currentNode, parentNode, currentKey);
860};
861
862},{"./supported-node-types":7,"estraverse":91}],10:[function(_dereq_,module,exports){
863(function (process,__filename){
864/** vim: et:ts=4:sw=4:sts=4
865 * @license amdefine 1.0.0 Copyright (c) 2011-2015, The Dojo Foundation All Rights Reserved.
866 * Available via the MIT or new BSD license.
867 * see: http://github.com/jrburke/amdefine for details
868 */
869
870/*jslint node: true */
871/*global module, process */
872'use strict';
873
874/**
875 * Creates a define for node.
876 * @param {Object} module the "module" object that is defined by Node for the
877 * current module.
878 * @param {Function} [requireFn]. Node's require function for the current module.
879 * It only needs to be passed in Node versions before 0.5, when module.require
880 * did not exist.
881 * @returns {Function} a define function that is usable for the current node
882 * module.
883 */
884function amdefine(module, requireFn) {
885 'use strict';
886 var defineCache = {},
887 loaderCache = {},
888 alreadyCalled = false,
889 path = _dereq_('path'),
890 makeRequire, stringRequire;
891
892 /**
893 * Trims the . and .. from an array of path segments.
894 * It will keep a leading path segment if a .. will become
895 * the first path segment, to help with module name lookups,
896 * which act like paths, but can be remapped. But the end result,
897 * all paths that use this function should look normalized.
898 * NOTE: this method MODIFIES the input array.
899 * @param {Array} ary the array of path segments.
900 */
901 function trimDots(ary) {
902 var i, part;
903 for (i = 0; ary[i]; i+= 1) {
904 part = ary[i];
905 if (part === '.') {
906 ary.splice(i, 1);
907 i -= 1;
908 } else if (part === '..') {
909 if (i === 1 && (ary[2] === '..' || ary[0] === '..')) {
910 //End of the line. Keep at least one non-dot
911 //path segment at the front so it can be mapped
912 //correctly to disk. Otherwise, there is likely
913 //no path mapping for a path starting with '..'.
914 //This can still fail, but catches the most reasonable
915 //uses of ..
916 break;
917 } else if (i > 0) {
918 ary.splice(i - 1, 2);
919 i -= 2;
920 }
921 }
922 }
923 }
924
925 function normalize(name, baseName) {
926 var baseParts;
927
928 //Adjust any relative paths.
929 if (name && name.charAt(0) === '.') {
930 //If have a base name, try to normalize against it,
931 //otherwise, assume it is a top-level require that will
932 //be relative to baseUrl in the end.
933 if (baseName) {
934 baseParts = baseName.split('/');
935 baseParts = baseParts.slice(0, baseParts.length - 1);
936 baseParts = baseParts.concat(name.split('/'));
937 trimDots(baseParts);
938 name = baseParts.join('/');
939 }
940 }
941
942 return name;
943 }
944
945 /**
946 * Create the normalize() function passed to a loader plugin's
947 * normalize method.
948 */
949 function makeNormalize(relName) {
950 return function (name) {
951 return normalize(name, relName);
952 };
953 }
954
955 function makeLoad(id) {
956 function load(value) {
957 loaderCache[id] = value;
958 }
959
960 load.fromText = function (id, text) {
961 //This one is difficult because the text can/probably uses
962 //define, and any relative paths and requires should be relative
963 //to that id was it would be found on disk. But this would require
964 //bootstrapping a module/require fairly deeply from node core.
965 //Not sure how best to go about that yet.
966 throw new Error('amdefine does not implement load.fromText');
967 };
968
969 return load;
970 }
971
972 makeRequire = function (systemRequire, exports, module, relId) {
973 function amdRequire(deps, callback) {
974 if (typeof deps === 'string') {
975 //Synchronous, single module require('')
976 return stringRequire(systemRequire, exports, module, deps, relId);
977 } else {
978 //Array of dependencies with a callback.
979
980 //Convert the dependencies to modules.
981 deps = deps.map(function (depName) {
982 return stringRequire(systemRequire, exports, module, depName, relId);
983 });
984
985 //Wait for next tick to call back the require call.
986 if (callback) {
987 process.nextTick(function () {
988 callback.apply(null, deps);
989 });
990 }
991 }
992 }
993
994 amdRequire.toUrl = function (filePath) {
995 if (filePath.indexOf('.') === 0) {
996 return normalize(filePath, path.dirname(module.filename));
997 } else {
998 return filePath;
999 }
1000 };
1001
1002 return amdRequire;
1003 };
1004
1005 //Favor explicit value, passed in if the module wants to support Node 0.4.
1006 requireFn = requireFn || function req() {
1007 return module.require.apply(module, arguments);
1008 };
1009
1010 function runFactory(id, deps, factory) {
1011 var r, e, m, result;
1012
1013 if (id) {
1014 e = loaderCache[id] = {};
1015 m = {
1016 id: id,
1017 uri: __filename,
1018 exports: e
1019 };
1020 r = makeRequire(requireFn, e, m, id);
1021 } else {
1022 //Only support one define call per file
1023 if (alreadyCalled) {
1024 throw new Error('amdefine with no module ID cannot be called more than once per file.');
1025 }
1026 alreadyCalled = true;
1027
1028 //Use the real variables from node
1029 //Use module.exports for exports, since
1030 //the exports in here is amdefine exports.
1031 e = module.exports;
1032 m = module;
1033 r = makeRequire(requireFn, e, m, module.id);
1034 }
1035
1036 //If there are dependencies, they are strings, so need
1037 //to convert them to dependency values.
1038 if (deps) {
1039 deps = deps.map(function (depName) {
1040 return r(depName);
1041 });
1042 }
1043
1044 //Call the factory with the right dependencies.
1045 if (typeof factory === 'function') {
1046 result = factory.apply(m.exports, deps);
1047 } else {
1048 result = factory;
1049 }
1050
1051 if (result !== undefined) {
1052 m.exports = result;
1053 if (id) {
1054 loaderCache[id] = m.exports;
1055 }
1056 }
1057 }
1058
1059 stringRequire = function (systemRequire, exports, module, id, relId) {
1060 //Split the ID by a ! so that
1061 var index = id.indexOf('!'),
1062 originalId = id,
1063 prefix, plugin;
1064
1065 if (index === -1) {
1066 id = normalize(id, relId);
1067
1068 //Straight module lookup. If it is one of the special dependencies,
1069 //deal with it, otherwise, delegate to node.
1070 if (id === 'require') {
1071 return makeRequire(systemRequire, exports, module, relId);
1072 } else if (id === 'exports') {
1073 return exports;
1074 } else if (id === 'module') {
1075 return module;
1076 } else if (loaderCache.hasOwnProperty(id)) {
1077 return loaderCache[id];
1078 } else if (defineCache[id]) {
1079 runFactory.apply(null, defineCache[id]);
1080 return loaderCache[id];
1081 } else {
1082 if(systemRequire) {
1083 return systemRequire(originalId);
1084 } else {
1085 throw new Error('No module with ID: ' + id);
1086 }
1087 }
1088 } else {
1089 //There is a plugin in play.
1090 prefix = id.substring(0, index);
1091 id = id.substring(index + 1, id.length);
1092
1093 plugin = stringRequire(systemRequire, exports, module, prefix, relId);
1094
1095 if (plugin.normalize) {
1096 id = plugin.normalize(id, makeNormalize(relId));
1097 } else {
1098 //Normalize the ID normally.
1099 id = normalize(id, relId);
1100 }
1101
1102 if (loaderCache[id]) {
1103 return loaderCache[id];
1104 } else {
1105 plugin.load(id, makeRequire(systemRequire, exports, module, relId), makeLoad(id), {});
1106
1107 return loaderCache[id];
1108 }
1109 }
1110 };
1111
1112 //Create a define function specific to the module asking for amdefine.
1113 function define(id, deps, factory) {
1114 if (Array.isArray(id)) {
1115 factory = deps;
1116 deps = id;
1117 id = undefined;
1118 } else if (typeof id !== 'string') {
1119 factory = id;
1120 id = deps = undefined;
1121 }
1122
1123 if (deps && !Array.isArray(deps)) {
1124 factory = deps;
1125 deps = undefined;
1126 }
1127
1128 if (!deps) {
1129 deps = ['require', 'exports', 'module'];
1130 }
1131
1132 //Set up properties for this module. If an ID, then use
1133 //internal cache. If no ID, then use the external variables
1134 //for this node module.
1135 if (id) {
1136 //Put the module in deep freeze until there is a
1137 //require call for it.
1138 defineCache[id] = [id, deps, factory];
1139 } else {
1140 runFactory(id, deps, factory);
1141 }
1142 }
1143
1144 //define.require, which has access to all the values in the
1145 //cache. Useful for AMD modules that all have IDs in the file,
1146 //but need to finally export a value to node based on one of those
1147 //IDs.
1148 define.require = function (id) {
1149 if (loaderCache[id]) {
1150 return loaderCache[id];
1151 }
1152
1153 if (defineCache[id]) {
1154 runFactory.apply(null, defineCache[id]);
1155 return loaderCache[id];
1156 }
1157 };
1158
1159 define.amd = {};
1160
1161 return define;
1162}
1163
1164module.exports = amdefine;
1165
1166}).call(this,_dereq_('_process'),"/node_modules/amdefine/amdefine.js")
1167},{"_process":102,"path":100}],11:[function(_dereq_,module,exports){
1168
1169/**
1170 * Array#filter.
1171 *
1172 * @param {Array} arr
1173 * @param {Function} fn
1174 * @param {Object=} self
1175 * @return {Array}
1176 * @throw TypeError
1177 */
1178
1179module.exports = function (arr, fn, self) {
1180 if (arr.filter) return arr.filter(fn, self);
1181 if (void 0 === arr || null === arr) throw new TypeError;
1182 if ('function' != typeof fn) throw new TypeError;
1183 var ret = [];
1184 for (var i = 0; i < arr.length; i++) {
1185 if (!hasOwn.call(arr, i)) continue;
1186 var val = arr[i];
1187 if (fn.call(self, val, i, arr)) ret.push(val);
1188 }
1189 return ret;
1190};
1191
1192var hasOwn = Object.prototype.hasOwnProperty;
1193
1194},{}],12:[function(_dereq_,module,exports){
1195'use strict';
1196
1197function find(array, predicate, context) {
1198 if (typeof Array.prototype.find === 'function') {
1199 return array.find(predicate, context);
1200 }
1201
1202 context = context || this;
1203 var length = array.length;
1204 var i;
1205
1206 if (typeof predicate !== 'function') {
1207 throw new TypeError(predicate + ' is not a function');
1208 }
1209
1210 for (i = 0; i < length; i++) {
1211 if (predicate.call(context, array[i], i, array)) {
1212 return array[i];
1213 }
1214 }
1215}
1216
1217module.exports = find;
1218
1219},{}],13:[function(_dereq_,module,exports){
1220/**
1221 * array-foreach
1222 * Array#forEach ponyfill for older browsers
1223 * (Ponyfill: A polyfill that doesn't overwrite the native method)
1224 *
1225 * https://github.com/twada/array-foreach
1226 *
1227 * Copyright (c) 2015-2016 Takuto Wada
1228 * Licensed under the MIT license.
1229 * https://github.com/twada/array-foreach/blob/master/MIT-LICENSE
1230 */
1231'use strict';
1232
1233module.exports = function forEach (ary, callback, thisArg) {
1234 if (ary.forEach) {
1235 ary.forEach(callback, thisArg);
1236 return;
1237 }
1238 for (var i = 0; i < ary.length; i+=1) {
1239 callback.call(thisArg, ary[i], i, ary);
1240 }
1241};
1242
1243},{}],14:[function(_dereq_,module,exports){
1244module.exports = function (xs, f) {
1245 if (xs.map) return xs.map(f);
1246 var res = [];
1247 for (var i = 0; i < xs.length; i++) {
1248 var x = xs[i];
1249 if (hasOwn.call(xs, i)) res.push(f(x, i, xs));
1250 }
1251 return res;
1252};
1253
1254var hasOwn = Object.prototype.hasOwnProperty;
1255
1256},{}],15:[function(_dereq_,module,exports){
1257var hasOwn = Object.prototype.hasOwnProperty;
1258
1259module.exports = function (xs, f, acc) {
1260 var hasAcc = arguments.length >= 3;
1261 if (hasAcc && xs.reduce) return xs.reduce(f, acc);
1262 if (xs.reduce) return xs.reduce(f);
1263
1264 for (var i = 0; i < xs.length; i++) {
1265 if (!hasOwn.call(xs, i)) continue;
1266 if (!hasAcc) {
1267 acc = xs[i];
1268 hasAcc = true;
1269 continue;
1270 }
1271 acc = f(acc, xs[i], i);
1272 }
1273 return acc;
1274};
1275
1276},{}],16:[function(_dereq_,module,exports){
1277_dereq_('../../modules/es6.array.index-of');
1278module.exports = _dereq_('../../modules/_core').Array.indexOf;
1279},{"../../modules/_core":26,"../../modules/es6.array.index-of":59}],17:[function(_dereq_,module,exports){
1280_dereq_('../../modules/es6.array.is-array');
1281module.exports = _dereq_('../../modules/_core').Array.isArray;
1282},{"../../modules/_core":26,"../../modules/es6.array.is-array":60}],18:[function(_dereq_,module,exports){
1283_dereq_('../../modules/es6.array.reduce');
1284module.exports = _dereq_('../../modules/_core').Array.reduce;
1285},{"../../modules/_core":26,"../../modules/es6.array.reduce":61}],19:[function(_dereq_,module,exports){
1286_dereq_('../../modules/es6.object.assign');
1287module.exports = _dereq_('../../modules/_core').Object.assign;
1288},{"../../modules/_core":26,"../../modules/es6.object.assign":62}],20:[function(_dereq_,module,exports){
1289_dereq_('../../modules/es6.object.keys');
1290module.exports = _dereq_('../../modules/_core').Object.keys;
1291},{"../../modules/_core":26,"../../modules/es6.object.keys":63}],21:[function(_dereq_,module,exports){
1292module.exports = function(it){
1293 if(typeof it != 'function')throw TypeError(it + ' is not a function!');
1294 return it;
1295};
1296},{}],22:[function(_dereq_,module,exports){
1297var isObject = _dereq_('./_is-object');
1298module.exports = function(it){
1299 if(!isObject(it))throw TypeError(it + ' is not an object!');
1300 return it;
1301};
1302},{"./_is-object":40}],23:[function(_dereq_,module,exports){
1303// false -> Array#indexOf
1304// true -> Array#includes
1305var toIObject = _dereq_('./_to-iobject')
1306 , toLength = _dereq_('./_to-length')
1307 , toIndex = _dereq_('./_to-index');
1308module.exports = function(IS_INCLUDES){
1309 return function($this, el, fromIndex){
1310 var O = toIObject($this)
1311 , length = toLength(O.length)
1312 , index = toIndex(fromIndex, length)
1313 , value;
1314 // Array#includes uses SameValueZero equality algorithm
1315 if(IS_INCLUDES && el != el)while(length > index){
1316 value = O[index++];
1317 if(value != value)return true;
1318 // Array#toIndex ignores holes, Array#includes - not
1319 } else for(;length > index; index++)if(IS_INCLUDES || index in O){
1320 if(O[index] === el)return IS_INCLUDES || index || 0;
1321 } return !IS_INCLUDES && -1;
1322 };
1323};
1324},{"./_to-index":52,"./_to-iobject":54,"./_to-length":55}],24:[function(_dereq_,module,exports){
1325var aFunction = _dereq_('./_a-function')
1326 , toObject = _dereq_('./_to-object')
1327 , IObject = _dereq_('./_iobject')
1328 , toLength = _dereq_('./_to-length');
1329
1330module.exports = function(that, callbackfn, aLen, memo, isRight){
1331 aFunction(callbackfn);
1332 var O = toObject(that)
1333 , self = IObject(O)
1334 , length = toLength(O.length)
1335 , index = isRight ? length - 1 : 0
1336 , i = isRight ? -1 : 1;
1337 if(aLen < 2)for(;;){
1338 if(index in self){
1339 memo = self[index];
1340 index += i;
1341 break;
1342 }
1343 index += i;
1344 if(isRight ? index < 0 : length <= index){
1345 throw TypeError('Reduce of empty array with no initial value');
1346 }
1347 }
1348 for(;isRight ? index >= 0 : length > index; index += i)if(index in self){
1349 memo = callbackfn(memo, self[index], index, O);
1350 }
1351 return memo;
1352};
1353},{"./_a-function":21,"./_iobject":38,"./_to-length":55,"./_to-object":56}],25:[function(_dereq_,module,exports){
1354var toString = {}.toString;
1355
1356module.exports = function(it){
1357 return toString.call(it).slice(8, -1);
1358};
1359},{}],26:[function(_dereq_,module,exports){
1360var core = module.exports = {version: '2.4.0'};
1361if(typeof __e == 'number')__e = core; // eslint-disable-line no-undef
1362},{}],27:[function(_dereq_,module,exports){
1363// optional / simple context binding
1364var aFunction = _dereq_('./_a-function');
1365module.exports = function(fn, that, length){
1366 aFunction(fn);
1367 if(that === undefined)return fn;
1368 switch(length){
1369 case 1: return function(a){
1370 return fn.call(that, a);
1371 };
1372 case 2: return function(a, b){
1373 return fn.call(that, a, b);
1374 };
1375 case 3: return function(a, b, c){
1376 return fn.call(that, a, b, c);
1377 };
1378 }
1379 return function(/* ...args */){
1380 return fn.apply(that, arguments);
1381 };
1382};
1383},{"./_a-function":21}],28:[function(_dereq_,module,exports){
1384// 7.2.1 RequireObjectCoercible(argument)
1385module.exports = function(it){
1386 if(it == undefined)throw TypeError("Can't call method on " + it);
1387 return it;
1388};
1389},{}],29:[function(_dereq_,module,exports){
1390// Thank's IE8 for his funny defineProperty
1391module.exports = !_dereq_('./_fails')(function(){
1392 return Object.defineProperty({}, 'a', {get: function(){ return 7; }}).a != 7;
1393});
1394},{"./_fails":33}],30:[function(_dereq_,module,exports){
1395var isObject = _dereq_('./_is-object')
1396 , document = _dereq_('./_global').document
1397 // in old IE typeof document.createElement is 'object'
1398 , is = isObject(document) && isObject(document.createElement);
1399module.exports = function(it){
1400 return is ? document.createElement(it) : {};
1401};
1402},{"./_global":34,"./_is-object":40}],31:[function(_dereq_,module,exports){
1403// IE 8- don't enum bug keys
1404module.exports = (
1405 'constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf'
1406).split(',');
1407},{}],32:[function(_dereq_,module,exports){
1408var global = _dereq_('./_global')
1409 , core = _dereq_('./_core')
1410 , ctx = _dereq_('./_ctx')
1411 , hide = _dereq_('./_hide')
1412 , PROTOTYPE = 'prototype';
1413
1414var $export = function(type, name, source){
1415 var IS_FORCED = type & $export.F
1416 , IS_GLOBAL = type & $export.G
1417 , IS_STATIC = type & $export.S
1418 , IS_PROTO = type & $export.P
1419 , IS_BIND = type & $export.B
1420 , IS_WRAP = type & $export.W
1421 , exports = IS_GLOBAL ? core : core[name] || (core[name] = {})
1422 , expProto = exports[PROTOTYPE]
1423 , target = IS_GLOBAL ? global : IS_STATIC ? global[name] : (global[name] || {})[PROTOTYPE]
1424 , key, own, out;
1425 if(IS_GLOBAL)source = name;
1426 for(key in source){
1427 // contains in native
1428 own = !IS_FORCED && target && target[key] !== undefined;
1429 if(own && key in exports)continue;
1430 // export native or passed
1431 out = own ? target[key] : source[key];
1432 // prevent global pollution for namespaces
1433 exports[key] = IS_GLOBAL && typeof target[key] != 'function' ? source[key]
1434 // bind timers to global for call from export context
1435 : IS_BIND && own ? ctx(out, global)
1436 // wrap global constructors for prevent change them in library
1437 : IS_WRAP && target[key] == out ? (function(C){
1438 var F = function(a, b, c){
1439 if(this instanceof C){
1440 switch(arguments.length){
1441 case 0: return new C;
1442 case 1: return new C(a);
1443 case 2: return new C(a, b);
1444 } return new C(a, b, c);
1445 } return C.apply(this, arguments);
1446 };
1447 F[PROTOTYPE] = C[PROTOTYPE];
1448 return F;
1449 // make static versions for prototype methods
1450 })(out) : IS_PROTO && typeof out == 'function' ? ctx(Function.call, out) : out;
1451 // export proto methods to core.%CONSTRUCTOR%.methods.%NAME%
1452 if(IS_PROTO){
1453 (exports.virtual || (exports.virtual = {}))[key] = out;
1454 // export proto methods to core.%CONSTRUCTOR%.prototype.%NAME%
1455 if(type & $export.R && expProto && !expProto[key])hide(expProto, key, out);
1456 }
1457 }
1458};
1459// type bitmap
1460$export.F = 1; // forced
1461$export.G = 2; // global
1462$export.S = 4; // static
1463$export.P = 8; // proto
1464$export.B = 16; // bind
1465$export.W = 32; // wrap
1466$export.U = 64; // safe
1467$export.R = 128; // real proto method for `library`
1468module.exports = $export;
1469},{"./_core":26,"./_ctx":27,"./_global":34,"./_hide":36}],33:[function(_dereq_,module,exports){
1470module.exports = function(exec){
1471 try {
1472 return !!exec();
1473 } catch(e){
1474 return true;
1475 }
1476};
1477},{}],34:[function(_dereq_,module,exports){
1478// https://github.com/zloirock/core-js/issues/86#issuecomment-115759028
1479var global = module.exports = typeof window != 'undefined' && window.Math == Math
1480 ? window : typeof self != 'undefined' && self.Math == Math ? self : Function('return this')();
1481if(typeof __g == 'number')__g = global; // eslint-disable-line no-undef
1482},{}],35:[function(_dereq_,module,exports){
1483var hasOwnProperty = {}.hasOwnProperty;
1484module.exports = function(it, key){
1485 return hasOwnProperty.call(it, key);
1486};
1487},{}],36:[function(_dereq_,module,exports){
1488var dP = _dereq_('./_object-dp')
1489 , createDesc = _dereq_('./_property-desc');
1490module.exports = _dereq_('./_descriptors') ? function(object, key, value){
1491 return dP.f(object, key, createDesc(1, value));
1492} : function(object, key, value){
1493 object[key] = value;
1494 return object;
1495};
1496},{"./_descriptors":29,"./_object-dp":42,"./_property-desc":48}],37:[function(_dereq_,module,exports){
1497module.exports = !_dereq_('./_descriptors') && !_dereq_('./_fails')(function(){
1498 return Object.defineProperty(_dereq_('./_dom-create')('div'), 'a', {get: function(){ return 7; }}).a != 7;
1499});
1500},{"./_descriptors":29,"./_dom-create":30,"./_fails":33}],38:[function(_dereq_,module,exports){
1501// fallback for non-array-like ES3 and non-enumerable old V8 strings
1502var cof = _dereq_('./_cof');
1503module.exports = Object('z').propertyIsEnumerable(0) ? Object : function(it){
1504 return cof(it) == 'String' ? it.split('') : Object(it);
1505};
1506},{"./_cof":25}],39:[function(_dereq_,module,exports){
1507// 7.2.2 IsArray(argument)
1508var cof = _dereq_('./_cof');
1509module.exports = Array.isArray || function isArray(arg){
1510 return cof(arg) == 'Array';
1511};
1512},{"./_cof":25}],40:[function(_dereq_,module,exports){
1513module.exports = function(it){
1514 return typeof it === 'object' ? it !== null : typeof it === 'function';
1515};
1516},{}],41:[function(_dereq_,module,exports){
1517'use strict';
1518// 19.1.2.1 Object.assign(target, source, ...)
1519var getKeys = _dereq_('./_object-keys')
1520 , gOPS = _dereq_('./_object-gops')
1521 , pIE = _dereq_('./_object-pie')
1522 , toObject = _dereq_('./_to-object')
1523 , IObject = _dereq_('./_iobject')
1524 , $assign = Object.assign;
1525
1526// should work with symbols and should have deterministic property order (V8 bug)
1527module.exports = !$assign || _dereq_('./_fails')(function(){
1528 var A = {}
1529 , B = {}
1530 , S = Symbol()
1531 , K = 'abcdefghijklmnopqrst';
1532 A[S] = 7;
1533 K.split('').forEach(function(k){ B[k] = k; });
1534 return $assign({}, A)[S] != 7 || Object.keys($assign({}, B)).join('') != K;
1535}) ? function assign(target, source){ // eslint-disable-line no-unused-vars
1536 var T = toObject(target)
1537 , aLen = arguments.length
1538 , index = 1
1539 , getSymbols = gOPS.f
1540 , isEnum = pIE.f;
1541 while(aLen > index){
1542 var S = IObject(arguments[index++])
1543 , keys = getSymbols ? getKeys(S).concat(getSymbols(S)) : getKeys(S)
1544 , length = keys.length
1545 , j = 0
1546 , key;
1547 while(length > j)if(isEnum.call(S, key = keys[j++]))T[key] = S[key];
1548 } return T;
1549} : $assign;
1550},{"./_fails":33,"./_iobject":38,"./_object-gops":43,"./_object-keys":45,"./_object-pie":46,"./_to-object":56}],42:[function(_dereq_,module,exports){
1551var anObject = _dereq_('./_an-object')
1552 , IE8_DOM_DEFINE = _dereq_('./_ie8-dom-define')
1553 , toPrimitive = _dereq_('./_to-primitive')
1554 , dP = Object.defineProperty;
1555
1556exports.f = _dereq_('./_descriptors') ? Object.defineProperty : function defineProperty(O, P, Attributes){
1557 anObject(O);
1558 P = toPrimitive(P, true);
1559 anObject(Attributes);
1560 if(IE8_DOM_DEFINE)try {
1561 return dP(O, P, Attributes);
1562 } catch(e){ /* empty */ }
1563 if('get' in Attributes || 'set' in Attributes)throw TypeError('Accessors not supported!');
1564 if('value' in Attributes)O[P] = Attributes.value;
1565 return O;
1566};
1567},{"./_an-object":22,"./_descriptors":29,"./_ie8-dom-define":37,"./_to-primitive":57}],43:[function(_dereq_,module,exports){
1568exports.f = Object.getOwnPropertySymbols;
1569},{}],44:[function(_dereq_,module,exports){
1570var has = _dereq_('./_has')
1571 , toIObject = _dereq_('./_to-iobject')
1572 , arrayIndexOf = _dereq_('./_array-includes')(false)
1573 , IE_PROTO = _dereq_('./_shared-key')('IE_PROTO');
1574
1575module.exports = function(object, names){
1576 var O = toIObject(object)
1577 , i = 0
1578 , result = []
1579 , key;
1580 for(key in O)if(key != IE_PROTO)has(O, key) && result.push(key);
1581 // Don't enum bug & hidden keys
1582 while(names.length > i)if(has(O, key = names[i++])){
1583 ~arrayIndexOf(result, key) || result.push(key);
1584 }
1585 return result;
1586};
1587},{"./_array-includes":23,"./_has":35,"./_shared-key":49,"./_to-iobject":54}],45:[function(_dereq_,module,exports){
1588// 19.1.2.14 / 15.2.3.14 Object.keys(O)
1589var $keys = _dereq_('./_object-keys-internal')
1590 , enumBugKeys = _dereq_('./_enum-bug-keys');
1591
1592module.exports = Object.keys || function keys(O){
1593 return $keys(O, enumBugKeys);
1594};
1595},{"./_enum-bug-keys":31,"./_object-keys-internal":44}],46:[function(_dereq_,module,exports){
1596exports.f = {}.propertyIsEnumerable;
1597},{}],47:[function(_dereq_,module,exports){
1598// most Object methods by ES6 should accept primitives
1599var $export = _dereq_('./_export')
1600 , core = _dereq_('./_core')
1601 , fails = _dereq_('./_fails');
1602module.exports = function(KEY, exec){
1603 var fn = (core.Object || {})[KEY] || Object[KEY]
1604 , exp = {};
1605 exp[KEY] = exec(fn);
1606 $export($export.S + $export.F * fails(function(){ fn(1); }), 'Object', exp);
1607};
1608},{"./_core":26,"./_export":32,"./_fails":33}],48:[function(_dereq_,module,exports){
1609module.exports = function(bitmap, value){
1610 return {
1611 enumerable : !(bitmap & 1),
1612 configurable: !(bitmap & 2),
1613 writable : !(bitmap & 4),
1614 value : value
1615 };
1616};
1617},{}],49:[function(_dereq_,module,exports){
1618var shared = _dereq_('./_shared')('keys')
1619 , uid = _dereq_('./_uid');
1620module.exports = function(key){
1621 return shared[key] || (shared[key] = uid(key));
1622};
1623},{"./_shared":50,"./_uid":58}],50:[function(_dereq_,module,exports){
1624var global = _dereq_('./_global')
1625 , SHARED = '__core-js_shared__'
1626 , store = global[SHARED] || (global[SHARED] = {});
1627module.exports = function(key){
1628 return store[key] || (store[key] = {});
1629};
1630},{"./_global":34}],51:[function(_dereq_,module,exports){
1631var fails = _dereq_('./_fails');
1632
1633module.exports = function(method, arg){
1634 return !!method && fails(function(){
1635 arg ? method.call(null, function(){}, 1) : method.call(null);
1636 });
1637};
1638},{"./_fails":33}],52:[function(_dereq_,module,exports){
1639var toInteger = _dereq_('./_to-integer')
1640 , max = Math.max
1641 , min = Math.min;
1642module.exports = function(index, length){
1643 index = toInteger(index);
1644 return index < 0 ? max(index + length, 0) : min(index, length);
1645};
1646},{"./_to-integer":53}],53:[function(_dereq_,module,exports){
1647// 7.1.4 ToInteger
1648var ceil = Math.ceil
1649 , floor = Math.floor;
1650module.exports = function(it){
1651 return isNaN(it = +it) ? 0 : (it > 0 ? floor : ceil)(it);
1652};
1653},{}],54:[function(_dereq_,module,exports){
1654// to indexed object, toObject with fallback for non-array-like ES3 strings
1655var IObject = _dereq_('./_iobject')
1656 , defined = _dereq_('./_defined');
1657module.exports = function(it){
1658 return IObject(defined(it));
1659};
1660},{"./_defined":28,"./_iobject":38}],55:[function(_dereq_,module,exports){
1661// 7.1.15 ToLength
1662var toInteger = _dereq_('./_to-integer')
1663 , min = Math.min;
1664module.exports = function(it){
1665 return it > 0 ? min(toInteger(it), 0x1fffffffffffff) : 0; // pow(2, 53) - 1 == 9007199254740991
1666};
1667},{"./_to-integer":53}],56:[function(_dereq_,module,exports){
1668// 7.1.13 ToObject(argument)
1669var defined = _dereq_('./_defined');
1670module.exports = function(it){
1671 return Object(defined(it));
1672};
1673},{"./_defined":28}],57:[function(_dereq_,module,exports){
1674// 7.1.1 ToPrimitive(input [, PreferredType])
1675var isObject = _dereq_('./_is-object');
1676// instead of the ES6 spec version, we didn't implement @@toPrimitive case
1677// and the second argument - flag - preferred type is a string
1678module.exports = function(it, S){
1679 if(!isObject(it))return it;
1680 var fn, val;
1681 if(S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it)))return val;
1682 if(typeof (fn = it.valueOf) == 'function' && !isObject(val = fn.call(it)))return val;
1683 if(!S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it)))return val;
1684 throw TypeError("Can't convert object to primitive value");
1685};
1686},{"./_is-object":40}],58:[function(_dereq_,module,exports){
1687var id = 0
1688 , px = Math.random();
1689module.exports = function(key){
1690 return 'Symbol('.concat(key === undefined ? '' : key, ')_', (++id + px).toString(36));
1691};
1692},{}],59:[function(_dereq_,module,exports){
1693'use strict';
1694var $export = _dereq_('./_export')
1695 , $indexOf = _dereq_('./_array-includes')(false)
1696 , $native = [].indexOf
1697 , NEGATIVE_ZERO = !!$native && 1 / [1].indexOf(1, -0) < 0;
1698
1699$export($export.P + $export.F * (NEGATIVE_ZERO || !_dereq_('./_strict-method')($native)), 'Array', {
1700 // 22.1.3.11 / 15.4.4.14 Array.prototype.indexOf(searchElement [, fromIndex])
1701 indexOf: function indexOf(searchElement /*, fromIndex = 0 */){
1702 return NEGATIVE_ZERO
1703 // convert -0 to +0
1704 ? $native.apply(this, arguments) || 0
1705 : $indexOf(this, searchElement, arguments[1]);
1706 }
1707});
1708},{"./_array-includes":23,"./_export":32,"./_strict-method":51}],60:[function(_dereq_,module,exports){
1709// 22.1.2.2 / 15.4.3.2 Array.isArray(arg)
1710var $export = _dereq_('./_export');
1711
1712$export($export.S, 'Array', {isArray: _dereq_('./_is-array')});
1713},{"./_export":32,"./_is-array":39}],61:[function(_dereq_,module,exports){
1714'use strict';
1715var $export = _dereq_('./_export')
1716 , $reduce = _dereq_('./_array-reduce');
1717
1718$export($export.P + $export.F * !_dereq_('./_strict-method')([].reduce, true), 'Array', {
1719 // 22.1.3.18 / 15.4.4.21 Array.prototype.reduce(callbackfn [, initialValue])
1720 reduce: function reduce(callbackfn /* , initialValue */){
1721 return $reduce(this, callbackfn, arguments.length, arguments[1], false);
1722 }
1723});
1724},{"./_array-reduce":24,"./_export":32,"./_strict-method":51}],62:[function(_dereq_,module,exports){
1725// 19.1.3.1 Object.assign(target, source)
1726var $export = _dereq_('./_export');
1727
1728$export($export.S + $export.F, 'Object', {assign: _dereq_('./_object-assign')});
1729},{"./_export":32,"./_object-assign":41}],63:[function(_dereq_,module,exports){
1730// 19.1.2.14 Object.keys(O)
1731var toObject = _dereq_('./_to-object')
1732 , $keys = _dereq_('./_object-keys');
1733
1734_dereq_('./_object-sap')('keys', function(){
1735 return function keys(it){
1736 return $keys(toObject(it));
1737 };
1738});
1739},{"./_object-keys":45,"./_object-sap":47,"./_to-object":56}],64:[function(_dereq_,module,exports){
1740var pSlice = Array.prototype.slice;
1741var objectKeys = _dereq_('./lib/keys.js');
1742var isArguments = _dereq_('./lib/is_arguments.js');
1743
1744var deepEqual = module.exports = function (actual, expected, opts) {
1745 if (!opts) opts = {};
1746 // 7.1. All identical values are equivalent, as determined by ===.
1747 if (actual === expected) {
1748 return true;
1749
1750 } else if (actual instanceof Date && expected instanceof Date) {
1751 return actual.getTime() === expected.getTime();
1752
1753 // 7.3. Other pairs that do not both pass typeof value == 'object',
1754 // equivalence is determined by ==.
1755 } else if (!actual || !expected || typeof actual != 'object' && typeof expected != 'object') {
1756 return opts.strict ? actual === expected : actual == expected;
1757
1758 // 7.4. For all other Object pairs, including Array objects, equivalence is
1759 // determined by having the same number of owned properties (as verified
1760 // with Object.prototype.hasOwnProperty.call), the same set of keys
1761 // (although not necessarily the same order), equivalent values for every
1762 // corresponding key, and an identical 'prototype' property. Note: this
1763 // accounts for both named and indexed properties on Arrays.
1764 } else {
1765 return objEquiv(actual, expected, opts);
1766 }
1767}
1768
1769function isUndefinedOrNull(value) {
1770 return value === null || value === undefined;
1771}
1772
1773function isBuffer (x) {
1774 if (!x || typeof x !== 'object' || typeof x.length !== 'number') return false;
1775 if (typeof x.copy !== 'function' || typeof x.slice !== 'function') {
1776 return false;
1777 }
1778 if (x.length > 0 && typeof x[0] !== 'number') return false;
1779 return true;
1780}
1781
1782function objEquiv(a, b, opts) {
1783 var i, key;
1784 if (isUndefinedOrNull(a) || isUndefinedOrNull(b))
1785 return false;
1786 // an identical 'prototype' property.
1787 if (a.prototype !== b.prototype) return false;
1788 //~~~I've managed to break Object.keys through screwy arguments passing.
1789 // Converting to array solves the problem.
1790 if (isArguments(a)) {
1791 if (!isArguments(b)) {
1792 return false;
1793 }
1794 a = pSlice.call(a);
1795 b = pSlice.call(b);
1796 return deepEqual(a, b, opts);
1797 }
1798 if (isBuffer(a)) {
1799 if (!isBuffer(b)) {
1800 return false;
1801 }
1802 if (a.length !== b.length) return false;
1803 for (i = 0; i < a.length; i++) {
1804 if (a[i] !== b[i]) return false;
1805 }
1806 return true;
1807 }
1808 try {
1809 var ka = objectKeys(a),
1810 kb = objectKeys(b);
1811 } catch (e) {//happens when one is a string literal and the other isn't
1812 return false;
1813 }
1814 // having the same number of owned properties (keys incorporates
1815 // hasOwnProperty)
1816 if (ka.length != kb.length)
1817 return false;
1818 //the same set of keys (although not necessarily the same order),
1819 ka.sort();
1820 kb.sort();
1821 //~~~cheap key test
1822 for (i = ka.length - 1; i >= 0; i--) {
1823 if (ka[i] != kb[i])
1824 return false;
1825 }
1826 //equivalent values for every corresponding key, and
1827 //~~~possibly expensive deep test
1828 for (i = ka.length - 1; i >= 0; i--) {
1829 key = ka[i];
1830 if (!deepEqual(a[key], b[key], opts)) return false;
1831 }
1832 return typeof a === typeof b;
1833}
1834
1835},{"./lib/is_arguments.js":65,"./lib/keys.js":66}],65:[function(_dereq_,module,exports){
1836var supportsArgumentsClass = (function(){
1837 return Object.prototype.toString.call(arguments)
1838})() == '[object Arguments]';
1839
1840exports = module.exports = supportsArgumentsClass ? supported : unsupported;
1841
1842exports.supported = supported;
1843function supported(object) {
1844 return Object.prototype.toString.call(object) == '[object Arguments]';
1845};
1846
1847exports.unsupported = unsupported;
1848function unsupported(object){
1849 return object &&
1850 typeof object == 'object' &&
1851 typeof object.length == 'number' &&
1852 Object.prototype.hasOwnProperty.call(object, 'callee') &&
1853 !Object.prototype.propertyIsEnumerable.call(object, 'callee') ||
1854 false;
1855};
1856
1857},{}],66:[function(_dereq_,module,exports){
1858exports = module.exports = typeof Object.keys === 'function'
1859 ? Object.keys : shim;
1860
1861exports.shim = shim;
1862function shim (obj) {
1863 var keys = [];
1864 for (var key in obj) keys.push(key);
1865 return keys;
1866}
1867
1868},{}],67:[function(_dereq_,module,exports){
1869/**
1870 * escallmatch:
1871 * ECMAScript CallExpression matcher made from function/method signature
1872 *
1873 * https://github.com/twada/escallmatch
1874 *
1875 * Copyright (c) 2014-2015 Takuto Wada
1876 * Licensed under the MIT license.
1877 * http://twada.mit-license.org/
1878 */
1879'use strict';
1880/* jshint -W024 */
1881
1882var esprima = _dereq_('esprima');
1883var estraverse = _dereq_('estraverse');
1884var espurify = _dereq_('espurify');
1885var syntax = estraverse.Syntax;
1886var hasOwn = Object.prototype.hasOwnProperty;
1887var forEach = _dereq_('array-foreach');
1888var map = _dereq_('array-map');
1889var filter = _dereq_('array-filter');
1890var reduce = _dereq_('array-reduce');
1891var indexOf = _dereq_('indexof');
1892var deepEqual = _dereq_('deep-equal');
1893var notCallExprMessage = 'Argument should be in the form of CallExpression';
1894var duplicatedArgMessage = 'Duplicate argument name: ';
1895var invalidFormMessage = 'Argument should be in the form of `name` or `[name]`';
1896
1897function createMatcher (signatureStr, options) {
1898 var ast = extractExpressionFrom(esprima.parse(signatureStr));
1899 return new Matcher(ast, options || {});
1900}
1901
1902function Matcher (signatureAst, options) {
1903 this.visitorKeys = options.visitorKeys || estraverse.VisitorKeys;
1904 this.signatureAst = signatureAst;
1905 this.signatureCalleeDepth = astDepth(signatureAst.callee, this.visitorKeys);
1906 this.numMaxArgs = this.signatureAst.arguments.length;
1907 this.numMinArgs = filter(this.signatureAst.arguments, identifiers).length;
1908}
1909
1910Matcher.prototype.test = function (currentNode) {
1911 var calleeMatched = this.isCalleeMatched(currentNode);
1912 var numArgs;
1913 if (calleeMatched) {
1914 numArgs = currentNode.arguments.length;
1915 return this.numMinArgs <= numArgs && numArgs <= this.numMaxArgs;
1916 }
1917 return false;
1918};
1919
1920Matcher.prototype.matchArgument = function (currentNode, parentNode) {
1921 if (isCalleeOfParent(currentNode, parentNode)) {
1922 return null;
1923 }
1924 if (this.test(parentNode)) {
1925 var indexOfCurrentArg = indexOf(parentNode.arguments, currentNode);
1926 var numOptional = parentNode.arguments.length - this.numMinArgs;
1927 var matchedSignatures = reduce(this.argumentSignatures(), function (accum, argSig) {
1928 if (argSig.kind === 'mandatory') {
1929 accum.push(argSig);
1930 }
1931 if (argSig.kind === 'optional' && 0 < numOptional) {
1932 numOptional -= 1;
1933 accum.push(argSig);
1934 }
1935 return accum;
1936 }, []);
1937 return matchedSignatures[indexOfCurrentArg];
1938 }
1939 return null;
1940};
1941
1942Matcher.prototype.calleeAst = function () {
1943 return espurify(this.signatureAst.callee);
1944};
1945
1946Matcher.prototype.argumentSignatures = function () {
1947 return map(this.signatureAst.arguments, toArgumentSignature);
1948};
1949
1950Matcher.prototype.isCalleeMatched = function (node) {
1951 if (!isCallExpression(node)) {
1952 return false;
1953 }
1954 if (!this.isSameDepthAsSignatureCallee(node.callee)) {
1955 return false;
1956 }
1957 return deepEqual(espurify(this.signatureAst.callee), espurify(node.callee));
1958};
1959
1960Matcher.prototype.isSameDepthAsSignatureCallee = function (ast) {
1961 var depth = this.signatureCalleeDepth;
1962 var currentDepth = 0;
1963 estraverse.traverse(ast, {
1964 keys: this.visitorKeys,
1965 enter: function (currentNode, parentNode) {
1966 var path = this.path();
1967 var pathDepth = path ? path.length : 0;
1968 if (currentDepth < pathDepth) {
1969 currentDepth = pathDepth;
1970 }
1971 if (depth < currentDepth) {
1972 this['break']();
1973 }
1974 }
1975 });
1976 return (depth === currentDepth);
1977};
1978
1979function toArgumentSignature (argSignatureNode) {
1980 switch(argSignatureNode.type) {
1981 case syntax.Identifier:
1982 return {
1983 name: argSignatureNode.name,
1984 kind: 'mandatory'
1985 };
1986 case syntax.ArrayExpression:
1987 return {
1988 name: argSignatureNode.elements[0].name,
1989 kind: 'optional'
1990 };
1991 default:
1992 return null;
1993 }
1994}
1995
1996function astDepth (ast, visitorKeys) {
1997 var maxDepth = 0;
1998 estraverse.traverse(ast, {
1999 keys: visitorKeys,
2000 enter: function (currentNode, parentNode) {
2001 var path = this.path();
2002 var pathDepth = path ? path.length : 0;
2003 if (maxDepth < pathDepth) {
2004 maxDepth = pathDepth;
2005 }
2006 }
2007 });
2008 return maxDepth;
2009}
2010
2011function isCallExpression (node) {
2012 return node && node.type === syntax.CallExpression;
2013}
2014
2015function isCalleeOfParent(currentNode, parentNode) {
2016 return parentNode && currentNode &&
2017 parentNode.type === syntax.CallExpression &&
2018 parentNode.callee === currentNode;
2019}
2020
2021function identifiers (node) {
2022 return node.type === syntax.Identifier;
2023}
2024
2025function validateApiExpression (callExpression) {
2026 if (callExpression.type !== syntax.CallExpression) {
2027 throw new Error(notCallExprMessage);
2028 }
2029 var names = {};
2030 forEach(callExpression.arguments, function (arg) {
2031 var name = validateArg(arg);
2032 if (hasOwn.call(names, name)) {
2033 throw new Error(duplicatedArgMessage + name);
2034 } else {
2035 names[name] = name;
2036 }
2037 });
2038}
2039
2040function validateArg (arg) {
2041 var inner;
2042 switch(arg.type) {
2043 case syntax.Identifier:
2044 return arg.name;
2045 case syntax.ArrayExpression:
2046 if (arg.elements.length !== 1) {
2047 throw new Error(invalidFormMessage);
2048 }
2049 inner = arg.elements[0];
2050 if (inner.type !== syntax.Identifier) {
2051 throw new Error(invalidFormMessage);
2052 }
2053 return inner.name;
2054 default:
2055 throw new Error(invalidFormMessage);
2056 }
2057}
2058
2059function extractExpressionFrom (tree) {
2060 var statement, expression;
2061 statement = tree.body[0];
2062 if (statement.type !== syntax.ExpressionStatement) {
2063 throw new Error(notCallExprMessage);
2064 }
2065 expression = statement.expression;
2066 validateApiExpression(expression);
2067 return expression;
2068}
2069
2070module.exports = createMatcher;
2071
2072},{"array-filter":11,"array-foreach":13,"array-map":14,"array-reduce":15,"deep-equal":64,"esprima":86,"espurify":87,"estraverse":91,"indexof":97}],68:[function(_dereq_,module,exports){
2073(function (global){
2074/*
2075 Copyright (C) 2012-2014 Yusuke Suzuki <utatane.tea@gmail.com>
2076 Copyright (C) 2015 Ingvar Stepanyan <me@rreverser.com>
2077 Copyright (C) 2014 Ivan Nikulin <ifaaan@gmail.com>
2078 Copyright (C) 2012-2013 Michael Ficarra <escodegen.copyright@michael.ficarra.me>
2079 Copyright (C) 2012-2013 Mathias Bynens <mathias@qiwi.be>
2080 Copyright (C) 2013 Irakli Gozalishvili <rfobic@gmail.com>
2081 Copyright (C) 2012 Robert Gust-Bardon <donate@robert.gust-bardon.org>
2082 Copyright (C) 2012 John Freeman <jfreeman08@gmail.com>
2083 Copyright (C) 2011-2012 Ariya Hidayat <ariya.hidayat@gmail.com>
2084 Copyright (C) 2012 Joost-Wim Boekesteijn <joost-wim@boekesteijn.nl>
2085 Copyright (C) 2012 Kris Kowal <kris.kowal@cixar.com>
2086 Copyright (C) 2012 Arpad Borsos <arpad.borsos@googlemail.com>
2087
2088 Redistribution and use in source and binary forms, with or without
2089 modification, are permitted provided that the following conditions are met:
2090
2091 * Redistributions of source code must retain the above copyright
2092 notice, this list of conditions and the following disclaimer.
2093 * Redistributions in binary form must reproduce the above copyright
2094 notice, this list of conditions and the following disclaimer in the
2095 documentation and/or other materials provided with the distribution.
2096
2097 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
2098 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
2099 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
2100 ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
2101 DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
2102 (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
2103 LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
2104 ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
2105 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
2106 THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
2107*/
2108
2109/*global exports:true, require:true, global:true*/
2110(function () {
2111 'use strict';
2112
2113 var Syntax,
2114 Precedence,
2115 BinaryPrecedence,
2116 SourceNode,
2117 estraverse,
2118 esutils,
2119 isArray,
2120 base,
2121 indent,
2122 json,
2123 renumber,
2124 hexadecimal,
2125 quotes,
2126 escapeless,
2127 newline,
2128 space,
2129 parentheses,
2130 semicolons,
2131 safeConcatenation,
2132 directive,
2133 extra,
2134 parse,
2135 sourceMap,
2136 sourceCode,
2137 preserveBlankLines,
2138 FORMAT_MINIFY,
2139 FORMAT_DEFAULTS;
2140
2141 estraverse = _dereq_('estraverse');
2142 esutils = _dereq_('esutils');
2143
2144 Syntax = estraverse.Syntax;
2145
2146 // Generation is done by generateExpression.
2147 function isExpression(node) {
2148 return CodeGenerator.Expression.hasOwnProperty(node.type);
2149 }
2150
2151 // Generation is done by generateStatement.
2152 function isStatement(node) {
2153 return CodeGenerator.Statement.hasOwnProperty(node.type);
2154 }
2155
2156 Precedence = {
2157 Sequence: 0,
2158 Yield: 1,
2159 Await: 1,
2160 Assignment: 1,
2161 Conditional: 2,
2162 ArrowFunction: 2,
2163 LogicalOR: 3,
2164 LogicalAND: 4,
2165 BitwiseOR: 5,
2166 BitwiseXOR: 6,
2167 BitwiseAND: 7,
2168 Equality: 8,
2169 Relational: 9,
2170 BitwiseSHIFT: 10,
2171 Additive: 11,
2172 Multiplicative: 12,
2173 Unary: 13,
2174 Postfix: 14,
2175 Call: 15,
2176 New: 16,
2177 TaggedTemplate: 17,
2178 Member: 18,
2179 Primary: 19
2180 };
2181
2182 BinaryPrecedence = {
2183 '||': Precedence.LogicalOR,
2184 '&&': Precedence.LogicalAND,
2185 '|': Precedence.BitwiseOR,
2186 '^': Precedence.BitwiseXOR,
2187 '&': Precedence.BitwiseAND,
2188 '==': Precedence.Equality,
2189 '!=': Precedence.Equality,
2190 '===': Precedence.Equality,
2191 '!==': Precedence.Equality,
2192 'is': Precedence.Equality,
2193 'isnt': Precedence.Equality,
2194 '<': Precedence.Relational,
2195 '>': Precedence.Relational,
2196 '<=': Precedence.Relational,
2197 '>=': Precedence.Relational,
2198 'in': Precedence.Relational,
2199 'instanceof': Precedence.Relational,
2200 '<<': Precedence.BitwiseSHIFT,
2201 '>>': Precedence.BitwiseSHIFT,
2202 '>>>': Precedence.BitwiseSHIFT,
2203 '+': Precedence.Additive,
2204 '-': Precedence.Additive,
2205 '*': Precedence.Multiplicative,
2206 '%': Precedence.Multiplicative,
2207 '/': Precedence.Multiplicative
2208 };
2209
2210 //Flags
2211 var F_ALLOW_IN = 1,
2212 F_ALLOW_CALL = 1 << 1,
2213 F_ALLOW_UNPARATH_NEW = 1 << 2,
2214 F_FUNC_BODY = 1 << 3,
2215 F_DIRECTIVE_CTX = 1 << 4,
2216 F_SEMICOLON_OPT = 1 << 5;
2217
2218 //Expression flag sets
2219 //NOTE: Flag order:
2220 // F_ALLOW_IN
2221 // F_ALLOW_CALL
2222 // F_ALLOW_UNPARATH_NEW
2223 var E_FTT = F_ALLOW_CALL | F_ALLOW_UNPARATH_NEW,
2224 E_TTF = F_ALLOW_IN | F_ALLOW_CALL,
2225 E_TTT = F_ALLOW_IN | F_ALLOW_CALL | F_ALLOW_UNPARATH_NEW,
2226 E_TFF = F_ALLOW_IN,
2227 E_FFT = F_ALLOW_UNPARATH_NEW,
2228 E_TFT = F_ALLOW_IN | F_ALLOW_UNPARATH_NEW;
2229
2230 //Statement flag sets
2231 //NOTE: Flag order:
2232 // F_ALLOW_IN
2233 // F_FUNC_BODY
2234 // F_DIRECTIVE_CTX
2235 // F_SEMICOLON_OPT
2236 var S_TFFF = F_ALLOW_IN,
2237 S_TFFT = F_ALLOW_IN | F_SEMICOLON_OPT,
2238 S_FFFF = 0x00,
2239 S_TFTF = F_ALLOW_IN | F_DIRECTIVE_CTX,
2240 S_TTFF = F_ALLOW_IN | F_FUNC_BODY;
2241
2242 function getDefaultOptions() {
2243 // default options
2244 return {
2245 indent: null,
2246 base: null,
2247 parse: null,
2248 comment: false,
2249 format: {
2250 indent: {
2251 style: ' ',
2252 base: 0,
2253 adjustMultilineComment: false
2254 },
2255 newline: '\n',
2256 space: ' ',
2257 json: false,
2258 renumber: false,
2259 hexadecimal: false,
2260 quotes: 'single',
2261 escapeless: false,
2262 compact: false,
2263 parentheses: true,
2264 semicolons: true,
2265 safeConcatenation: false,
2266 preserveBlankLines: false
2267 },
2268 moz: {
2269 comprehensionExpressionStartsWithAssignment: false,
2270 starlessGenerator: false
2271 },
2272 sourceMap: null,
2273 sourceMapRoot: null,
2274 sourceMapWithCode: false,
2275 directive: false,
2276 raw: true,
2277 verbatim: null,
2278 sourceCode: null
2279 };
2280 }
2281
2282 function stringRepeat(str, num) {
2283 var result = '';
2284
2285 for (num |= 0; num > 0; num >>>= 1, str += str) {
2286 if (num & 1) {
2287 result += str;
2288 }
2289 }
2290
2291 return result;
2292 }
2293
2294 isArray = Array.isArray;
2295 if (!isArray) {
2296 isArray = function isArray(array) {
2297 return Object.prototype.toString.call(array) === '[object Array]';
2298 };
2299 }
2300
2301 function hasLineTerminator(str) {
2302 return (/[\r\n]/g).test(str);
2303 }
2304
2305 function endsWithLineTerminator(str) {
2306 var len = str.length;
2307 return len && esutils.code.isLineTerminator(str.charCodeAt(len - 1));
2308 }
2309
2310 function merge(target, override) {
2311 var key;
2312 for (key in override) {
2313 if (override.hasOwnProperty(key)) {
2314 target[key] = override[key];
2315 }
2316 }
2317 return target;
2318 }
2319
2320 function updateDeeply(target, override) {
2321 var key, val;
2322
2323 function isHashObject(target) {
2324 return typeof target === 'object' && target instanceof Object && !(target instanceof RegExp);
2325 }
2326
2327 for (key in override) {
2328 if (override.hasOwnProperty(key)) {
2329 val = override[key];
2330 if (isHashObject(val)) {
2331 if (isHashObject(target[key])) {
2332 updateDeeply(target[key], val);
2333 } else {
2334 target[key] = updateDeeply({}, val);
2335 }
2336 } else {
2337 target[key] = val;
2338 }
2339 }
2340 }
2341 return target;
2342 }
2343
2344 function generateNumber(value) {
2345 var result, point, temp, exponent, pos;
2346
2347 if (value !== value) {
2348 throw new Error('Numeric literal whose value is NaN');
2349 }
2350 if (value < 0 || (value === 0 && 1 / value < 0)) {
2351 throw new Error('Numeric literal whose value is negative');
2352 }
2353
2354 if (value === 1 / 0) {
2355 return json ? 'null' : renumber ? '1e400' : '1e+400';
2356 }
2357
2358 result = '' + value;
2359 if (!renumber || result.length < 3) {
2360 return result;
2361 }
2362
2363 point = result.indexOf('.');
2364 if (!json && result.charCodeAt(0) === 0x30 /* 0 */ && point === 1) {
2365 point = 0;
2366 result = result.slice(1);
2367 }
2368 temp = result;
2369 result = result.replace('e+', 'e');
2370 exponent = 0;
2371 if ((pos = temp.indexOf('e')) > 0) {
2372 exponent = +temp.slice(pos + 1);
2373 temp = temp.slice(0, pos);
2374 }
2375 if (point >= 0) {
2376 exponent -= temp.length - point - 1;
2377 temp = +(temp.slice(0, point) + temp.slice(point + 1)) + '';
2378 }
2379 pos = 0;
2380 while (temp.charCodeAt(temp.length + pos - 1) === 0x30 /* 0 */) {
2381 --pos;
2382 }
2383 if (pos !== 0) {
2384 exponent -= pos;
2385 temp = temp.slice(0, pos);
2386 }
2387 if (exponent !== 0) {
2388 temp += 'e' + exponent;
2389 }
2390 if ((temp.length < result.length ||
2391 (hexadecimal && value > 1e12 && Math.floor(value) === value && (temp = '0x' + value.toString(16)).length < result.length)) &&
2392 +temp === value) {
2393 result = temp;
2394 }
2395
2396 return result;
2397 }
2398
2399 // Generate valid RegExp expression.
2400 // This function is based on https://github.com/Constellation/iv Engine
2401
2402 function escapeRegExpCharacter(ch, previousIsBackslash) {
2403 // not handling '\' and handling \u2028 or \u2029 to unicode escape sequence
2404 if ((ch & ~1) === 0x2028) {
2405 return (previousIsBackslash ? 'u' : '\\u') + ((ch === 0x2028) ? '2028' : '2029');
2406 } else if (ch === 10 || ch === 13) { // \n, \r
2407 return (previousIsBackslash ? '' : '\\') + ((ch === 10) ? 'n' : 'r');
2408 }
2409 return String.fromCharCode(ch);
2410 }
2411
2412 function generateRegExp(reg) {
2413 var match, result, flags, i, iz, ch, characterInBrack, previousIsBackslash;
2414
2415 result = reg.toString();
2416
2417 if (reg.source) {
2418 // extract flag from toString result
2419 match = result.match(/\/([^/]*)$/);
2420 if (!match) {
2421 return result;
2422 }
2423
2424 flags = match[1];
2425 result = '';
2426
2427 characterInBrack = false;
2428 previousIsBackslash = false;
2429 for (i = 0, iz = reg.source.length; i < iz; ++i) {
2430 ch = reg.source.charCodeAt(i);
2431
2432 if (!previousIsBackslash) {
2433 if (characterInBrack) {
2434 if (ch === 93) { // ]
2435 characterInBrack = false;
2436 }
2437 } else {
2438 if (ch === 47) { // /
2439 result += '\\';
2440 } else if (ch === 91) { // [
2441 characterInBrack = true;
2442 }
2443 }
2444 result += escapeRegExpCharacter(ch, previousIsBackslash);
2445 previousIsBackslash = ch === 92; // \
2446 } else {
2447 // if new RegExp("\\\n') is provided, create /\n/
2448 result += escapeRegExpCharacter(ch, previousIsBackslash);
2449 // prevent like /\\[/]/
2450 previousIsBackslash = false;
2451 }
2452 }
2453
2454 return '/' + result + '/' + flags;
2455 }
2456
2457 return result;
2458 }
2459
2460 function escapeAllowedCharacter(code, next) {
2461 var hex;
2462
2463 if (code === 0x08 /* \b */) {
2464 return '\\b';
2465 }
2466
2467 if (code === 0x0C /* \f */) {
2468 return '\\f';
2469 }
2470
2471 if (code === 0x09 /* \t */) {
2472 return '\\t';
2473 }
2474
2475 hex = code.toString(16).toUpperCase();
2476 if (json || code > 0xFF) {
2477 return '\\u' + '0000'.slice(hex.length) + hex;
2478 } else if (code === 0x0000 && !esutils.code.isDecimalDigit(next)) {
2479 return '\\0';
2480 } else if (code === 0x000B /* \v */) { // '\v'
2481 return '\\x0B';
2482 } else {
2483 return '\\x' + '00'.slice(hex.length) + hex;
2484 }
2485 }
2486
2487 function escapeDisallowedCharacter(code) {
2488 if (code === 0x5C /* \ */) {
2489 return '\\\\';
2490 }
2491
2492 if (code === 0x0A /* \n */) {
2493 return '\\n';
2494 }
2495
2496 if (code === 0x0D /* \r */) {
2497 return '\\r';
2498 }
2499
2500 if (code === 0x2028) {
2501 return '\\u2028';
2502 }
2503
2504 if (code === 0x2029) {
2505 return '\\u2029';
2506 }
2507
2508 throw new Error('Incorrectly classified character');
2509 }
2510
2511 function escapeDirective(str) {
2512 var i, iz, code, quote;
2513
2514 quote = quotes === 'double' ? '"' : '\'';
2515 for (i = 0, iz = str.length; i < iz; ++i) {
2516 code = str.charCodeAt(i);
2517 if (code === 0x27 /* ' */) {
2518 quote = '"';
2519 break;
2520 } else if (code === 0x22 /* " */) {
2521 quote = '\'';
2522 break;
2523 } else if (code === 0x5C /* \ */) {
2524 ++i;
2525 }
2526 }
2527
2528 return quote + str + quote;
2529 }
2530
2531 function escapeString(str) {
2532 var result = '', i, len, code, singleQuotes = 0, doubleQuotes = 0, single, quote;
2533
2534 for (i = 0, len = str.length; i < len; ++i) {
2535 code = str.charCodeAt(i);
2536 if (code === 0x27 /* ' */) {
2537 ++singleQuotes;
2538 } else if (code === 0x22 /* " */) {
2539 ++doubleQuotes;
2540 } else if (code === 0x2F /* / */ && json) {
2541 result += '\\';
2542 } else if (esutils.code.isLineTerminator(code) || code === 0x5C /* \ */) {
2543 result += escapeDisallowedCharacter(code);
2544 continue;
2545 } else if (!esutils.code.isIdentifierPartES5(code) && (json && code < 0x20 /* SP */ || !json && !escapeless && ((code < 0x20 /* SP */ || code > 0x7E) /* ~ */))) {
2546 result += escapeAllowedCharacter(code, str.charCodeAt(i + 1));
2547 continue;
2548 }
2549 result += String.fromCharCode(code);
2550 }
2551
2552 single = !(quotes === 'double' || (quotes === 'auto' && doubleQuotes < singleQuotes));
2553 quote = single ? '\'' : '"';
2554
2555 if (!(single ? singleQuotes : doubleQuotes)) {
2556 return quote + result + quote;
2557 }
2558
2559 str = result;
2560 result = quote;
2561
2562 for (i = 0, len = str.length; i < len; ++i) {
2563 code = str.charCodeAt(i);
2564 if ((code === 0x27 /* ' */ && single) || (code === 0x22 /* " */ && !single)) {
2565 result += '\\';
2566 }
2567 result += String.fromCharCode(code);
2568 }
2569
2570 return result + quote;
2571 }
2572
2573 /**
2574 * flatten an array to a string, where the array can contain
2575 * either strings or nested arrays
2576 */
2577 function flattenToString(arr) {
2578 var i, iz, elem, result = '';
2579 for (i = 0, iz = arr.length; i < iz; ++i) {
2580 elem = arr[i];
2581 result += isArray(elem) ? flattenToString(elem) : elem;
2582 }
2583 return result;
2584 }
2585
2586 /**
2587 * convert generated to a SourceNode when source maps are enabled.
2588 */
2589 function toSourceNodeWhenNeeded(generated, node) {
2590 if (!sourceMap) {
2591 // with no source maps, generated is either an
2592 // array or a string. if an array, flatten it.
2593 // if a string, just return it
2594 if (isArray(generated)) {
2595 return flattenToString(generated);
2596 } else {
2597 return generated;
2598 }
2599 }
2600 if (node == null) {
2601 if (generated instanceof SourceNode) {
2602 return generated;
2603 } else {
2604 node = {};
2605 }
2606 }
2607 if (node.loc == null) {
2608 return new SourceNode(null, null, sourceMap, generated, node.name || null);
2609 }
2610 return new SourceNode(node.loc.start.line, node.loc.start.column, (sourceMap === true ? node.loc.source || null : sourceMap), generated, node.name || null);
2611 }
2612
2613 function noEmptySpace() {
2614 return (space) ? space : ' ';
2615 }
2616
2617 function join(left, right) {
2618 var leftSource,
2619 rightSource,
2620 leftCharCode,
2621 rightCharCode;
2622
2623 leftSource = toSourceNodeWhenNeeded(left).toString();
2624 if (leftSource.length === 0) {
2625 return [right];
2626 }
2627
2628 rightSource = toSourceNodeWhenNeeded(right).toString();
2629 if (rightSource.length === 0) {
2630 return [left];
2631 }
2632
2633 leftCharCode = leftSource.charCodeAt(leftSource.length - 1);
2634 rightCharCode = rightSource.charCodeAt(0);
2635
2636 if (((leftCharCode === 0x2B /* + */ || leftCharCode === 0x2D) /* - */) && leftCharCode === rightCharCode ||
2637 esutils.code.isIdentifierPartES5(leftCharCode) && esutils.code.isIdentifierPartES5(rightCharCode) ||
2638 leftCharCode === 0x2F /* / */ && rightCharCode === 0x69 /* i */) { // infix word operators all start with `i`
2639 return [left, noEmptySpace(), right];
2640 } else if (esutils.code.isWhiteSpace(leftCharCode) || esutils.code.isLineTerminator(leftCharCode) ||
2641 esutils.code.isWhiteSpace(rightCharCode) || esutils.code.isLineTerminator(rightCharCode)) {
2642 return [left, right];
2643 }
2644 return [left, space, right];
2645 }
2646
2647 function addIndent(stmt) {
2648 return [base, stmt];
2649 }
2650
2651 function withIndent(fn) {
2652 var previousBase;
2653 previousBase = base;
2654 base += indent;
2655 fn(base);
2656 base = previousBase;
2657 }
2658
2659 function calculateSpaces(str) {
2660 var i;
2661 for (i = str.length - 1; i >= 0; --i) {
2662 if (esutils.code.isLineTerminator(str.charCodeAt(i))) {
2663 break;
2664 }
2665 }
2666 return (str.length - 1) - i;
2667 }
2668
2669 function adjustMultilineComment(value, specialBase) {
2670 var array, i, len, line, j, spaces, previousBase, sn;
2671
2672 array = value.split(/\r\n|[\r\n]/);
2673 spaces = Number.MAX_VALUE;
2674
2675 // first line doesn't have indentation
2676 for (i = 1, len = array.length; i < len; ++i) {
2677 line = array[i];
2678 j = 0;
2679 while (j < line.length && esutils.code.isWhiteSpace(line.charCodeAt(j))) {
2680 ++j;
2681 }
2682 if (spaces > j) {
2683 spaces = j;
2684 }
2685 }
2686
2687 if (typeof specialBase !== 'undefined') {
2688 // pattern like
2689 // {
2690 // var t = 20; /*
2691 // * this is comment
2692 // */
2693 // }
2694 previousBase = base;
2695 if (array[1][spaces] === '*') {
2696 specialBase += ' ';
2697 }
2698 base = specialBase;
2699 } else {
2700 if (spaces & 1) {
2701 // /*
2702 // *
2703 // */
2704 // If spaces are odd number, above pattern is considered.
2705 // We waste 1 space.
2706 --spaces;
2707 }
2708 previousBase = base;
2709 }
2710
2711 for (i = 1, len = array.length; i < len; ++i) {
2712 sn = toSourceNodeWhenNeeded(addIndent(array[i].slice(spaces)));
2713 array[i] = sourceMap ? sn.join('') : sn;
2714 }
2715
2716 base = previousBase;
2717
2718 return array.join('\n');
2719 }
2720
2721 function generateComment(comment, specialBase) {
2722 if (comment.type === 'Line') {
2723 if (endsWithLineTerminator(comment.value)) {
2724 return '//' + comment.value;
2725 } else {
2726 // Always use LineTerminator
2727 var result = '//' + comment.value;
2728 if (!preserveBlankLines) {
2729 result += '\n';
2730 }
2731 return result;
2732 }
2733 }
2734 if (extra.format.indent.adjustMultilineComment && /[\n\r]/.test(comment.value)) {
2735 return adjustMultilineComment('/*' + comment.value + '*/', specialBase);
2736 }
2737 return '/*' + comment.value + '*/';
2738 }
2739
2740 function addComments(stmt, result) {
2741 var i, len, comment, save, tailingToStatement, specialBase, fragment,
2742 extRange, range, prevRange, prefix, infix, suffix, count;
2743
2744 if (stmt.leadingComments && stmt.leadingComments.length > 0) {
2745 save = result;
2746
2747 if (preserveBlankLines) {
2748 comment = stmt.leadingComments[0];
2749 result = [];
2750
2751 extRange = comment.extendedRange;
2752 range = comment.range;
2753
2754 prefix = sourceCode.substring(extRange[0], range[0]);
2755 count = (prefix.match(/\n/g) || []).length;
2756 if (count > 0) {
2757 result.push(stringRepeat('\n', count));
2758 result.push(addIndent(generateComment(comment)));
2759 } else {
2760 result.push(prefix);
2761 result.push(generateComment(comment));
2762 }
2763
2764 prevRange = range;
2765
2766 for (i = 1, len = stmt.leadingComments.length; i < len; i++) {
2767 comment = stmt.leadingComments[i];
2768 range = comment.range;
2769
2770 infix = sourceCode.substring(prevRange[1], range[0]);
2771 count = (infix.match(/\n/g) || []).length;
2772 result.push(stringRepeat('\n', count));
2773 result.push(addIndent(generateComment(comment)));
2774
2775 prevRange = range;
2776 }
2777
2778 suffix = sourceCode.substring(range[1], extRange[1]);
2779 count = (suffix.match(/\n/g) || []).length;
2780 result.push(stringRepeat('\n', count));
2781 } else {
2782 comment = stmt.leadingComments[0];
2783 result = [];
2784 if (safeConcatenation && stmt.type === Syntax.Program && stmt.body.length === 0) {
2785 result.push('\n');
2786 }
2787 result.push(generateComment(comment));
2788 if (!endsWithLineTerminator(toSourceNodeWhenNeeded(result).toString())) {
2789 result.push('\n');
2790 }
2791
2792 for (i = 1, len = stmt.leadingComments.length; i < len; ++i) {
2793 comment = stmt.leadingComments[i];
2794 fragment = [generateComment(comment)];
2795 if (!endsWithLineTerminator(toSourceNodeWhenNeeded(fragment).toString())) {
2796 fragment.push('\n');
2797 }
2798 result.push(addIndent(fragment));
2799 }
2800 }
2801
2802 result.push(addIndent(save));
2803 }
2804
2805 if (stmt.trailingComments) {
2806
2807 if (preserveBlankLines) {
2808 comment = stmt.trailingComments[0];
2809 extRange = comment.extendedRange;
2810 range = comment.range;
2811
2812 prefix = sourceCode.substring(extRange[0], range[0]);
2813 count = (prefix.match(/\n/g) || []).length;
2814
2815 if (count > 0) {
2816 result.push(stringRepeat('\n', count));
2817 result.push(addIndent(generateComment(comment)));
2818 } else {
2819 result.push(prefix);
2820 result.push(generateComment(comment));
2821 }
2822 } else {
2823 tailingToStatement = !endsWithLineTerminator(toSourceNodeWhenNeeded(result).toString());
2824 specialBase = stringRepeat(' ', calculateSpaces(toSourceNodeWhenNeeded([base, result, indent]).toString()));
2825 for (i = 0, len = stmt.trailingComments.length; i < len; ++i) {
2826 comment = stmt.trailingComments[i];
2827 if (tailingToStatement) {
2828 // We assume target like following script
2829 //
2830 // var t = 20; /**
2831 // * This is comment of t
2832 // */
2833 if (i === 0) {
2834 // first case
2835 result = [result, indent];
2836 } else {
2837 result = [result, specialBase];
2838 }
2839 result.push(generateComment(comment, specialBase));
2840 } else {
2841 result = [result, addIndent(generateComment(comment))];
2842 }
2843 if (i !== len - 1 && !endsWithLineTerminator(toSourceNodeWhenNeeded(result).toString())) {
2844 result = [result, '\n'];
2845 }
2846 }
2847 }
2848 }
2849
2850 return result;
2851 }
2852
2853 function generateBlankLines(start, end, result) {
2854 var j, newlineCount = 0;
2855
2856 for (j = start; j < end; j++) {
2857 if (sourceCode[j] === '\n') {
2858 newlineCount++;
2859 }
2860 }
2861
2862 for (j = 1; j < newlineCount; j++) {
2863 result.push(newline);
2864 }
2865 }
2866
2867 function parenthesize(text, current, should) {
2868 if (current < should) {
2869 return ['(', text, ')'];
2870 }
2871 return text;
2872 }
2873
2874 function generateVerbatimString(string) {
2875 var i, iz, result;
2876 result = string.split(/\r\n|\n/);
2877 for (i = 1, iz = result.length; i < iz; i++) {
2878 result[i] = newline + base + result[i];
2879 }
2880 return result;
2881 }
2882
2883 function generateVerbatim(expr, precedence) {
2884 var verbatim, result, prec;
2885 verbatim = expr[extra.verbatim];
2886
2887 if (typeof verbatim === 'string') {
2888 result = parenthesize(generateVerbatimString(verbatim), Precedence.Sequence, precedence);
2889 } else {
2890 // verbatim is object
2891 result = generateVerbatimString(verbatim.content);
2892 prec = (verbatim.precedence != null) ? verbatim.precedence : Precedence.Sequence;
2893 result = parenthesize(result, prec, precedence);
2894 }
2895
2896 return toSourceNodeWhenNeeded(result, expr);
2897 }
2898
2899 function CodeGenerator() {
2900 }
2901
2902 // Helpers.
2903
2904 CodeGenerator.prototype.maybeBlock = function(stmt, flags) {
2905 var result, noLeadingComment, that = this;
2906
2907 noLeadingComment = !extra.comment || !stmt.leadingComments;
2908
2909 if (stmt.type === Syntax.BlockStatement && noLeadingComment) {
2910 return [space, this.generateStatement(stmt, flags)];
2911 }
2912
2913 if (stmt.type === Syntax.EmptyStatement && noLeadingComment) {
2914 return ';';
2915 }
2916
2917 withIndent(function () {
2918 result = [
2919 newline,
2920 addIndent(that.generateStatement(stmt, flags))
2921 ];
2922 });
2923
2924 return result;
2925 };
2926
2927 CodeGenerator.prototype.maybeBlockSuffix = function (stmt, result) {
2928 var ends = endsWithLineTerminator(toSourceNodeWhenNeeded(result).toString());
2929 if (stmt.type === Syntax.BlockStatement && (!extra.comment || !stmt.leadingComments) && !ends) {
2930 return [result, space];
2931 }
2932 if (ends) {
2933 return [result, base];
2934 }
2935 return [result, newline, base];
2936 };
2937
2938 function generateIdentifier(node) {
2939 return toSourceNodeWhenNeeded(node.name, node);
2940 }
2941
2942 function generateAsyncPrefix(node, spaceRequired) {
2943 return node.async ? 'async' + (spaceRequired ? noEmptySpace() : space) : '';
2944 }
2945
2946 function generateStarSuffix(node) {
2947 var isGenerator = node.generator && !extra.moz.starlessGenerator;
2948 return isGenerator ? '*' + space : '';
2949 }
2950
2951 function generateMethodPrefix(prop) {
2952 var func = prop.value;
2953 if (func.async) {
2954 return generateAsyncPrefix(func, !prop.computed);
2955 } else {
2956 // avoid space before method name
2957 return generateStarSuffix(func) ? '*' : '';
2958 }
2959 }
2960
2961 CodeGenerator.prototype.generatePattern = function (node, precedence, flags) {
2962 if (node.type === Syntax.Identifier) {
2963 return generateIdentifier(node);
2964 }
2965 return this.generateExpression(node, precedence, flags);
2966 };
2967
2968 CodeGenerator.prototype.generateFunctionParams = function (node) {
2969 var i, iz, result, hasDefault;
2970
2971 hasDefault = false;
2972
2973 if (node.type === Syntax.ArrowFunctionExpression &&
2974 !node.rest && (!node.defaults || node.defaults.length === 0) &&
2975 node.params.length === 1 && node.params[0].type === Syntax.Identifier) {
2976 // arg => { } case
2977 result = [generateAsyncPrefix(node, true), generateIdentifier(node.params[0])];
2978 } else {
2979 result = node.type === Syntax.ArrowFunctionExpression ? [generateAsyncPrefix(node, false)] : [];
2980 result.push('(');
2981 if (node.defaults) {
2982 hasDefault = true;
2983 }
2984 for (i = 0, iz = node.params.length; i < iz; ++i) {
2985 if (hasDefault && node.defaults[i]) {
2986 // Handle default values.
2987 result.push(this.generateAssignment(node.params[i], node.defaults[i], '=', Precedence.Assignment, E_TTT));
2988 } else {
2989 result.push(this.generatePattern(node.params[i], Precedence.Assignment, E_TTT));
2990 }
2991 if (i + 1 < iz) {
2992 result.push(',' + space);
2993 }
2994 }
2995
2996 if (node.rest) {
2997 if (node.params.length) {
2998 result.push(',' + space);
2999 }
3000 result.push('...');
3001 result.push(generateIdentifier(node.rest));
3002 }
3003
3004 result.push(')');
3005 }
3006
3007 return result;
3008 };
3009
3010 CodeGenerator.prototype.generateFunctionBody = function (node) {
3011 var result, expr;
3012
3013 result = this.generateFunctionParams(node);
3014
3015 if (node.type === Syntax.ArrowFunctionExpression) {
3016 result.push(space);
3017 result.push('=>');
3018 }
3019
3020 if (node.expression) {
3021 result.push(space);
3022 expr = this.generateExpression(node.body, Precedence.Assignment, E_TTT);
3023 if (expr.toString().charAt(0) === '{') {
3024 expr = ['(', expr, ')'];
3025 }
3026 result.push(expr);
3027 } else {
3028 result.push(this.maybeBlock(node.body, S_TTFF));
3029 }
3030
3031 return result;
3032 };
3033
3034 CodeGenerator.prototype.generateIterationForStatement = function (operator, stmt, flags) {
3035 var result = ['for' + space + '('], that = this;
3036 withIndent(function () {
3037 if (stmt.left.type === Syntax.VariableDeclaration) {
3038 withIndent(function () {
3039 result.push(stmt.left.kind + noEmptySpace());
3040 result.push(that.generateStatement(stmt.left.declarations[0], S_FFFF));
3041 });
3042 } else {
3043 result.push(that.generateExpression(stmt.left, Precedence.Call, E_TTT));
3044 }
3045
3046 result = join(result, operator);
3047 result = [join(
3048 result,
3049 that.generateExpression(stmt.right, Precedence.Sequence, E_TTT)
3050 ), ')'];
3051 });
3052 result.push(this.maybeBlock(stmt.body, flags));
3053 return result;
3054 };
3055
3056 CodeGenerator.prototype.generatePropertyKey = function (expr, computed) {
3057 var result = [];
3058
3059 if (computed) {
3060 result.push('[');
3061 }
3062
3063 result.push(this.generateExpression(expr, Precedence.Sequence, E_TTT));
3064 if (computed) {
3065 result.push(']');
3066 }
3067
3068 return result;
3069 };
3070
3071 CodeGenerator.prototype.generateAssignment = function (left, right, operator, precedence, flags) {
3072 if (Precedence.Assignment < precedence) {
3073 flags |= F_ALLOW_IN;
3074 }
3075
3076 return parenthesize(
3077 [
3078 this.generateExpression(left, Precedence.Call, flags),
3079 space + operator + space,
3080 this.generateExpression(right, Precedence.Assignment, flags)
3081 ],
3082 Precedence.Assignment,
3083 precedence
3084 );
3085 };
3086
3087 CodeGenerator.prototype.semicolon = function (flags) {
3088 if (!semicolons && flags & F_SEMICOLON_OPT) {
3089 return '';
3090 }
3091 return ';';
3092 };
3093
3094 // Statements.
3095
3096 CodeGenerator.Statement = {
3097
3098 BlockStatement: function (stmt, flags) {
3099 var range, content, result = ['{', newline], that = this;
3100
3101 withIndent(function () {
3102 // handle functions without any code
3103 if (stmt.body.length === 0 && preserveBlankLines) {
3104 range = stmt.range;
3105 if (range[1] - range[0] > 2) {
3106 content = sourceCode.substring(range[0] + 1, range[1] - 1);
3107 if (content[0] === '\n') {
3108 result = ['{'];
3109 }
3110 result.push(content);
3111 }
3112 }
3113
3114 var i, iz, fragment, bodyFlags;
3115 bodyFlags = S_TFFF;
3116 if (flags & F_FUNC_BODY) {
3117 bodyFlags |= F_DIRECTIVE_CTX;
3118 }
3119
3120 for (i = 0, iz = stmt.body.length; i < iz; ++i) {
3121 if (preserveBlankLines) {
3122 // handle spaces before the first line
3123 if (i === 0) {
3124 if (stmt.body[0].leadingComments) {
3125 range = stmt.body[0].leadingComments[0].extendedRange;
3126 content = sourceCode.substring(range[0], range[1]);
3127 if (content[0] === '\n') {
3128 result = ['{'];
3129 }
3130 }
3131 if (!stmt.body[0].leadingComments) {
3132 generateBlankLines(stmt.range[0], stmt.body[0].range[0], result);
3133 }
3134 }
3135
3136 // handle spaces between lines
3137 if (i > 0) {
3138 if (!stmt.body[i - 1].trailingComments && !stmt.body[i].leadingComments) {
3139 generateBlankLines(stmt.body[i - 1].range[1], stmt.body[i].range[0], result);
3140 }
3141 }
3142 }
3143
3144 if (i === iz - 1) {
3145 bodyFlags |= F_SEMICOLON_OPT;
3146 }
3147
3148 if (stmt.body[i].leadingComments && preserveBlankLines) {
3149 fragment = that.generateStatement(stmt.body[i], bodyFlags);
3150 } else {
3151 fragment = addIndent(that.generateStatement(stmt.body[i], bodyFlags));
3152 }
3153
3154 result.push(fragment);
3155 if (!endsWithLineTerminator(toSourceNodeWhenNeeded(fragment).toString())) {
3156 if (preserveBlankLines && i < iz - 1) {
3157 // don't add a new line if there are leading coments
3158 // in the next statement
3159 if (!stmt.body[i + 1].leadingComments) {
3160 result.push(newline);
3161 }
3162 } else {
3163 result.push(newline);
3164 }
3165 }
3166
3167 if (preserveBlankLines) {
3168 // handle spaces after the last line
3169 if (i === iz - 1) {
3170 if (!stmt.body[i].trailingComments) {
3171 generateBlankLines(stmt.body[i].range[1], stmt.range[1], result);
3172 }
3173 }
3174 }
3175 }
3176 });
3177
3178 result.push(addIndent('}'));
3179 return result;
3180 },
3181
3182 BreakStatement: function (stmt, flags) {
3183 if (stmt.label) {
3184 return 'break ' + stmt.label.name + this.semicolon(flags);
3185 }
3186 return 'break' + this.semicolon(flags);
3187 },
3188
3189 ContinueStatement: function (stmt, flags) {
3190 if (stmt.label) {
3191 return 'continue ' + stmt.label.name + this.semicolon(flags);
3192 }
3193 return 'continue' + this.semicolon(flags);
3194 },
3195
3196 ClassBody: function (stmt, flags) {
3197 var result = [ '{', newline], that = this;
3198
3199 withIndent(function (indent) {
3200 var i, iz;
3201
3202 for (i = 0, iz = stmt.body.length; i < iz; ++i) {
3203 result.push(indent);
3204 result.push(that.generateExpression(stmt.body[i], Precedence.Sequence, E_TTT));
3205 if (i + 1 < iz) {
3206 result.push(newline);
3207 }
3208 }
3209 });
3210
3211 if (!endsWithLineTerminator(toSourceNodeWhenNeeded(result).toString())) {
3212 result.push(newline);
3213 }
3214 result.push(base);
3215 result.push('}');
3216 return result;
3217 },
3218
3219 ClassDeclaration: function (stmt, flags) {
3220 var result, fragment;
3221 result = ['class ' + stmt.id.name];
3222 if (stmt.superClass) {
3223 fragment = join('extends', this.generateExpression(stmt.superClass, Precedence.Assignment, E_TTT));
3224 result = join(result, fragment);
3225 }
3226 result.push(space);
3227 result.push(this.generateStatement(stmt.body, S_TFFT));
3228 return result;
3229 },
3230
3231 DirectiveStatement: function (stmt, flags) {
3232 if (extra.raw && stmt.raw) {
3233 return stmt.raw + this.semicolon(flags);
3234 }
3235 return escapeDirective(stmt.directive) + this.semicolon(flags);
3236 },
3237
3238 DoWhileStatement: function (stmt, flags) {
3239 // Because `do 42 while (cond)` is Syntax Error. We need semicolon.
3240 var result = join('do', this.maybeBlock(stmt.body, S_TFFF));
3241 result = this.maybeBlockSuffix(stmt.body, result);
3242 return join(result, [
3243 'while' + space + '(',
3244 this.generateExpression(stmt.test, Precedence.Sequence, E_TTT),
3245 ')' + this.semicolon(flags)
3246 ]);
3247 },
3248
3249 CatchClause: function (stmt, flags) {
3250 var result, that = this;
3251 withIndent(function () {
3252 var guard;
3253
3254 result = [
3255 'catch' + space + '(',
3256 that.generateExpression(stmt.param, Precedence.Sequence, E_TTT),
3257 ')'
3258 ];
3259
3260 if (stmt.guard) {
3261 guard = that.generateExpression(stmt.guard, Precedence.Sequence, E_TTT);
3262 result.splice(2, 0, ' if ', guard);
3263 }
3264 });
3265 result.push(this.maybeBlock(stmt.body, S_TFFF));
3266 return result;
3267 },
3268
3269 DebuggerStatement: function (stmt, flags) {
3270 return 'debugger' + this.semicolon(flags);
3271 },
3272
3273 EmptyStatement: function (stmt, flags) {
3274 return ';';
3275 },
3276
3277 ExportDefaultDeclaration: function (stmt, flags) {
3278 var result = [ 'export' ], bodyFlags;
3279
3280 bodyFlags = (flags & F_SEMICOLON_OPT) ? S_TFFT : S_TFFF;
3281
3282 // export default HoistableDeclaration[Default]
3283 // export default AssignmentExpression[In] ;
3284 result = join(result, 'default');
3285 if (isStatement(stmt.declaration)) {
3286 result = join(result, this.generateStatement(stmt.declaration, bodyFlags));
3287 } else {
3288 result = join(result, this.generateExpression(stmt.declaration, Precedence.Assignment, E_TTT) + this.semicolon(flags));
3289 }
3290 return result;
3291 },
3292
3293 ExportNamedDeclaration: function (stmt, flags) {
3294 var result = [ 'export' ], bodyFlags, that = this;
3295
3296 bodyFlags = (flags & F_SEMICOLON_OPT) ? S_TFFT : S_TFFF;
3297
3298 // export VariableStatement
3299 // export Declaration[Default]
3300 if (stmt.declaration) {
3301 return join(result, this.generateStatement(stmt.declaration, bodyFlags));
3302 }
3303
3304 // export ExportClause[NoReference] FromClause ;
3305 // export ExportClause ;
3306 if (stmt.specifiers) {
3307 if (stmt.specifiers.length === 0) {
3308 result = join(result, '{' + space + '}');
3309 } else if (stmt.specifiers[0].type === Syntax.ExportBatchSpecifier) {
3310 result = join(result, this.generateExpression(stmt.specifiers[0], Precedence.Sequence, E_TTT));
3311 } else {
3312 result = join(result, '{');
3313 withIndent(function (indent) {
3314 var i, iz;
3315 result.push(newline);
3316 for (i = 0, iz = stmt.specifiers.length; i < iz; ++i) {
3317 result.push(indent);
3318 result.push(that.generateExpression(stmt.specifiers[i], Precedence.Sequence, E_TTT));
3319 if (i + 1 < iz) {
3320 result.push(',' + newline);
3321 }
3322 }
3323 });
3324 if (!endsWithLineTerminator(toSourceNodeWhenNeeded(result).toString())) {
3325 result.push(newline);
3326 }
3327 result.push(base + '}');
3328 }
3329
3330 if (stmt.source) {
3331 result = join(result, [
3332 'from' + space,
3333 // ModuleSpecifier
3334 this.generateExpression(stmt.source, Precedence.Sequence, E_TTT),
3335 this.semicolon(flags)
3336 ]);
3337 } else {
3338 result.push(this.semicolon(flags));
3339 }
3340 }
3341 return result;
3342 },
3343
3344 ExportAllDeclaration: function (stmt, flags) {
3345 // export * FromClause ;
3346 return [
3347 'export' + space,
3348 '*' + space,
3349 'from' + space,
3350 // ModuleSpecifier
3351 this.generateExpression(stmt.source, Precedence.Sequence, E_TTT),
3352 this.semicolon(flags)
3353 ];
3354 },
3355
3356 ExpressionStatement: function (stmt, flags) {
3357 var result, fragment;
3358
3359 function isClassPrefixed(fragment) {
3360 var code;
3361 if (fragment.slice(0, 5) !== 'class') {
3362 return false;
3363 }
3364 code = fragment.charCodeAt(5);
3365 return code === 0x7B /* '{' */ || esutils.code.isWhiteSpace(code) || esutils.code.isLineTerminator(code);
3366 }
3367
3368 function isFunctionPrefixed(fragment) {
3369 var code;
3370 if (fragment.slice(0, 8) !== 'function') {
3371 return false;
3372 }
3373 code = fragment.charCodeAt(8);
3374 return code === 0x28 /* '(' */ || esutils.code.isWhiteSpace(code) || code === 0x2A /* '*' */ || esutils.code.isLineTerminator(code);
3375 }
3376
3377 function isAsyncPrefixed(fragment) {
3378 var code, i, iz;
3379 if (fragment.slice(0, 5) !== 'async') {
3380 return false;
3381 }
3382 if (!esutils.code.isWhiteSpace(fragment.charCodeAt(5))) {
3383 return false;
3384 }
3385 for (i = 6, iz = fragment.length; i < iz; ++i) {
3386 if (!esutils.code.isWhiteSpace(fragment.charCodeAt(i))) {
3387 break;
3388 }
3389 }
3390 if (i === iz) {
3391 return false;
3392 }
3393 if (fragment.slice(i, i + 8) !== 'function') {
3394 return false;
3395 }
3396 code = fragment.charCodeAt(i + 8);
3397 return code === 0x28 /* '(' */ || esutils.code.isWhiteSpace(code) || code === 0x2A /* '*' */ || esutils.code.isLineTerminator(code);
3398 }
3399
3400 result = [this.generateExpression(stmt.expression, Precedence.Sequence, E_TTT)];
3401 // 12.4 '{', 'function', 'class' is not allowed in this position.
3402 // wrap expression with parentheses
3403 fragment = toSourceNodeWhenNeeded(result).toString();
3404 if (fragment.charCodeAt(0) === 0x7B /* '{' */ || // ObjectExpression
3405 isClassPrefixed(fragment) ||
3406 isFunctionPrefixed(fragment) ||
3407 isAsyncPrefixed(fragment) ||
3408 (directive && (flags & F_DIRECTIVE_CTX) && stmt.expression.type === Syntax.Literal && typeof stmt.expression.value === 'string')) {
3409 result = ['(', result, ')' + this.semicolon(flags)];
3410 } else {
3411 result.push(this.semicolon(flags));
3412 }
3413 return result;
3414 },
3415
3416 ImportDeclaration: function (stmt, flags) {
3417 // ES6: 15.2.1 valid import declarations:
3418 // - import ImportClause FromClause ;
3419 // - import ModuleSpecifier ;
3420 var result, cursor, that = this;
3421
3422 // If no ImportClause is present,
3423 // this should be `import ModuleSpecifier` so skip `from`
3424 // ModuleSpecifier is StringLiteral.
3425 if (stmt.specifiers.length === 0) {
3426 // import ModuleSpecifier ;
3427 return [
3428 'import',
3429 space,
3430 // ModuleSpecifier
3431 this.generateExpression(stmt.source, Precedence.Sequence, E_TTT),
3432 this.semicolon(flags)
3433 ];
3434 }
3435
3436 // import ImportClause FromClause ;
3437 result = [
3438 'import'
3439 ];
3440 cursor = 0;
3441
3442 // ImportedBinding
3443 if (stmt.specifiers[cursor].type === Syntax.ImportDefaultSpecifier) {
3444 result = join(result, [
3445 this.generateExpression(stmt.specifiers[cursor], Precedence.Sequence, E_TTT)
3446 ]);
3447 ++cursor;
3448 }
3449
3450 if (stmt.specifiers[cursor]) {
3451 if (cursor !== 0) {
3452 result.push(',');
3453 }
3454
3455 if (stmt.specifiers[cursor].type === Syntax.ImportNamespaceSpecifier) {
3456 // NameSpaceImport
3457 result = join(result, [
3458 space,
3459 this.generateExpression(stmt.specifiers[cursor], Precedence.Sequence, E_TTT)
3460 ]);
3461 } else {
3462 // NamedImports
3463 result.push(space + '{');
3464
3465 if ((stmt.specifiers.length - cursor) === 1) {
3466 // import { ... } from "...";
3467 result.push(space);
3468 result.push(this.generateExpression(stmt.specifiers[cursor], Precedence.Sequence, E_TTT));
3469 result.push(space + '}' + space);
3470 } else {
3471 // import {
3472 // ...,
3473 // ...,
3474 // } from "...";
3475 withIndent(function (indent) {
3476 var i, iz;
3477 result.push(newline);
3478 for (i = cursor, iz = stmt.specifiers.length; i < iz; ++i) {
3479 result.push(indent);
3480 result.push(that.generateExpression(stmt.specifiers[i], Precedence.Sequence, E_TTT));
3481 if (i + 1 < iz) {
3482 result.push(',' + newline);
3483 }
3484 }
3485 });
3486 if (!endsWithLineTerminator(toSourceNodeWhenNeeded(result).toString())) {
3487 result.push(newline);
3488 }
3489 result.push(base + '}' + space);
3490 }
3491 }
3492 }
3493
3494 result = join(result, [
3495 'from' + space,
3496 // ModuleSpecifier
3497 this.generateExpression(stmt.source, Precedence.Sequence, E_TTT),
3498 this.semicolon(flags)
3499 ]);
3500 return result;
3501 },
3502
3503 VariableDeclarator: function (stmt, flags) {
3504 var itemFlags = (flags & F_ALLOW_IN) ? E_TTT : E_FTT;
3505 if (stmt.init) {
3506 return [
3507 this.generateExpression(stmt.id, Precedence.Assignment, itemFlags),
3508 space,
3509 '=',
3510 space,
3511 this.generateExpression(stmt.init, Precedence.Assignment, itemFlags)
3512 ];
3513 }
3514 return this.generatePattern(stmt.id, Precedence.Assignment, itemFlags);
3515 },
3516
3517 VariableDeclaration: function (stmt, flags) {
3518 // VariableDeclarator is typed as Statement,
3519 // but joined with comma (not LineTerminator).
3520 // So if comment is attached to target node, we should specialize.
3521 var result, i, iz, node, bodyFlags, that = this;
3522
3523 result = [ stmt.kind ];
3524
3525 bodyFlags = (flags & F_ALLOW_IN) ? S_TFFF : S_FFFF;
3526
3527 function block() {
3528 node = stmt.declarations[0];
3529 if (extra.comment && node.leadingComments) {
3530 result.push('\n');
3531 result.push(addIndent(that.generateStatement(node, bodyFlags)));
3532 } else {
3533 result.push(noEmptySpace());
3534 result.push(that.generateStatement(node, bodyFlags));
3535 }
3536
3537 for (i = 1, iz = stmt.declarations.length; i < iz; ++i) {
3538 node = stmt.declarations[i];
3539 if (extra.comment && node.leadingComments) {
3540 result.push(',' + newline);
3541 result.push(addIndent(that.generateStatement(node, bodyFlags)));
3542 } else {
3543 result.push(',' + space);
3544 result.push(that.generateStatement(node, bodyFlags));
3545 }
3546 }
3547 }
3548
3549 if (stmt.declarations.length > 1) {
3550 withIndent(block);
3551 } else {
3552 block();
3553 }
3554
3555 result.push(this.semicolon(flags));
3556
3557 return result;
3558 },
3559
3560 ThrowStatement: function (stmt, flags) {
3561 return [join(
3562 'throw',
3563 this.generateExpression(stmt.argument, Precedence.Sequence, E_TTT)
3564 ), this.semicolon(flags)];
3565 },
3566
3567 TryStatement: function (stmt, flags) {
3568 var result, i, iz, guardedHandlers;
3569
3570 result = ['try', this.maybeBlock(stmt.block, S_TFFF)];
3571 result = this.maybeBlockSuffix(stmt.block, result);
3572
3573 if (stmt.handlers) {
3574 // old interface
3575 for (i = 0, iz = stmt.handlers.length; i < iz; ++i) {
3576 result = join(result, this.generateStatement(stmt.handlers[i], S_TFFF));
3577 if (stmt.finalizer || i + 1 !== iz) {
3578 result = this.maybeBlockSuffix(stmt.handlers[i].body, result);
3579 }
3580 }
3581 } else {
3582 guardedHandlers = stmt.guardedHandlers || [];
3583
3584 for (i = 0, iz = guardedHandlers.length; i < iz; ++i) {
3585 result = join(result, this.generateStatement(guardedHandlers[i], S_TFFF));
3586 if (stmt.finalizer || i + 1 !== iz) {
3587 result = this.maybeBlockSuffix(guardedHandlers[i].body, result);
3588 }
3589 }
3590
3591 // new interface
3592 if (stmt.handler) {
3593 if (isArray(stmt.handler)) {
3594 for (i = 0, iz = stmt.handler.length; i < iz; ++i) {
3595 result = join(result, this.generateStatement(stmt.handler[i], S_TFFF));
3596 if (stmt.finalizer || i + 1 !== iz) {
3597 result = this.maybeBlockSuffix(stmt.handler[i].body, result);
3598 }
3599 }
3600 } else {
3601 result = join(result, this.generateStatement(stmt.handler, S_TFFF));
3602 if (stmt.finalizer) {
3603 result = this.maybeBlockSuffix(stmt.handler.body, result);
3604 }
3605 }
3606 }
3607 }
3608 if (stmt.finalizer) {
3609 result = join(result, ['finally', this.maybeBlock(stmt.finalizer, S_TFFF)]);
3610 }
3611 return result;
3612 },
3613
3614 SwitchStatement: function (stmt, flags) {
3615 var result, fragment, i, iz, bodyFlags, that = this;
3616 withIndent(function () {
3617 result = [
3618 'switch' + space + '(',
3619 that.generateExpression(stmt.discriminant, Precedence.Sequence, E_TTT),
3620 ')' + space + '{' + newline
3621 ];
3622 });
3623 if (stmt.cases) {
3624 bodyFlags = S_TFFF;
3625 for (i = 0, iz = stmt.cases.length; i < iz; ++i) {
3626 if (i === iz - 1) {
3627 bodyFlags |= F_SEMICOLON_OPT;
3628 }
3629 fragment = addIndent(this.generateStatement(stmt.cases[i], bodyFlags));
3630 result.push(fragment);
3631 if (!endsWithLineTerminator(toSourceNodeWhenNeeded(fragment).toString())) {
3632 result.push(newline);
3633 }
3634 }
3635 }
3636 result.push(addIndent('}'));
3637 return result;
3638 },
3639
3640 SwitchCase: function (stmt, flags) {
3641 var result, fragment, i, iz, bodyFlags, that = this;
3642 withIndent(function () {
3643 if (stmt.test) {
3644 result = [
3645 join('case', that.generateExpression(stmt.test, Precedence.Sequence, E_TTT)),
3646 ':'
3647 ];
3648 } else {
3649 result = ['default:'];
3650 }
3651
3652 i = 0;
3653 iz = stmt.consequent.length;
3654 if (iz && stmt.consequent[0].type === Syntax.BlockStatement) {
3655 fragment = that.maybeBlock(stmt.consequent[0], S_TFFF);
3656 result.push(fragment);
3657 i = 1;
3658 }
3659
3660 if (i !== iz && !endsWithLineTerminator(toSourceNodeWhenNeeded(result).toString())) {
3661 result.push(newline);
3662 }
3663
3664 bodyFlags = S_TFFF;
3665 for (; i < iz; ++i) {
3666 if (i === iz - 1 && flags & F_SEMICOLON_OPT) {
3667 bodyFlags |= F_SEMICOLON_OPT;
3668 }
3669 fragment = addIndent(that.generateStatement(stmt.consequent[i], bodyFlags));
3670 result.push(fragment);
3671 if (i + 1 !== iz && !endsWithLineTerminator(toSourceNodeWhenNeeded(fragment).toString())) {
3672 result.push(newline);
3673 }
3674 }
3675 });
3676 return result;
3677 },
3678
3679 IfStatement: function (stmt, flags) {
3680 var result, bodyFlags, semicolonOptional, that = this;
3681 withIndent(function () {
3682 result = [
3683 'if' + space + '(',
3684 that.generateExpression(stmt.test, Precedence.Sequence, E_TTT),
3685 ')'
3686 ];
3687 });
3688 semicolonOptional = flags & F_SEMICOLON_OPT;
3689 bodyFlags = S_TFFF;
3690 if (semicolonOptional) {
3691 bodyFlags |= F_SEMICOLON_OPT;
3692 }
3693 if (stmt.alternate) {
3694 result.push(this.maybeBlock(stmt.consequent, S_TFFF));
3695 result = this.maybeBlockSuffix(stmt.consequent, result);
3696 if (stmt.alternate.type === Syntax.IfStatement) {
3697 result = join(result, ['else ', this.generateStatement(stmt.alternate, bodyFlags)]);
3698 } else {
3699 result = join(result, join('else', this.maybeBlock(stmt.alternate, bodyFlags)));
3700 }
3701 } else {
3702 result.push(this.maybeBlock(stmt.consequent, bodyFlags));
3703 }
3704 return result;
3705 },
3706
3707 ForStatement: function (stmt, flags) {
3708 var result, that = this;
3709 withIndent(function () {
3710 result = ['for' + space + '('];
3711 if (stmt.init) {
3712 if (stmt.init.type === Syntax.VariableDeclaration) {
3713 result.push(that.generateStatement(stmt.init, S_FFFF));
3714 } else {
3715 // F_ALLOW_IN becomes false.
3716 result.push(that.generateExpression(stmt.init, Precedence.Sequence, E_FTT));
3717 result.push(';');
3718 }
3719 } else {
3720 result.push(';');
3721 }
3722
3723 if (stmt.test) {
3724 result.push(space);
3725 result.push(that.generateExpression(stmt.test, Precedence.Sequence, E_TTT));
3726 result.push(';');
3727 } else {
3728 result.push(';');
3729 }
3730
3731 if (stmt.update) {
3732 result.push(space);
3733 result.push(that.generateExpression(stmt.update, Precedence.Sequence, E_TTT));
3734 result.push(')');
3735 } else {
3736 result.push(')');
3737 }
3738 });
3739
3740 result.push(this.maybeBlock(stmt.body, flags & F_SEMICOLON_OPT ? S_TFFT : S_TFFF));
3741 return result;
3742 },
3743
3744 ForInStatement: function (stmt, flags) {
3745 return this.generateIterationForStatement('in', stmt, flags & F_SEMICOLON_OPT ? S_TFFT : S_TFFF);
3746 },
3747
3748 ForOfStatement: function (stmt, flags) {
3749 return this.generateIterationForStatement('of', stmt, flags & F_SEMICOLON_OPT ? S_TFFT : S_TFFF);
3750 },
3751
3752 LabeledStatement: function (stmt, flags) {
3753 return [stmt.label.name + ':', this.maybeBlock(stmt.body, flags & F_SEMICOLON_OPT ? S_TFFT : S_TFFF)];
3754 },
3755
3756 Program: function (stmt, flags) {
3757 var result, fragment, i, iz, bodyFlags;
3758 iz = stmt.body.length;
3759 result = [safeConcatenation && iz > 0 ? '\n' : ''];
3760 bodyFlags = S_TFTF;
3761 for (i = 0; i < iz; ++i) {
3762 if (!safeConcatenation && i === iz - 1) {
3763 bodyFlags |= F_SEMICOLON_OPT;
3764 }
3765
3766 if (preserveBlankLines) {
3767 // handle spaces before the first line
3768 if (i === 0) {
3769 if (!stmt.body[0].leadingComments) {
3770 generateBlankLines(stmt.range[0], stmt.body[i].range[0], result);
3771 }
3772 }
3773
3774 // handle spaces between lines
3775 if (i > 0) {
3776 if (!stmt.body[i - 1].trailingComments && !stmt.body[i].leadingComments) {
3777 generateBlankLines(stmt.body[i - 1].range[1], stmt.body[i].range[0], result);
3778 }
3779 }
3780 }
3781
3782 fragment = addIndent(this.generateStatement(stmt.body[i], bodyFlags));
3783 result.push(fragment);
3784 if (i + 1 < iz && !endsWithLineTerminator(toSourceNodeWhenNeeded(fragment).toString())) {
3785 if (preserveBlankLines) {
3786 if (!stmt.body[i + 1].leadingComments) {
3787 result.push(newline);
3788 }
3789 } else {
3790 result.push(newline);
3791 }
3792 }
3793
3794 if (preserveBlankLines) {
3795 // handle spaces after the last line
3796 if (i === iz - 1) {
3797 if (!stmt.body[i].trailingComments) {
3798 generateBlankLines(stmt.body[i].range[1], stmt.range[1], result);
3799 }
3800 }
3801 }
3802 }
3803 return result;
3804 },
3805
3806 FunctionDeclaration: function (stmt, flags) {
3807 return [
3808 generateAsyncPrefix(stmt, true),
3809 'function',
3810 generateStarSuffix(stmt) || noEmptySpace(),
3811 stmt.id ? generateIdentifier(stmt.id) : '',
3812 this.generateFunctionBody(stmt)
3813 ];
3814 },
3815
3816 ReturnStatement: function (stmt, flags) {
3817 if (stmt.argument) {
3818 return [join(
3819 'return',
3820 this.generateExpression(stmt.argument, Precedence.Sequence, E_TTT)
3821 ), this.semicolon(flags)];
3822 }
3823 return ['return' + this.semicolon(flags)];
3824 },
3825
3826 WhileStatement: function (stmt, flags) {
3827 var result, that = this;
3828 withIndent(function () {
3829 result = [
3830 'while' + space + '(',
3831 that.generateExpression(stmt.test, Precedence.Sequence, E_TTT),
3832 ')'
3833 ];
3834 });
3835 result.push(this.maybeBlock(stmt.body, flags & F_SEMICOLON_OPT ? S_TFFT : S_TFFF));
3836 return result;
3837 },
3838
3839 WithStatement: function (stmt, flags) {
3840 var result, that = this;
3841 withIndent(function () {
3842 result = [
3843 'with' + space + '(',
3844 that.generateExpression(stmt.object, Precedence.Sequence, E_TTT),
3845 ')'
3846 ];
3847 });
3848 result.push(this.maybeBlock(stmt.body, flags & F_SEMICOLON_OPT ? S_TFFT : S_TFFF));
3849 return result;
3850 }
3851
3852 };
3853
3854 merge(CodeGenerator.prototype, CodeGenerator.Statement);
3855
3856 // Expressions.
3857
3858 CodeGenerator.Expression = {
3859
3860 SequenceExpression: function (expr, precedence, flags) {
3861 var result, i, iz;
3862 if (Precedence.Sequence < precedence) {
3863 flags |= F_ALLOW_IN;
3864 }
3865 result = [];
3866 for (i = 0, iz = expr.expressions.length; i < iz; ++i) {
3867 result.push(this.generateExpression(expr.expressions[i], Precedence.Assignment, flags));
3868 if (i + 1 < iz) {
3869 result.push(',' + space);
3870 }
3871 }
3872 return parenthesize(result, Precedence.Sequence, precedence);
3873 },
3874
3875 AssignmentExpression: function (expr, precedence, flags) {
3876 return this.generateAssignment(expr.left, expr.right, expr.operator, precedence, flags);
3877 },
3878
3879 ArrowFunctionExpression: function (expr, precedence, flags) {
3880 return parenthesize(this.generateFunctionBody(expr), Precedence.ArrowFunction, precedence);
3881 },
3882
3883 ConditionalExpression: function (expr, precedence, flags) {
3884 if (Precedence.Conditional < precedence) {
3885 flags |= F_ALLOW_IN;
3886 }
3887 return parenthesize(
3888 [
3889 this.generateExpression(expr.test, Precedence.LogicalOR, flags),
3890 space + '?' + space,
3891 this.generateExpression(expr.consequent, Precedence.Assignment, flags),
3892 space + ':' + space,
3893 this.generateExpression(expr.alternate, Precedence.Assignment, flags)
3894 ],
3895 Precedence.Conditional,
3896 precedence
3897 );
3898 },
3899
3900 LogicalExpression: function (expr, precedence, flags) {
3901 return this.BinaryExpression(expr, precedence, flags);
3902 },
3903
3904 BinaryExpression: function (expr, precedence, flags) {
3905 var result, currentPrecedence, fragment, leftSource;
3906 currentPrecedence = BinaryPrecedence[expr.operator];
3907
3908 if (currentPrecedence < precedence) {
3909 flags |= F_ALLOW_IN;
3910 }
3911
3912 fragment = this.generateExpression(expr.left, currentPrecedence, flags);
3913
3914 leftSource = fragment.toString();
3915
3916 if (leftSource.charCodeAt(leftSource.length - 1) === 0x2F /* / */ && esutils.code.isIdentifierPartES5(expr.operator.charCodeAt(0))) {
3917 result = [fragment, noEmptySpace(), expr.operator];
3918 } else {
3919 result = join(fragment, expr.operator);
3920 }
3921
3922 fragment = this.generateExpression(expr.right, currentPrecedence + 1, flags);
3923
3924 if (expr.operator === '/' && fragment.toString().charAt(0) === '/' ||
3925 expr.operator.slice(-1) === '<' && fragment.toString().slice(0, 3) === '!--') {
3926 // If '/' concats with '/' or `<` concats with `!--`, it is interpreted as comment start
3927 result.push(noEmptySpace());
3928 result.push(fragment);
3929 } else {
3930 result = join(result, fragment);
3931 }
3932
3933 if (expr.operator === 'in' && !(flags & F_ALLOW_IN)) {
3934 return ['(', result, ')'];
3935 }
3936 return parenthesize(result, currentPrecedence, precedence);
3937 },
3938
3939 CallExpression: function (expr, precedence, flags) {
3940 var result, i, iz;
3941 // F_ALLOW_UNPARATH_NEW becomes false.
3942 result = [this.generateExpression(expr.callee, Precedence.Call, E_TTF)];
3943 result.push('(');
3944 for (i = 0, iz = expr['arguments'].length; i < iz; ++i) {
3945 result.push(this.generateExpression(expr['arguments'][i], Precedence.Assignment, E_TTT));
3946 if (i + 1 < iz) {
3947 result.push(',' + space);
3948 }
3949 }
3950 result.push(')');
3951
3952 if (!(flags & F_ALLOW_CALL)) {
3953 return ['(', result, ')'];
3954 }
3955 return parenthesize(result, Precedence.Call, precedence);
3956 },
3957
3958 NewExpression: function (expr, precedence, flags) {
3959 var result, length, i, iz, itemFlags;
3960 length = expr['arguments'].length;
3961
3962 // F_ALLOW_CALL becomes false.
3963 // F_ALLOW_UNPARATH_NEW may become false.
3964 itemFlags = (flags & F_ALLOW_UNPARATH_NEW && !parentheses && length === 0) ? E_TFT : E_TFF;
3965
3966 result = join(
3967 'new',
3968 this.generateExpression(expr.callee, Precedence.New, itemFlags)
3969 );
3970
3971 if (!(flags & F_ALLOW_UNPARATH_NEW) || parentheses || length > 0) {
3972 result.push('(');
3973 for (i = 0, iz = length; i < iz; ++i) {
3974 result.push(this.generateExpression(expr['arguments'][i], Precedence.Assignment, E_TTT));
3975 if (i + 1 < iz) {
3976 result.push(',' + space);
3977 }
3978 }
3979 result.push(')');
3980 }
3981
3982 return parenthesize(result, Precedence.New, precedence);
3983 },
3984
3985 MemberExpression: function (expr, precedence, flags) {
3986 var result, fragment;
3987
3988 // F_ALLOW_UNPARATH_NEW becomes false.
3989 result = [this.generateExpression(expr.object, Precedence.Call, (flags & F_ALLOW_CALL) ? E_TTF : E_TFF)];
3990
3991 if (expr.computed) {
3992 result.push('[');
3993 result.push(this.generateExpression(expr.property, Precedence.Sequence, flags & F_ALLOW_CALL ? E_TTT : E_TFT));
3994 result.push(']');
3995 } else {
3996 if (expr.object.type === Syntax.Literal && typeof expr.object.value === 'number') {
3997 fragment = toSourceNodeWhenNeeded(result).toString();
3998 // When the following conditions are all true,
3999 // 1. No floating point
4000 // 2. Don't have exponents
4001 // 3. The last character is a decimal digit
4002 // 4. Not hexadecimal OR octal number literal
4003 // we should add a floating point.
4004 if (
4005 fragment.indexOf('.') < 0 &&
4006 !/[eExX]/.test(fragment) &&
4007 esutils.code.isDecimalDigit(fragment.charCodeAt(fragment.length - 1)) &&
4008 !(fragment.length >= 2 && fragment.charCodeAt(0) === 48) // '0'
4009 ) {
4010 result.push('.');
4011 }
4012 }
4013 result.push('.');
4014 result.push(generateIdentifier(expr.property));
4015 }
4016
4017 return parenthesize(result, Precedence.Member, precedence);
4018 },
4019
4020 MetaProperty: function (expr, precedence, flags) {
4021 var result;
4022 result = [];
4023 result.push(expr.meta);
4024 result.push('.');
4025 result.push(expr.property);
4026 return parenthesize(result, Precedence.Member, precedence);
4027 },
4028
4029 UnaryExpression: function (expr, precedence, flags) {
4030 var result, fragment, rightCharCode, leftSource, leftCharCode;
4031 fragment = this.generateExpression(expr.argument, Precedence.Unary, E_TTT);
4032
4033 if (space === '') {
4034 result = join(expr.operator, fragment);
4035 } else {
4036 result = [expr.operator];
4037 if (expr.operator.length > 2) {
4038 // delete, void, typeof
4039 // get `typeof []`, not `typeof[]`
4040 result = join(result, fragment);
4041 } else {
4042 // Prevent inserting spaces between operator and argument if it is unnecessary
4043 // like, `!cond`
4044 leftSource = toSourceNodeWhenNeeded(result).toString();
4045 leftCharCode = leftSource.charCodeAt(leftSource.length - 1);
4046 rightCharCode = fragment.toString().charCodeAt(0);
4047
4048 if ((((leftCharCode === 0x2B /* + */ || leftCharCode === 0x2D) /* - */) && leftCharCode === rightCharCode) ||
4049 (esutils.code.isIdentifierPartES5(leftCharCode) && esutils.code.isIdentifierPartES5(rightCharCode))) {
4050 result.push(noEmptySpace());
4051 result.push(fragment);
4052 } else {
4053 result.push(fragment);
4054 }
4055 }
4056 }
4057 return parenthesize(result, Precedence.Unary, precedence);
4058 },
4059
4060 YieldExpression: function (expr, precedence, flags) {
4061 var result;
4062 if (expr.delegate) {
4063 result = 'yield*';
4064 } else {
4065 result = 'yield';
4066 }
4067 if (expr.argument) {
4068 result = join(
4069 result,
4070 this.generateExpression(expr.argument, Precedence.Yield, E_TTT)
4071 );
4072 }
4073 return parenthesize(result, Precedence.Yield, precedence);
4074 },
4075
4076 AwaitExpression: function (expr, precedence, flags) {
4077 var result = join(
4078 expr.all ? 'await*' : 'await',
4079 this.generateExpression(expr.argument, Precedence.Await, E_TTT)
4080 );
4081 return parenthesize(result, Precedence.Await, precedence);
4082 },
4083
4084 UpdateExpression: function (expr, precedence, flags) {
4085 if (expr.prefix) {
4086 return parenthesize(
4087 [
4088 expr.operator,
4089 this.generateExpression(expr.argument, Precedence.Unary, E_TTT)
4090 ],
4091 Precedence.Unary,
4092 precedence
4093 );
4094 }
4095 return parenthesize(
4096 [
4097 this.generateExpression(expr.argument, Precedence.Postfix, E_TTT),
4098 expr.operator
4099 ],
4100 Precedence.Postfix,
4101 precedence
4102 );
4103 },
4104
4105 FunctionExpression: function (expr, precedence, flags) {
4106 var result = [
4107 generateAsyncPrefix(expr, true),
4108 'function'
4109 ];
4110 if (expr.id) {
4111 result.push(generateStarSuffix(expr) || noEmptySpace());
4112 result.push(generateIdentifier(expr.id));
4113 } else {
4114 result.push(generateStarSuffix(expr) || space);
4115 }
4116 result.push(this.generateFunctionBody(expr));
4117 return result;
4118 },
4119
4120 ArrayPattern: function (expr, precedence, flags) {
4121 return this.ArrayExpression(expr, precedence, flags, true);
4122 },
4123
4124 ArrayExpression: function (expr, precedence, flags, isPattern) {
4125 var result, multiline, that = this;
4126 if (!expr.elements.length) {
4127 return '[]';
4128 }
4129 multiline = isPattern ? false : expr.elements.length > 1;
4130 result = ['[', multiline ? newline : ''];
4131 withIndent(function (indent) {
4132 var i, iz;
4133 for (i = 0, iz = expr.elements.length; i < iz; ++i) {
4134 if (!expr.elements[i]) {
4135 if (multiline) {
4136 result.push(indent);
4137 }
4138 if (i + 1 === iz) {
4139 result.push(',');
4140 }
4141 } else {
4142 result.push(multiline ? indent : '');
4143 result.push(that.generateExpression(expr.elements[i], Precedence.Assignment, E_TTT));
4144 }
4145 if (i + 1 < iz) {
4146 result.push(',' + (multiline ? newline : space));
4147 }
4148 }
4149 });
4150 if (multiline && !endsWithLineTerminator(toSourceNodeWhenNeeded(result).toString())) {
4151 result.push(newline);
4152 }
4153 result.push(multiline ? base : '');
4154 result.push(']');
4155 return result;
4156 },
4157
4158 RestElement: function(expr, precedence, flags) {
4159 return '...' + this.generatePattern(expr.argument);
4160 },
4161
4162 ClassExpression: function (expr, precedence, flags) {
4163 var result, fragment;
4164 result = ['class'];
4165 if (expr.id) {
4166 result = join(result, this.generateExpression(expr.id, Precedence.Sequence, E_TTT));
4167 }
4168 if (expr.superClass) {
4169 fragment = join('extends', this.generateExpression(expr.superClass, Precedence.Assignment, E_TTT));
4170 result = join(result, fragment);
4171 }
4172 result.push(space);
4173 result.push(this.generateStatement(expr.body, S_TFFT));
4174 return result;
4175 },
4176
4177 MethodDefinition: function (expr, precedence, flags) {
4178 var result, fragment;
4179 if (expr['static']) {
4180 result = ['static' + space];
4181 } else {
4182 result = [];
4183 }
4184 if (expr.kind === 'get' || expr.kind === 'set') {
4185 fragment = [
4186 join(expr.kind, this.generatePropertyKey(expr.key, expr.computed)),
4187 this.generateFunctionBody(expr.value)
4188 ];
4189 } else {
4190 fragment = [
4191 generateMethodPrefix(expr),
4192 this.generatePropertyKey(expr.key, expr.computed),
4193 this.generateFunctionBody(expr.value)
4194 ];
4195 }
4196 return join(result, fragment);
4197 },
4198
4199 Property: function (expr, precedence, flags) {
4200 if (expr.kind === 'get' || expr.kind === 'set') {
4201 return [
4202 expr.kind, noEmptySpace(),
4203 this.generatePropertyKey(expr.key, expr.computed),
4204 this.generateFunctionBody(expr.value)
4205 ];
4206 }
4207
4208 if (expr.shorthand) {
4209 return this.generatePropertyKey(expr.key, expr.computed);
4210 }
4211
4212 if (expr.method) {
4213 return [
4214 generateMethodPrefix(expr),
4215 this.generatePropertyKey(expr.key, expr.computed),
4216 this.generateFunctionBody(expr.value)
4217 ];
4218 }
4219
4220 return [
4221 this.generatePropertyKey(expr.key, expr.computed),
4222 ':' + space,
4223 this.generateExpression(expr.value, Precedence.Assignment, E_TTT)
4224 ];
4225 },
4226
4227 ObjectExpression: function (expr, precedence, flags) {
4228 var multiline, result, fragment, that = this;
4229
4230 if (!expr.properties.length) {
4231 return '{}';
4232 }
4233 multiline = expr.properties.length > 1;
4234
4235 withIndent(function () {
4236 fragment = that.generateExpression(expr.properties[0], Precedence.Sequence, E_TTT);
4237 });
4238
4239 if (!multiline) {
4240 // issues 4
4241 // Do not transform from
4242 // dejavu.Class.declare({
4243 // method2: function () {}
4244 // });
4245 // to
4246 // dejavu.Class.declare({method2: function () {
4247 // }});
4248 if (!hasLineTerminator(toSourceNodeWhenNeeded(fragment).toString())) {
4249 return [ '{', space, fragment, space, '}' ];
4250 }
4251 }
4252
4253 withIndent(function (indent) {
4254 var i, iz;
4255 result = [ '{', newline, indent, fragment ];
4256
4257 if (multiline) {
4258 result.push(',' + newline);
4259 for (i = 1, iz = expr.properties.length; i < iz; ++i) {
4260 result.push(indent);
4261 result.push(that.generateExpression(expr.properties[i], Precedence.Sequence, E_TTT));
4262 if (i + 1 < iz) {
4263 result.push(',' + newline);
4264 }
4265 }
4266 }
4267 });
4268
4269 if (!endsWithLineTerminator(toSourceNodeWhenNeeded(result).toString())) {
4270 result.push(newline);
4271 }
4272 result.push(base);
4273 result.push('}');
4274 return result;
4275 },
4276
4277 AssignmentPattern: function(expr, precedence, flags) {
4278 return this.generateAssignment(expr.left, expr.right, expr.operator, precedence, flags);
4279 },
4280
4281 ObjectPattern: function (expr, precedence, flags) {
4282 var result, i, iz, multiline, property, that = this;
4283 if (!expr.properties.length) {
4284 return '{}';
4285 }
4286
4287 multiline = false;
4288 if (expr.properties.length === 1) {
4289 property = expr.properties[0];
4290 if (property.value.type !== Syntax.Identifier) {
4291 multiline = true;
4292 }
4293 } else {
4294 for (i = 0, iz = expr.properties.length; i < iz; ++i) {
4295 property = expr.properties[i];
4296 if (!property.shorthand) {
4297 multiline = true;
4298 break;
4299 }
4300 }
4301 }
4302 result = ['{', multiline ? newline : '' ];
4303
4304 withIndent(function (indent) {
4305 var i, iz;
4306 for (i = 0, iz = expr.properties.length; i < iz; ++i) {
4307 result.push(multiline ? indent : '');
4308 result.push(that.generateExpression(expr.properties[i], Precedence.Sequence, E_TTT));
4309 if (i + 1 < iz) {
4310 result.push(',' + (multiline ? newline : space));
4311 }
4312 }
4313 });
4314
4315 if (multiline && !endsWithLineTerminator(toSourceNodeWhenNeeded(result).toString())) {
4316 result.push(newline);
4317 }
4318 result.push(multiline ? base : '');
4319 result.push('}');
4320 return result;
4321 },
4322
4323 ThisExpression: function (expr, precedence, flags) {
4324 return 'this';
4325 },
4326
4327 Super: function (expr, precedence, flags) {
4328 return 'super';
4329 },
4330
4331 Identifier: function (expr, precedence, flags) {
4332 return generateIdentifier(expr);
4333 },
4334
4335 ImportDefaultSpecifier: function (expr, precedence, flags) {
4336 return generateIdentifier(expr.id || expr.local);
4337 },
4338
4339 ImportNamespaceSpecifier: function (expr, precedence, flags) {
4340 var result = ['*'];
4341 var id = expr.id || expr.local;
4342 if (id) {
4343 result.push(space + 'as' + noEmptySpace() + generateIdentifier(id));
4344 }
4345 return result;
4346 },
4347
4348 ImportSpecifier: function (expr, precedence, flags) {
4349 var imported = expr.imported;
4350 var result = [ imported.name ];
4351 var local = expr.local;
4352 if (local && local.name !== imported.name) {
4353 result.push(noEmptySpace() + 'as' + noEmptySpace() + generateIdentifier(local));
4354 }
4355 return result;
4356 },
4357
4358 ExportSpecifier: function (expr, precedence, flags) {
4359 var local = expr.local;
4360 var result = [ local.name ];
4361 var exported = expr.exported;
4362 if (exported && exported.name !== local.name) {
4363 result.push(noEmptySpace() + 'as' + noEmptySpace() + generateIdentifier(exported));
4364 }
4365 return result;
4366 },
4367
4368 Literal: function (expr, precedence, flags) {
4369 var raw;
4370 if (expr.hasOwnProperty('raw') && parse && extra.raw) {
4371 try {
4372 raw = parse(expr.raw).body[0].expression;
4373 if (raw.type === Syntax.Literal) {
4374 if (raw.value === expr.value) {
4375 return expr.raw;
4376 }
4377 }
4378 } catch (e) {
4379 // not use raw property
4380 }
4381 }
4382
4383 if (expr.value === null) {
4384 return 'null';
4385 }
4386
4387 if (typeof expr.value === 'string') {
4388 return escapeString(expr.value);
4389 }
4390
4391 if (typeof expr.value === 'number') {
4392 return generateNumber(expr.value);
4393 }
4394
4395 if (typeof expr.value === 'boolean') {
4396 return expr.value ? 'true' : 'false';
4397 }
4398
4399 return generateRegExp(expr.value);
4400 },
4401
4402 GeneratorExpression: function (expr, precedence, flags) {
4403 return this.ComprehensionExpression(expr, precedence, flags);
4404 },
4405
4406 ComprehensionExpression: function (expr, precedence, flags) {
4407 // GeneratorExpression should be parenthesized with (...), ComprehensionExpression with [...]
4408 // Due to https://bugzilla.mozilla.org/show_bug.cgi?id=883468 position of expr.body can differ in Spidermonkey and ES6
4409
4410 var result, i, iz, fragment, that = this;
4411 result = (expr.type === Syntax.GeneratorExpression) ? ['('] : ['['];
4412
4413 if (extra.moz.comprehensionExpressionStartsWithAssignment) {
4414 fragment = this.generateExpression(expr.body, Precedence.Assignment, E_TTT);
4415 result.push(fragment);
4416 }
4417
4418 if (expr.blocks) {
4419 withIndent(function () {
4420 for (i = 0, iz = expr.blocks.length; i < iz; ++i) {
4421 fragment = that.generateExpression(expr.blocks[i], Precedence.Sequence, E_TTT);
4422 if (i > 0 || extra.moz.comprehensionExpressionStartsWithAssignment) {
4423 result = join(result, fragment);
4424 } else {
4425 result.push(fragment);
4426 }
4427 }
4428 });
4429 }
4430
4431 if (expr.filter) {
4432 result = join(result, 'if' + space);
4433 fragment = this.generateExpression(expr.filter, Precedence.Sequence, E_TTT);
4434 result = join(result, [ '(', fragment, ')' ]);
4435 }
4436
4437 if (!extra.moz.comprehensionExpressionStartsWithAssignment) {
4438 fragment = this.generateExpression(expr.body, Precedence.Assignment, E_TTT);
4439
4440 result = join(result, fragment);
4441 }
4442
4443 result.push((expr.type === Syntax.GeneratorExpression) ? ')' : ']');
4444 return result;
4445 },
4446
4447 ComprehensionBlock: function (expr, precedence, flags) {
4448 var fragment;
4449 if (expr.left.type === Syntax.VariableDeclaration) {
4450 fragment = [
4451 expr.left.kind, noEmptySpace(),
4452 this.generateStatement(expr.left.declarations[0], S_FFFF)
4453 ];
4454 } else {
4455 fragment = this.generateExpression(expr.left, Precedence.Call, E_TTT);
4456 }
4457
4458 fragment = join(fragment, expr.of ? 'of' : 'in');
4459 fragment = join(fragment, this.generateExpression(expr.right, Precedence.Sequence, E_TTT));
4460
4461 return [ 'for' + space + '(', fragment, ')' ];
4462 },
4463
4464 SpreadElement: function (expr, precedence, flags) {
4465 return [
4466 '...',
4467 this.generateExpression(expr.argument, Precedence.Assignment, E_TTT)
4468 ];
4469 },
4470
4471 TaggedTemplateExpression: function (expr, precedence, flags) {
4472 var itemFlags = E_TTF;
4473 if (!(flags & F_ALLOW_CALL)) {
4474 itemFlags = E_TFF;
4475 }
4476 var result = [
4477 this.generateExpression(expr.tag, Precedence.Call, itemFlags),
4478 this.generateExpression(expr.quasi, Precedence.Primary, E_FFT)
4479 ];
4480 return parenthesize(result, Precedence.TaggedTemplate, precedence);
4481 },
4482
4483 TemplateElement: function (expr, precedence, flags) {
4484 // Don't use "cooked". Since tagged template can use raw template
4485 // representation. So if we do so, it breaks the script semantics.
4486 return expr.value.raw;
4487 },
4488
4489 TemplateLiteral: function (expr, precedence, flags) {
4490 var result, i, iz;
4491 result = [ '`' ];
4492 for (i = 0, iz = expr.quasis.length; i < iz; ++i) {
4493 result.push(this.generateExpression(expr.quasis[i], Precedence.Primary, E_TTT));
4494 if (i + 1 < iz) {
4495 result.push('${' + space);
4496 result.push(this.generateExpression(expr.expressions[i], Precedence.Sequence, E_TTT));
4497 result.push(space + '}');
4498 }
4499 }
4500 result.push('`');
4501 return result;
4502 },
4503
4504 ModuleSpecifier: function (expr, precedence, flags) {
4505 return this.Literal(expr, precedence, flags);
4506 }
4507
4508 };
4509
4510 merge(CodeGenerator.prototype, CodeGenerator.Expression);
4511
4512 CodeGenerator.prototype.generateExpression = function (expr, precedence, flags) {
4513 var result, type;
4514
4515 type = expr.type || Syntax.Property;
4516
4517 if (extra.verbatim && expr.hasOwnProperty(extra.verbatim)) {
4518 return generateVerbatim(expr, precedence);
4519 }
4520
4521 result = this[type](expr, precedence, flags);
4522
4523
4524 if (extra.comment) {
4525 result = addComments(expr, result);
4526 }
4527 return toSourceNodeWhenNeeded(result, expr);
4528 };
4529
4530 CodeGenerator.prototype.generateStatement = function (stmt, flags) {
4531 var result,
4532 fragment;
4533
4534 result = this[stmt.type](stmt, flags);
4535
4536 // Attach comments
4537
4538 if (extra.comment) {
4539 result = addComments(stmt, result);
4540 }
4541
4542 fragment = toSourceNodeWhenNeeded(result).toString();
4543 if (stmt.type === Syntax.Program && !safeConcatenation && newline === '' && fragment.charAt(fragment.length - 1) === '\n') {
4544 result = sourceMap ? toSourceNodeWhenNeeded(result).replaceRight(/\s+$/, '') : fragment.replace(/\s+$/, '');
4545 }
4546
4547 return toSourceNodeWhenNeeded(result, stmt);
4548 };
4549
4550 function generateInternal(node) {
4551 var codegen;
4552
4553 codegen = new CodeGenerator();
4554 if (isStatement(node)) {
4555 return codegen.generateStatement(node, S_TFFF);
4556 }
4557
4558 if (isExpression(node)) {
4559 return codegen.generateExpression(node, Precedence.Sequence, E_TTT);
4560 }
4561
4562 throw new Error('Unknown node type: ' + node.type);
4563 }
4564
4565 function generate(node, options) {
4566 var defaultOptions = getDefaultOptions(), result, pair;
4567
4568 if (options != null) {
4569 // Obsolete options
4570 //
4571 // `options.indent`
4572 // `options.base`
4573 //
4574 // Instead of them, we can use `option.format.indent`.
4575 if (typeof options.indent === 'string') {
4576 defaultOptions.format.indent.style = options.indent;
4577 }
4578 if (typeof options.base === 'number') {
4579 defaultOptions.format.indent.base = options.base;
4580 }
4581 options = updateDeeply(defaultOptions, options);
4582 indent = options.format.indent.style;
4583 if (typeof options.base === 'string') {
4584 base = options.base;
4585 } else {
4586 base = stringRepeat(indent, options.format.indent.base);
4587 }
4588 } else {
4589 options = defaultOptions;
4590 indent = options.format.indent.style;
4591 base = stringRepeat(indent, options.format.indent.base);
4592 }
4593 json = options.format.json;
4594 renumber = options.format.renumber;
4595 hexadecimal = json ? false : options.format.hexadecimal;
4596 quotes = json ? 'double' : options.format.quotes;
4597 escapeless = options.format.escapeless;
4598 newline = options.format.newline;
4599 space = options.format.space;
4600 if (options.format.compact) {
4601 newline = space = indent = base = '';
4602 }
4603 parentheses = options.format.parentheses;
4604 semicolons = options.format.semicolons;
4605 safeConcatenation = options.format.safeConcatenation;
4606 directive = options.directive;
4607 parse = json ? null : options.parse;
4608 sourceMap = options.sourceMap;
4609 sourceCode = options.sourceCode;
4610 preserveBlankLines = options.format.preserveBlankLines && sourceCode !== null;
4611 extra = options;
4612
4613 if (sourceMap) {
4614 if (!exports.browser) {
4615 // We assume environment is node.js
4616 // And prevent from including source-map by browserify
4617 SourceNode = _dereq_('source-map').SourceNode;
4618 } else {
4619 SourceNode = global.sourceMap.SourceNode;
4620 }
4621 }
4622
4623 result = generateInternal(node);
4624
4625 if (!sourceMap) {
4626 pair = {code: result.toString(), map: null};
4627 return options.sourceMapWithCode ? pair : pair.code;
4628 }
4629
4630
4631 pair = result.toStringWithSourceMap({
4632 file: options.file,
4633 sourceRoot: options.sourceMapRoot
4634 });
4635
4636 if (options.sourceContent) {
4637 pair.map.setSourceContent(options.sourceMap,
4638 options.sourceContent);
4639 }
4640
4641 if (options.sourceMapWithCode) {
4642 return pair;
4643 }
4644
4645 return pair.map.toString();
4646 }
4647
4648 FORMAT_MINIFY = {
4649 indent: {
4650 style: '',
4651 base: 0
4652 },
4653 renumber: true,
4654 hexadecimal: true,
4655 quotes: 'auto',
4656 escapeless: true,
4657 compact: true,
4658 parentheses: false,
4659 semicolons: false
4660 };
4661
4662 FORMAT_DEFAULTS = getDefaultOptions().format;
4663
4664 exports.version = _dereq_('./package.json').version;
4665 exports.generate = generate;
4666 exports.attachComments = estraverse.attachComments;
4667 exports.Precedence = updateDeeply({}, Precedence);
4668 exports.browser = false;
4669 exports.FORMAT_MINIFY = FORMAT_MINIFY;
4670 exports.FORMAT_DEFAULTS = FORMAT_DEFAULTS;
4671}());
4672/* vim: set sw=4 ts=4 et tw=80 : */
4673
4674}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
4675},{"./package.json":82,"estraverse":69,"esutils":96,"source-map":70}],69:[function(_dereq_,module,exports){
4676/*
4677 Copyright (C) 2012-2013 Yusuke Suzuki <utatane.tea@gmail.com>
4678 Copyright (C) 2012 Ariya Hidayat <ariya.hidayat@gmail.com>
4679
4680 Redistribution and use in source and binary forms, with or without
4681 modification, are permitted provided that the following conditions are met:
4682
4683 * Redistributions of source code must retain the above copyright
4684 notice, this list of conditions and the following disclaimer.
4685 * Redistributions in binary form must reproduce the above copyright
4686 notice, this list of conditions and the following disclaimer in the
4687 documentation and/or other materials provided with the distribution.
4688
4689 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
4690 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
4691 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
4692 ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
4693 DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
4694 (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
4695 LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
4696 ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
4697 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
4698 THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
4699*/
4700/*jslint vars:false, bitwise:true*/
4701/*jshint indent:4*/
4702/*global exports:true, define:true*/
4703(function (root, factory) {
4704 'use strict';
4705
4706 // Universal Module Definition (UMD) to support AMD, CommonJS/Node.js,
4707 // and plain browser loading,
4708 if (typeof define === 'function' && define.amd) {
4709 define(['exports'], factory);
4710 } else if (typeof exports !== 'undefined') {
4711 factory(exports);
4712 } else {
4713 factory((root.estraverse = {}));
4714 }
4715}(this, function clone(exports) {
4716 'use strict';
4717
4718 var Syntax,
4719 isArray,
4720 VisitorOption,
4721 VisitorKeys,
4722 objectCreate,
4723 objectKeys,
4724 BREAK,
4725 SKIP,
4726 REMOVE;
4727
4728 function ignoreJSHintError() { }
4729
4730 isArray = Array.isArray;
4731 if (!isArray) {
4732 isArray = function isArray(array) {
4733 return Object.prototype.toString.call(array) === '[object Array]';
4734 };
4735 }
4736
4737 function deepCopy(obj) {
4738 var ret = {}, key, val;
4739 for (key in obj) {
4740 if (obj.hasOwnProperty(key)) {
4741 val = obj[key];
4742 if (typeof val === 'object' && val !== null) {
4743 ret[key] = deepCopy(val);
4744 } else {
4745 ret[key] = val;
4746 }
4747 }
4748 }
4749 return ret;
4750 }
4751
4752 function shallowCopy(obj) {
4753 var ret = {}, key;
4754 for (key in obj) {
4755 if (obj.hasOwnProperty(key)) {
4756 ret[key] = obj[key];
4757 }
4758 }
4759 return ret;
4760 }
4761 ignoreJSHintError(shallowCopy);
4762
4763 // based on LLVM libc++ upper_bound / lower_bound
4764 // MIT License
4765
4766 function upperBound(array, func) {
4767 var diff, len, i, current;
4768
4769 len = array.length;
4770 i = 0;
4771
4772 while (len) {
4773 diff = len >>> 1;
4774 current = i + diff;
4775 if (func(array[current])) {
4776 len = diff;
4777 } else {
4778 i = current + 1;
4779 len -= diff + 1;
4780 }
4781 }
4782 return i;
4783 }
4784
4785 function lowerBound(array, func) {
4786 var diff, len, i, current;
4787
4788 len = array.length;
4789 i = 0;
4790
4791 while (len) {
4792 diff = len >>> 1;
4793 current = i + diff;
4794 if (func(array[current])) {
4795 i = current + 1;
4796 len -= diff + 1;
4797 } else {
4798 len = diff;
4799 }
4800 }
4801 return i;
4802 }
4803 ignoreJSHintError(lowerBound);
4804
4805 objectCreate = Object.create || (function () {
4806 function F() { }
4807
4808 return function (o) {
4809 F.prototype = o;
4810 return new F();
4811 };
4812 })();
4813
4814 objectKeys = Object.keys || function (o) {
4815 var keys = [], key;
4816 for (key in o) {
4817 keys.push(key);
4818 }
4819 return keys;
4820 };
4821
4822 function extend(to, from) {
4823 var keys = objectKeys(from), key, i, len;
4824 for (i = 0, len = keys.length; i < len; i += 1) {
4825 key = keys[i];
4826 to[key] = from[key];
4827 }
4828 return to;
4829 }
4830
4831 Syntax = {
4832 AssignmentExpression: 'AssignmentExpression',
4833 ArrayExpression: 'ArrayExpression',
4834 ArrayPattern: 'ArrayPattern',
4835 ArrowFunctionExpression: 'ArrowFunctionExpression',
4836 AwaitExpression: 'AwaitExpression', // CAUTION: It's deferred to ES7.
4837 BlockStatement: 'BlockStatement',
4838 BinaryExpression: 'BinaryExpression',
4839 BreakStatement: 'BreakStatement',
4840 CallExpression: 'CallExpression',
4841 CatchClause: 'CatchClause',
4842 ClassBody: 'ClassBody',
4843 ClassDeclaration: 'ClassDeclaration',
4844 ClassExpression: 'ClassExpression',
4845 ComprehensionBlock: 'ComprehensionBlock', // CAUTION: It's deferred to ES7.
4846 ComprehensionExpression: 'ComprehensionExpression', // CAUTION: It's deferred to ES7.
4847 ConditionalExpression: 'ConditionalExpression',
4848 ContinueStatement: 'ContinueStatement',
4849 DebuggerStatement: 'DebuggerStatement',
4850 DirectiveStatement: 'DirectiveStatement',
4851 DoWhileStatement: 'DoWhileStatement',
4852 EmptyStatement: 'EmptyStatement',
4853 ExportBatchSpecifier: 'ExportBatchSpecifier',
4854 ExportDeclaration: 'ExportDeclaration',
4855 ExportSpecifier: 'ExportSpecifier',
4856 ExpressionStatement: 'ExpressionStatement',
4857 ForStatement: 'ForStatement',
4858 ForInStatement: 'ForInStatement',
4859 ForOfStatement: 'ForOfStatement',
4860 FunctionDeclaration: 'FunctionDeclaration',
4861 FunctionExpression: 'FunctionExpression',
4862 GeneratorExpression: 'GeneratorExpression', // CAUTION: It's deferred to ES7.
4863 Identifier: 'Identifier',
4864 IfStatement: 'IfStatement',
4865 ImportDeclaration: 'ImportDeclaration',
4866 ImportDefaultSpecifier: 'ImportDefaultSpecifier',
4867 ImportNamespaceSpecifier: 'ImportNamespaceSpecifier',
4868 ImportSpecifier: 'ImportSpecifier',
4869 Literal: 'Literal',
4870 LabeledStatement: 'LabeledStatement',
4871 LogicalExpression: 'LogicalExpression',
4872 MemberExpression: 'MemberExpression',
4873 MethodDefinition: 'MethodDefinition',
4874 ModuleSpecifier: 'ModuleSpecifier',
4875 NewExpression: 'NewExpression',
4876 ObjectExpression: 'ObjectExpression',
4877 ObjectPattern: 'ObjectPattern',
4878 Program: 'Program',
4879 Property: 'Property',
4880 ReturnStatement: 'ReturnStatement',
4881 SequenceExpression: 'SequenceExpression',
4882 SpreadElement: 'SpreadElement',
4883 SwitchStatement: 'SwitchStatement',
4884 SwitchCase: 'SwitchCase',
4885 TaggedTemplateExpression: 'TaggedTemplateExpression',
4886 TemplateElement: 'TemplateElement',
4887 TemplateLiteral: 'TemplateLiteral',
4888 ThisExpression: 'ThisExpression',
4889 ThrowStatement: 'ThrowStatement',
4890 TryStatement: 'TryStatement',
4891 UnaryExpression: 'UnaryExpression',
4892 UpdateExpression: 'UpdateExpression',
4893 VariableDeclaration: 'VariableDeclaration',
4894 VariableDeclarator: 'VariableDeclarator',
4895 WhileStatement: 'WhileStatement',
4896 WithStatement: 'WithStatement',
4897 YieldExpression: 'YieldExpression'
4898 };
4899
4900 VisitorKeys = {
4901 AssignmentExpression: ['left', 'right'],
4902 ArrayExpression: ['elements'],
4903 ArrayPattern: ['elements'],
4904 ArrowFunctionExpression: ['params', 'defaults', 'rest', 'body'],
4905 AwaitExpression: ['argument'], // CAUTION: It's deferred to ES7.
4906 BlockStatement: ['body'],
4907 BinaryExpression: ['left', 'right'],
4908 BreakStatement: ['label'],
4909 CallExpression: ['callee', 'arguments'],
4910 CatchClause: ['param', 'body'],
4911 ClassBody: ['body'],
4912 ClassDeclaration: ['id', 'body', 'superClass'],
4913 ClassExpression: ['id', 'body', 'superClass'],
4914 ComprehensionBlock: ['left', 'right'], // CAUTION: It's deferred to ES7.
4915 ComprehensionExpression: ['blocks', 'filter', 'body'], // CAUTION: It's deferred to ES7.
4916 ConditionalExpression: ['test', 'consequent', 'alternate'],
4917 ContinueStatement: ['label'],
4918 DebuggerStatement: [],
4919 DirectiveStatement: [],
4920 DoWhileStatement: ['body', 'test'],
4921 EmptyStatement: [],
4922 ExportBatchSpecifier: [],
4923 ExportDeclaration: ['declaration', 'specifiers', 'source'],
4924 ExportSpecifier: ['id', 'name'],
4925 ExpressionStatement: ['expression'],
4926 ForStatement: ['init', 'test', 'update', 'body'],
4927 ForInStatement: ['left', 'right', 'body'],
4928 ForOfStatement: ['left', 'right', 'body'],
4929 FunctionDeclaration: ['id', 'params', 'defaults', 'rest', 'body'],
4930 FunctionExpression: ['id', 'params', 'defaults', 'rest', 'body'],
4931 GeneratorExpression: ['blocks', 'filter', 'body'], // CAUTION: It's deferred to ES7.
4932 Identifier: [],
4933 IfStatement: ['test', 'consequent', 'alternate'],
4934 ImportDeclaration: ['specifiers', 'source'],
4935 ImportDefaultSpecifier: ['id'],
4936 ImportNamespaceSpecifier: ['id'],
4937 ImportSpecifier: ['id', 'name'],
4938 Literal: [],
4939 LabeledStatement: ['label', 'body'],
4940 LogicalExpression: ['left', 'right'],
4941 MemberExpression: ['object', 'property'],
4942 MethodDefinition: ['key', 'value'],
4943 ModuleSpecifier: [],
4944 NewExpression: ['callee', 'arguments'],
4945 ObjectExpression: ['properties'],
4946 ObjectPattern: ['properties'],
4947 Program: ['body'],
4948 Property: ['key', 'value'],
4949 ReturnStatement: ['argument'],
4950 SequenceExpression: ['expressions'],
4951 SpreadElement: ['argument'],
4952 SwitchStatement: ['discriminant', 'cases'],
4953 SwitchCase: ['test', 'consequent'],
4954 TaggedTemplateExpression: ['tag', 'quasi'],
4955 TemplateElement: [],
4956 TemplateLiteral: ['quasis', 'expressions'],
4957 ThisExpression: [],
4958 ThrowStatement: ['argument'],
4959 TryStatement: ['block', 'handlers', 'handler', 'guardedHandlers', 'finalizer'],
4960 UnaryExpression: ['argument'],
4961 UpdateExpression: ['argument'],
4962 VariableDeclaration: ['declarations'],
4963 VariableDeclarator: ['id', 'init'],
4964 WhileStatement: ['test', 'body'],
4965 WithStatement: ['object', 'body'],
4966 YieldExpression: ['argument']
4967 };
4968
4969 // unique id
4970 BREAK = {};
4971 SKIP = {};
4972 REMOVE = {};
4973
4974 VisitorOption = {
4975 Break: BREAK,
4976 Skip: SKIP,
4977 Remove: REMOVE
4978 };
4979
4980 function Reference(parent, key) {
4981 this.parent = parent;
4982 this.key = key;
4983 }
4984
4985 Reference.prototype.replace = function replace(node) {
4986 this.parent[this.key] = node;
4987 };
4988
4989 Reference.prototype.remove = function remove() {
4990 if (isArray(this.parent)) {
4991 this.parent.splice(this.key, 1);
4992 return true;
4993 } else {
4994 this.replace(null);
4995 return false;
4996 }
4997 };
4998
4999 function Element(node, path, wrap, ref) {
5000 this.node = node;
5001 this.path = path;
5002 this.wrap = wrap;
5003 this.ref = ref;
5004 }
5005
5006 function Controller() { }
5007
5008 // API:
5009 // return property path array from root to current node
5010 Controller.prototype.path = function path() {
5011 var i, iz, j, jz, result, element;
5012
5013 function addToPath(result, path) {
5014 if (isArray(path)) {
5015 for (j = 0, jz = path.length; j < jz; ++j) {
5016 result.push(path[j]);
5017 }
5018 } else {
5019 result.push(path);
5020 }
5021 }
5022
5023 // root node
5024 if (!this.__current.path) {
5025 return null;
5026 }
5027
5028 // first node is sentinel, second node is root element
5029 result = [];
5030 for (i = 2, iz = this.__leavelist.length; i < iz; ++i) {
5031 element = this.__leavelist[i];
5032 addToPath(result, element.path);
5033 }
5034 addToPath(result, this.__current.path);
5035 return result;
5036 };
5037
5038 // API:
5039 // return type of current node
5040 Controller.prototype.type = function () {
5041 var node = this.current();
5042 return node.type || this.__current.wrap;
5043 };
5044
5045 // API:
5046 // return array of parent elements
5047 Controller.prototype.parents = function parents() {
5048 var i, iz, result;
5049
5050 // first node is sentinel
5051 result = [];
5052 for (i = 1, iz = this.__leavelist.length; i < iz; ++i) {
5053 result.push(this.__leavelist[i].node);
5054 }
5055
5056 return result;
5057 };
5058
5059 // API:
5060 // return current node
5061 Controller.prototype.current = function current() {
5062 return this.__current.node;
5063 };
5064
5065 Controller.prototype.__execute = function __execute(callback, element) {
5066 var previous, result;
5067
5068 result = undefined;
5069
5070 previous = this.__current;
5071 this.__current = element;
5072 this.__state = null;
5073 if (callback) {
5074 result = callback.call(this, element.node, this.__leavelist[this.__leavelist.length - 1].node);
5075 }
5076 this.__current = previous;
5077
5078 return result;
5079 };
5080
5081 // API:
5082 // notify control skip / break
5083 Controller.prototype.notify = function notify(flag) {
5084 this.__state = flag;
5085 };
5086
5087 // API:
5088 // skip child nodes of current node
5089 Controller.prototype.skip = function () {
5090 this.notify(SKIP);
5091 };
5092
5093 // API:
5094 // break traversals
5095 Controller.prototype['break'] = function () {
5096 this.notify(BREAK);
5097 };
5098
5099 // API:
5100 // remove node
5101 Controller.prototype.remove = function () {
5102 this.notify(REMOVE);
5103 };
5104
5105 Controller.prototype.__initialize = function(root, visitor) {
5106 this.visitor = visitor;
5107 this.root = root;
5108 this.__worklist = [];
5109 this.__leavelist = [];
5110 this.__current = null;
5111 this.__state = null;
5112 this.__fallback = visitor.fallback === 'iteration';
5113 this.__keys = VisitorKeys;
5114 if (visitor.keys) {
5115 this.__keys = extend(objectCreate(this.__keys), visitor.keys);
5116 }
5117 };
5118
5119 function isNode(node) {
5120 if (node == null) {
5121 return false;
5122 }
5123 return typeof node === 'object' && typeof node.type === 'string';
5124 }
5125
5126 function isProperty(nodeType, key) {
5127 return (nodeType === Syntax.ObjectExpression || nodeType === Syntax.ObjectPattern) && 'properties' === key;
5128 }
5129
5130 Controller.prototype.traverse = function traverse(root, visitor) {
5131 var worklist,
5132 leavelist,
5133 element,
5134 node,
5135 nodeType,
5136 ret,
5137 key,
5138 current,
5139 current2,
5140 candidates,
5141 candidate,
5142 sentinel;
5143
5144 this.__initialize(root, visitor);
5145
5146 sentinel = {};
5147
5148 // reference
5149 worklist = this.__worklist;
5150 leavelist = this.__leavelist;
5151
5152 // initialize
5153 worklist.push(new Element(root, null, null, null));
5154 leavelist.push(new Element(null, null, null, null));
5155
5156 while (worklist.length) {
5157 element = worklist.pop();
5158
5159 if (element === sentinel) {
5160 element = leavelist.pop();
5161
5162 ret = this.__execute(visitor.leave, element);
5163
5164 if (this.__state === BREAK || ret === BREAK) {
5165 return;
5166 }
5167 continue;
5168 }
5169
5170 if (element.node) {
5171
5172 ret = this.__execute(visitor.enter, element);
5173
5174 if (this.__state === BREAK || ret === BREAK) {
5175 return;
5176 }
5177
5178 worklist.push(sentinel);
5179 leavelist.push(element);
5180
5181 if (this.__state === SKIP || ret === SKIP) {
5182 continue;
5183 }
5184
5185 node = element.node;
5186 nodeType = element.wrap || node.type;
5187 candidates = this.__keys[nodeType];
5188 if (!candidates) {
5189 if (this.__fallback) {
5190 candidates = objectKeys(node);
5191 } else {
5192 throw new Error('Unknown node type ' + nodeType + '.');
5193 }
5194 }
5195
5196 current = candidates.length;
5197 while ((current -= 1) >= 0) {
5198 key = candidates[current];
5199 candidate = node[key];
5200 if (!candidate) {
5201 continue;
5202 }
5203
5204 if (isArray(candidate)) {
5205 current2 = candidate.length;
5206 while ((current2 -= 1) >= 0) {
5207 if (!candidate[current2]) {
5208 continue;
5209 }
5210 if (isProperty(nodeType, candidates[current])) {
5211 element = new Element(candidate[current2], [key, current2], 'Property', null);
5212 } else if (isNode(candidate[current2])) {
5213 element = new Element(candidate[current2], [key, current2], null, null);
5214 } else {
5215 continue;
5216 }
5217 worklist.push(element);
5218 }
5219 } else if (isNode(candidate)) {
5220 worklist.push(new Element(candidate, key, null, null));
5221 }
5222 }
5223 }
5224 }
5225 };
5226
5227 Controller.prototype.replace = function replace(root, visitor) {
5228 function removeElem(element) {
5229 var i,
5230 key,
5231 nextElem,
5232 parent;
5233
5234 if (element.ref.remove()) {
5235 // When the reference is an element of an array.
5236 key = element.ref.key;
5237 parent = element.ref.parent;
5238
5239 // If removed from array, then decrease following items' keys.
5240 i = worklist.length;
5241 while (i--) {
5242 nextElem = worklist[i];
5243 if (nextElem.ref && nextElem.ref.parent === parent) {
5244 if (nextElem.ref.key < key) {
5245 break;
5246 }
5247 --nextElem.ref.key;
5248 }
5249 }
5250 }
5251 }
5252
5253 var worklist,
5254 leavelist,
5255 node,
5256 nodeType,
5257 target,
5258 element,
5259 current,
5260 current2,
5261 candidates,
5262 candidate,
5263 sentinel,
5264 outer,
5265 key;
5266
5267 this.__initialize(root, visitor);
5268
5269 sentinel = {};
5270
5271 // reference
5272 worklist = this.__worklist;
5273 leavelist = this.__leavelist;
5274
5275 // initialize
5276 outer = {
5277 root: root
5278 };
5279 element = new Element(root, null, null, new Reference(outer, 'root'));
5280 worklist.push(element);
5281 leavelist.push(element);
5282
5283 while (worklist.length) {
5284 element = worklist.pop();
5285
5286 if (element === sentinel) {
5287 element = leavelist.pop();
5288
5289 target = this.__execute(visitor.leave, element);
5290
5291 // node may be replaced with null,
5292 // so distinguish between undefined and null in this place
5293 if (target !== undefined && target !== BREAK && target !== SKIP && target !== REMOVE) {
5294 // replace
5295 element.ref.replace(target);
5296 }
5297
5298 if (this.__state === REMOVE || target === REMOVE) {
5299 removeElem(element);
5300 }
5301
5302 if (this.__state === BREAK || target === BREAK) {
5303 return outer.root;
5304 }
5305 continue;
5306 }
5307
5308 target = this.__execute(visitor.enter, element);
5309
5310 // node may be replaced with null,
5311 // so distinguish between undefined and null in this place
5312 if (target !== undefined && target !== BREAK && target !== SKIP && target !== REMOVE) {
5313 // replace
5314 element.ref.replace(target);
5315 element.node = target;
5316 }
5317
5318 if (this.__state === REMOVE || target === REMOVE) {
5319 removeElem(element);
5320 element.node = null;
5321 }
5322
5323 if (this.__state === BREAK || target === BREAK) {
5324 return outer.root;
5325 }
5326
5327 // node may be null
5328 node = element.node;
5329 if (!node) {
5330 continue;
5331 }
5332
5333 worklist.push(sentinel);
5334 leavelist.push(element);
5335
5336 if (this.__state === SKIP || target === SKIP) {
5337 continue;
5338 }
5339
5340 nodeType = element.wrap || node.type;
5341 candidates = this.__keys[nodeType];
5342 if (!candidates) {
5343 if (this.__fallback) {
5344 candidates = objectKeys(node);
5345 } else {
5346 throw new Error('Unknown node type ' + nodeType + '.');
5347 }
5348 }
5349
5350 current = candidates.length;
5351 while ((current -= 1) >= 0) {
5352 key = candidates[current];
5353 candidate = node[key];
5354 if (!candidate) {
5355 continue;
5356 }
5357
5358 if (isArray(candidate)) {
5359 current2 = candidate.length;
5360 while ((current2 -= 1) >= 0) {
5361 if (!candidate[current2]) {
5362 continue;
5363 }
5364 if (isProperty(nodeType, candidates[current])) {
5365 element = new Element(candidate[current2], [key, current2], 'Property', new Reference(candidate, current2));
5366 } else if (isNode(candidate[current2])) {
5367 element = new Element(candidate[current2], [key, current2], null, new Reference(candidate, current2));
5368 } else {
5369 continue;
5370 }
5371 worklist.push(element);
5372 }
5373 } else if (isNode(candidate)) {
5374 worklist.push(new Element(candidate, key, null, new Reference(node, key)));
5375 }
5376 }
5377 }
5378
5379 return outer.root;
5380 };
5381
5382 function traverse(root, visitor) {
5383 var controller = new Controller();
5384 return controller.traverse(root, visitor);
5385 }
5386
5387 function replace(root, visitor) {
5388 var controller = new Controller();
5389 return controller.replace(root, visitor);
5390 }
5391
5392 function extendCommentRange(comment, tokens) {
5393 var target;
5394
5395 target = upperBound(tokens, function search(token) {
5396 return token.range[0] > comment.range[0];
5397 });
5398
5399 comment.extendedRange = [comment.range[0], comment.range[1]];
5400
5401 if (target !== tokens.length) {
5402 comment.extendedRange[1] = tokens[target].range[0];
5403 }
5404
5405 target -= 1;
5406 if (target >= 0) {
5407 comment.extendedRange[0] = tokens[target].range[1];
5408 }
5409
5410 return comment;
5411 }
5412
5413 function attachComments(tree, providedComments, tokens) {
5414 // At first, we should calculate extended comment ranges.
5415 var comments = [], comment, len, i, cursor;
5416
5417 if (!tree.range) {
5418 throw new Error('attachComments needs range information');
5419 }
5420
5421 // tokens array is empty, we attach comments to tree as 'leadingComments'
5422 if (!tokens.length) {
5423 if (providedComments.length) {
5424 for (i = 0, len = providedComments.length; i < len; i += 1) {
5425 comment = deepCopy(providedComments[i]);
5426 comment.extendedRange = [0, tree.range[0]];
5427 comments.push(comment);
5428 }
5429 tree.leadingComments = comments;
5430 }
5431 return tree;
5432 }
5433
5434 for (i = 0, len = providedComments.length; i < len; i += 1) {
5435 comments.push(extendCommentRange(deepCopy(providedComments[i]), tokens));
5436 }
5437
5438 // This is based on John Freeman's implementation.
5439 cursor = 0;
5440 traverse(tree, {
5441 enter: function (node) {
5442 var comment;
5443
5444 while (cursor < comments.length) {
5445 comment = comments[cursor];
5446 if (comment.extendedRange[1] > node.range[0]) {
5447 break;
5448 }
5449
5450 if (comment.extendedRange[1] === node.range[0]) {
5451 if (!node.leadingComments) {
5452 node.leadingComments = [];
5453 }
5454 node.leadingComments.push(comment);
5455 comments.splice(cursor, 1);
5456 } else {
5457 cursor += 1;
5458 }
5459 }
5460
5461 // already out of owned node
5462 if (cursor === comments.length) {
5463 return VisitorOption.Break;
5464 }
5465
5466 if (comments[cursor].extendedRange[0] > node.range[1]) {
5467 return VisitorOption.Skip;
5468 }
5469 }
5470 });
5471
5472 cursor = 0;
5473 traverse(tree, {
5474 leave: function (node) {
5475 var comment;
5476
5477 while (cursor < comments.length) {
5478 comment = comments[cursor];
5479 if (node.range[1] < comment.extendedRange[0]) {
5480 break;
5481 }
5482
5483 if (node.range[1] === comment.extendedRange[0]) {
5484 if (!node.trailingComments) {
5485 node.trailingComments = [];
5486 }
5487 node.trailingComments.push(comment);
5488 comments.splice(cursor, 1);
5489 } else {
5490 cursor += 1;
5491 }
5492 }
5493
5494 // already out of owned node
5495 if (cursor === comments.length) {
5496 return VisitorOption.Break;
5497 }
5498
5499 if (comments[cursor].extendedRange[0] > node.range[1]) {
5500 return VisitorOption.Skip;
5501 }
5502 }
5503 });
5504
5505 return tree;
5506 }
5507
5508 exports.version = '1.8.1-dev';
5509 exports.Syntax = Syntax;
5510 exports.traverse = traverse;
5511 exports.replace = replace;
5512 exports.attachComments = attachComments;
5513 exports.VisitorKeys = VisitorKeys;
5514 exports.VisitorOption = VisitorOption;
5515 exports.Controller = Controller;
5516 exports.cloneEnvironment = function () { return clone({}); };
5517
5518 return exports;
5519}));
5520/* vim: set sw=4 ts=4 et tw=80 : */
5521
5522},{}],70:[function(_dereq_,module,exports){
5523/*
5524 * Copyright 2009-2011 Mozilla Foundation and contributors
5525 * Licensed under the New BSD license. See LICENSE.txt or:
5526 * http://opensource.org/licenses/BSD-3-Clause
5527 */
5528exports.SourceMapGenerator = _dereq_('./source-map/source-map-generator').SourceMapGenerator;
5529exports.SourceMapConsumer = _dereq_('./source-map/source-map-consumer').SourceMapConsumer;
5530exports.SourceNode = _dereq_('./source-map/source-node').SourceNode;
5531
5532},{"./source-map/source-map-consumer":78,"./source-map/source-map-generator":79,"./source-map/source-node":80}],71:[function(_dereq_,module,exports){
5533/* -*- Mode: js; js-indent-level: 2; -*- */
5534/*
5535 * Copyright 2011 Mozilla Foundation and contributors
5536 * Licensed under the New BSD license. See LICENSE or:
5537 * http://opensource.org/licenses/BSD-3-Clause
5538 */
5539if (typeof define !== 'function') {
5540 var define = _dereq_('amdefine')(module, _dereq_);
5541}
5542define(function (_dereq_, exports, module) {
5543
5544 var util = _dereq_('./util');
5545
5546 /**
5547 * A data structure which is a combination of an array and a set. Adding a new
5548 * member is O(1), testing for membership is O(1), and finding the index of an
5549 * element is O(1). Removing elements from the set is not supported. Only
5550 * strings are supported for membership.
5551 */
5552 function ArraySet() {
5553 this._array = [];
5554 this._set = {};
5555 }
5556
5557 /**
5558 * Static method for creating ArraySet instances from an existing array.
5559 */
5560 ArraySet.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) {
5561 var set = new ArraySet();
5562 for (var i = 0, len = aArray.length; i < len; i++) {
5563 set.add(aArray[i], aAllowDuplicates);
5564 }
5565 return set;
5566 };
5567
5568 /**
5569 * Add the given string to this set.
5570 *
5571 * @param String aStr
5572 */
5573 ArraySet.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) {
5574 var isDuplicate = this.has(aStr);
5575 var idx = this._array.length;
5576 if (!isDuplicate || aAllowDuplicates) {
5577 this._array.push(aStr);
5578 }
5579 if (!isDuplicate) {
5580 this._set[util.toSetString(aStr)] = idx;
5581 }
5582 };
5583
5584 /**
5585 * Is the given string a member of this set?
5586 *
5587 * @param String aStr
5588 */
5589 ArraySet.prototype.has = function ArraySet_has(aStr) {
5590 return Object.prototype.hasOwnProperty.call(this._set,
5591 util.toSetString(aStr));
5592 };
5593
5594 /**
5595 * What is the index of the given string in the array?
5596 *
5597 * @param String aStr
5598 */
5599 ArraySet.prototype.indexOf = function ArraySet_indexOf(aStr) {
5600 if (this.has(aStr)) {
5601 return this._set[util.toSetString(aStr)];
5602 }
5603 throw new Error('"' + aStr + '" is not in the set.');
5604 };
5605
5606 /**
5607 * What is the element at the given index?
5608 *
5609 * @param Number aIdx
5610 */
5611 ArraySet.prototype.at = function ArraySet_at(aIdx) {
5612 if (aIdx >= 0 && aIdx < this._array.length) {
5613 return this._array[aIdx];
5614 }
5615 throw new Error('No element indexed by ' + aIdx);
5616 };
5617
5618 /**
5619 * Returns the array representation of this set (which has the proper indices
5620 * indicated by indexOf). Note that this is a copy of the internal array used
5621 * for storing the members so that no one can mess with internal state.
5622 */
5623 ArraySet.prototype.toArray = function ArraySet_toArray() {
5624 return this._array.slice();
5625 };
5626
5627 exports.ArraySet = ArraySet;
5628
5629});
5630
5631},{"./util":81,"amdefine":10}],72:[function(_dereq_,module,exports){
5632/* -*- Mode: js; js-indent-level: 2; -*- */
5633/*
5634 * Copyright 2011 Mozilla Foundation and contributors
5635 * Licensed under the New BSD license. See LICENSE or:
5636 * http://opensource.org/licenses/BSD-3-Clause
5637 *
5638 * Based on the Base 64 VLQ implementation in Closure Compiler:
5639 * https://code.google.com/p/closure-compiler/source/browse/trunk/src/com/google/debugging/sourcemap/Base64VLQ.java
5640 *
5641 * Copyright 2011 The Closure Compiler Authors. All rights reserved.
5642 * Redistribution and use in source and binary forms, with or without
5643 * modification, are permitted provided that the following conditions are
5644 * met:
5645 *
5646 * * Redistributions of source code must retain the above copyright
5647 * notice, this list of conditions and the following disclaimer.
5648 * * Redistributions in binary form must reproduce the above
5649 * copyright notice, this list of conditions and the following
5650 * disclaimer in the documentation and/or other materials provided
5651 * with the distribution.
5652 * * Neither the name of Google Inc. nor the names of its
5653 * contributors may be used to endorse or promote products derived
5654 * from this software without specific prior written permission.
5655 *
5656 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
5657 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
5658 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
5659 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
5660 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
5661 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
5662 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
5663 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
5664 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
5665 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
5666 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
5667 */
5668if (typeof define !== 'function') {
5669 var define = _dereq_('amdefine')(module, _dereq_);
5670}
5671define(function (_dereq_, exports, module) {
5672
5673 var base64 = _dereq_('./base64');
5674
5675 // A single base 64 digit can contain 6 bits of data. For the base 64 variable
5676 // length quantities we use in the source map spec, the first bit is the sign,
5677 // the next four bits are the actual value, and the 6th bit is the
5678 // continuation bit. The continuation bit tells us whether there are more
5679 // digits in this value following this digit.
5680 //
5681 // Continuation
5682 // | Sign
5683 // | |
5684 // V V
5685 // 101011
5686
5687 var VLQ_BASE_SHIFT = 5;
5688
5689 // binary: 100000
5690 var VLQ_BASE = 1 << VLQ_BASE_SHIFT;
5691
5692 // binary: 011111
5693 var VLQ_BASE_MASK = VLQ_BASE - 1;
5694
5695 // binary: 100000
5696 var VLQ_CONTINUATION_BIT = VLQ_BASE;
5697
5698 /**
5699 * Converts from a two-complement value to a value where the sign bit is
5700 * placed in the least significant bit. For example, as decimals:
5701 * 1 becomes 2 (10 binary), -1 becomes 3 (11 binary)
5702 * 2 becomes 4 (100 binary), -2 becomes 5 (101 binary)
5703 */
5704 function toVLQSigned(aValue) {
5705 return aValue < 0
5706 ? ((-aValue) << 1) + 1
5707 : (aValue << 1) + 0;
5708 }
5709
5710 /**
5711 * Converts to a two-complement value from a value where the sign bit is
5712 * placed in the least significant bit. For example, as decimals:
5713 * 2 (10 binary) becomes 1, 3 (11 binary) becomes -1
5714 * 4 (100 binary) becomes 2, 5 (101 binary) becomes -2
5715 */
5716 function fromVLQSigned(aValue) {
5717 var isNegative = (aValue & 1) === 1;
5718 var shifted = aValue >> 1;
5719 return isNegative
5720 ? -shifted
5721 : shifted;
5722 }
5723
5724 /**
5725 * Returns the base 64 VLQ encoded value.
5726 */
5727 exports.encode = function base64VLQ_encode(aValue) {
5728 var encoded = "";
5729 var digit;
5730
5731 var vlq = toVLQSigned(aValue);
5732
5733 do {
5734 digit = vlq & VLQ_BASE_MASK;
5735 vlq >>>= VLQ_BASE_SHIFT;
5736 if (vlq > 0) {
5737 // There are still more digits in this value, so we must make sure the
5738 // continuation bit is marked.
5739 digit |= VLQ_CONTINUATION_BIT;
5740 }
5741 encoded += base64.encode(digit);
5742 } while (vlq > 0);
5743
5744 return encoded;
5745 };
5746
5747 /**
5748 * Decodes the next base 64 VLQ value from the given string and returns the
5749 * value and the rest of the string via the out parameter.
5750 */
5751 exports.decode = function base64VLQ_decode(aStr, aOutParam) {
5752 var i = 0;
5753 var strLen = aStr.length;
5754 var result = 0;
5755 var shift = 0;
5756 var continuation, digit;
5757
5758 do {
5759 if (i >= strLen) {
5760 throw new Error("Expected more digits in base 64 VLQ value.");
5761 }
5762 digit = base64.decode(aStr.charAt(i++));
5763 continuation = !!(digit & VLQ_CONTINUATION_BIT);
5764 digit &= VLQ_BASE_MASK;
5765 result = result + (digit << shift);
5766 shift += VLQ_BASE_SHIFT;
5767 } while (continuation);
5768
5769 aOutParam.value = fromVLQSigned(result);
5770 aOutParam.rest = aStr.slice(i);
5771 };
5772
5773});
5774
5775},{"./base64":73,"amdefine":10}],73:[function(_dereq_,module,exports){
5776/* -*- Mode: js; js-indent-level: 2; -*- */
5777/*
5778 * Copyright 2011 Mozilla Foundation and contributors
5779 * Licensed under the New BSD license. See LICENSE or:
5780 * http://opensource.org/licenses/BSD-3-Clause
5781 */
5782if (typeof define !== 'function') {
5783 var define = _dereq_('amdefine')(module, _dereq_);
5784}
5785define(function (_dereq_, exports, module) {
5786
5787 var charToIntMap = {};
5788 var intToCharMap = {};
5789
5790 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
5791 .split('')
5792 .forEach(function (ch, index) {
5793 charToIntMap[ch] = index;
5794 intToCharMap[index] = ch;
5795 });
5796
5797 /**
5798 * Encode an integer in the range of 0 to 63 to a single base 64 digit.
5799 */
5800 exports.encode = function base64_encode(aNumber) {
5801 if (aNumber in intToCharMap) {
5802 return intToCharMap[aNumber];
5803 }
5804 throw new TypeError("Must be between 0 and 63: " + aNumber);
5805 };
5806
5807 /**
5808 * Decode a single base 64 digit to an integer.
5809 */
5810 exports.decode = function base64_decode(aChar) {
5811 if (aChar in charToIntMap) {
5812 return charToIntMap[aChar];
5813 }
5814 throw new TypeError("Not a valid base 64 digit: " + aChar);
5815 };
5816
5817});
5818
5819},{"amdefine":10}],74:[function(_dereq_,module,exports){
5820/* -*- Mode: js; js-indent-level: 2; -*- */
5821/*
5822 * Copyright 2011 Mozilla Foundation and contributors
5823 * Licensed under the New BSD license. See LICENSE or:
5824 * http://opensource.org/licenses/BSD-3-Clause
5825 */
5826if (typeof define !== 'function') {
5827 var define = _dereq_('amdefine')(module, _dereq_);
5828}
5829define(function (_dereq_, exports, module) {
5830
5831 var util = _dereq_('./util');
5832 var binarySearch = _dereq_('./binary-search');
5833 var ArraySet = _dereq_('./array-set').ArraySet;
5834 var base64VLQ = _dereq_('./base64-vlq');
5835 var SourceMapConsumer = _dereq_('./source-map-consumer').SourceMapConsumer;
5836
5837 /**
5838 * A BasicSourceMapConsumer instance represents a parsed source map which we can
5839 * query for information about the original file positions by giving it a file
5840 * position in the generated source.
5841 *
5842 * The only parameter is the raw source map (either as a JSON string, or
5843 * already parsed to an object). According to the spec, source maps have the
5844 * following attributes:
5845 *
5846 * - version: Which version of the source map spec this map is following.
5847 * - sources: An array of URLs to the original source files.
5848 * - names: An array of identifiers which can be referrenced by individual mappings.
5849 * - sourceRoot: Optional. The URL root from which all sources are relative.
5850 * - sourcesContent: Optional. An array of contents of the original source files.
5851 * - mappings: A string of base64 VLQs which contain the actual mappings.
5852 * - file: Optional. The generated file this source map is associated with.
5853 *
5854 * Here is an example source map, taken from the source map spec[0]:
5855 *
5856 * {
5857 * version : 3,
5858 * file: "out.js",
5859 * sourceRoot : "",
5860 * sources: ["foo.js", "bar.js"],
5861 * names: ["src", "maps", "are", "fun"],
5862 * mappings: "AA,AB;;ABCDE;"
5863 * }
5864 *
5865 * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?pli=1#
5866 */
5867 function BasicSourceMapConsumer(aSourceMap) {
5868 var sourceMap = aSourceMap;
5869 if (typeof aSourceMap === 'string') {
5870 sourceMap = JSON.parse(aSourceMap.replace(/^\)\]\}'/, ''));
5871 }
5872
5873 var version = util.getArg(sourceMap, 'version');
5874 var sources = util.getArg(sourceMap, 'sources');
5875 // Sass 3.3 leaves out the 'names' array, so we deviate from the spec (which
5876 // requires the array) to play nice here.
5877 var names = util.getArg(sourceMap, 'names', []);
5878 var sourceRoot = util.getArg(sourceMap, 'sourceRoot', null);
5879 var sourcesContent = util.getArg(sourceMap, 'sourcesContent', null);
5880 var mappings = util.getArg(sourceMap, 'mappings');
5881 var file = util.getArg(sourceMap, 'file', null);
5882
5883 // Once again, Sass deviates from the spec and supplies the version as a
5884 // string rather than a number, so we use loose equality checking here.
5885 if (version != this._version) {
5886 throw new Error('Unsupported version: ' + version);
5887 }
5888
5889 // Some source maps produce relative source paths like "./foo.js" instead of
5890 // "foo.js". Normalize these first so that future comparisons will succeed.
5891 // See bugzil.la/1090768.
5892 sources = sources.map(util.normalize);
5893
5894 // Pass `true` below to allow duplicate names and sources. While source maps
5895 // are intended to be compressed and deduplicated, the TypeScript compiler
5896 // sometimes generates source maps with duplicates in them. See Github issue
5897 // #72 and bugzil.la/889492.
5898 this._names = ArraySet.fromArray(names, true);
5899 this._sources = ArraySet.fromArray(sources, true);
5900
5901 this.sourceRoot = sourceRoot;
5902 this.sourcesContent = sourcesContent;
5903 this._mappings = mappings;
5904 this.file = file;
5905 }
5906
5907 BasicSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype);
5908 BasicSourceMapConsumer.prototype.consumer = SourceMapConsumer;
5909
5910 /**
5911 * Create a BasicSourceMapConsumer from a SourceMapGenerator.
5912 *
5913 * @param SourceMapGenerator aSourceMap
5914 * The source map that will be consumed.
5915 * @returns BasicSourceMapConsumer
5916 */
5917 BasicSourceMapConsumer.fromSourceMap =
5918 function SourceMapConsumer_fromSourceMap(aSourceMap) {
5919 var smc = Object.create(BasicSourceMapConsumer.prototype);
5920
5921 smc._names = ArraySet.fromArray(aSourceMap._names.toArray(), true);
5922 smc._sources = ArraySet.fromArray(aSourceMap._sources.toArray(), true);
5923 smc.sourceRoot = aSourceMap._sourceRoot;
5924 smc.sourcesContent = aSourceMap._generateSourcesContent(smc._sources.toArray(),
5925 smc.sourceRoot);
5926 smc.file = aSourceMap._file;
5927
5928 smc.__generatedMappings = aSourceMap._mappings.toArray().slice();
5929 smc.__originalMappings = aSourceMap._mappings.toArray().slice()
5930 .sort(util.compareByOriginalPositions);
5931
5932 return smc;
5933 };
5934
5935 /**
5936 * The version of the source mapping spec that we are consuming.
5937 */
5938 BasicSourceMapConsumer.prototype._version = 3;
5939
5940 /**
5941 * The list of original sources.
5942 */
5943 Object.defineProperty(BasicSourceMapConsumer.prototype, 'sources', {
5944 get: function () {
5945 return this._sources.toArray().map(function (s) {
5946 return this.sourceRoot != null ? util.join(this.sourceRoot, s) : s;
5947 }, this);
5948 }
5949 });
5950
5951 /**
5952 * Parse the mappings in a string in to a data structure which we can easily
5953 * query (the ordered arrays in the `this.__generatedMappings` and
5954 * `this.__originalMappings` properties).
5955 */
5956 BasicSourceMapConsumer.prototype._parseMappings =
5957 function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {
5958 var generatedLine = 1;
5959 var previousGeneratedColumn = 0;
5960 var previousOriginalLine = 0;
5961 var previousOriginalColumn = 0;
5962 var previousSource = 0;
5963 var previousName = 0;
5964 var str = aStr;
5965 var temp = {};
5966 var mapping;
5967
5968 while (str.length > 0) {
5969 if (str.charAt(0) === ';') {
5970 generatedLine++;
5971 str = str.slice(1);
5972 previousGeneratedColumn = 0;
5973 }
5974 else if (str.charAt(0) === ',') {
5975 str = str.slice(1);
5976 }
5977 else {
5978 mapping = {};
5979 mapping.generatedLine = generatedLine;
5980
5981 // Generated column.
5982 base64VLQ.decode(str, temp);
5983 mapping.generatedColumn = previousGeneratedColumn + temp.value;
5984 previousGeneratedColumn = mapping.generatedColumn;
5985 str = temp.rest;
5986
5987 if (str.length > 0 && !this._nextCharIsMappingSeparator(str)) {
5988 // Original source.
5989 base64VLQ.decode(str, temp);
5990 mapping.source = this._sources.at(previousSource + temp.value);
5991 previousSource += temp.value;
5992 str = temp.rest;
5993 if (str.length === 0 || this._nextCharIsMappingSeparator(str)) {
5994 throw new Error('Found a source, but no line and column');
5995 }
5996
5997 // Original line.
5998 base64VLQ.decode(str, temp);
5999 mapping.originalLine = previousOriginalLine + temp.value;
6000 previousOriginalLine = mapping.originalLine;
6001 // Lines are stored 0-based
6002 mapping.originalLine += 1;
6003 str = temp.rest;
6004 if (str.length === 0 || this._nextCharIsMappingSeparator(str)) {
6005 throw new Error('Found a source and line, but no column');
6006 }
6007
6008 // Original column.
6009 base64VLQ.decode(str, temp);
6010 mapping.originalColumn = previousOriginalColumn + temp.value;
6011 previousOriginalColumn = mapping.originalColumn;
6012 str = temp.rest;
6013
6014 if (str.length > 0 && !this._nextCharIsMappingSeparator(str)) {
6015 // Original name.
6016 base64VLQ.decode(str, temp);
6017 mapping.name = this._names.at(previousName + temp.value);
6018 previousName += temp.value;
6019 str = temp.rest;
6020 }
6021 }
6022
6023 this.__generatedMappings.push(mapping);
6024 if (typeof mapping.originalLine === 'number') {
6025 this.__originalMappings.push(mapping);
6026 }
6027 }
6028 }
6029
6030 this.__generatedMappings.sort(util.compareByGeneratedPositions);
6031 this.__originalMappings.sort(util.compareByOriginalPositions);
6032 };
6033
6034 /**
6035 * Find the mapping that best matches the hypothetical "needle" mapping that
6036 * we are searching for in the given "haystack" of mappings.
6037 */
6038 BasicSourceMapConsumer.prototype._findMapping =
6039 function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName,
6040 aColumnName, aComparator) {
6041 // To return the position we are searching for, we must first find the
6042 // mapping for the given position and then return the opposite position it
6043 // points to. Because the mappings are sorted, we can use binary search to
6044 // find the best mapping.
6045
6046 if (aNeedle[aLineName] <= 0) {
6047 throw new TypeError('Line must be greater than or equal to 1, got '
6048 + aNeedle[aLineName]);
6049 }
6050 if (aNeedle[aColumnName] < 0) {
6051 throw new TypeError('Column must be greater than or equal to 0, got '
6052 + aNeedle[aColumnName]);
6053 }
6054
6055 return binarySearch.search(aNeedle, aMappings, aComparator);
6056 };
6057
6058 /**
6059 * Compute the last column for each generated mapping. The last column is
6060 * inclusive.
6061 */
6062 BasicSourceMapConsumer.prototype.computeColumnSpans =
6063 function SourceMapConsumer_computeColumnSpans() {
6064 for (var index = 0; index < this._generatedMappings.length; ++index) {
6065 var mapping = this._generatedMappings[index];
6066
6067 // Mappings do not contain a field for the last generated columnt. We
6068 // can come up with an optimistic estimate, however, by assuming that
6069 // mappings are contiguous (i.e. given two consecutive mappings, the
6070 // first mapping ends where the second one starts).
6071 if (index + 1 < this._generatedMappings.length) {
6072 var nextMapping = this._generatedMappings[index + 1];
6073
6074 if (mapping.generatedLine === nextMapping.generatedLine) {
6075 mapping.lastGeneratedColumn = nextMapping.generatedColumn - 1;
6076 continue;
6077 }
6078 }
6079
6080 // The last mapping for each line spans the entire line.
6081 mapping.lastGeneratedColumn = Infinity;
6082 }
6083 };
6084
6085 /**
6086 * Returns the original source, line, and column information for the generated
6087 * source's line and column positions provided. The only argument is an object
6088 * with the following properties:
6089 *
6090 * - line: The line number in the generated source.
6091 * - column: The column number in the generated source.
6092 *
6093 * and an object is returned with the following properties:
6094 *
6095 * - source: The original source file, or null.
6096 * - line: The line number in the original source, or null.
6097 * - column: The column number in the original source, or null.
6098 * - name: The original identifier, or null.
6099 */
6100 BasicSourceMapConsumer.prototype.originalPositionFor =
6101 function SourceMapConsumer_originalPositionFor(aArgs) {
6102 var needle = {
6103 generatedLine: util.getArg(aArgs, 'line'),
6104 generatedColumn: util.getArg(aArgs, 'column')
6105 };
6106
6107 var index = this._findMapping(needle,
6108 this._generatedMappings,
6109 "generatedLine",
6110 "generatedColumn",
6111 util.compareByGeneratedPositions);
6112
6113 if (index >= 0) {
6114 var mapping = this._generatedMappings[index];
6115
6116 if (mapping.generatedLine === needle.generatedLine) {
6117 var source = util.getArg(mapping, 'source', null);
6118 if (source != null && this.sourceRoot != null) {
6119 source = util.join(this.sourceRoot, source);
6120 }
6121 return {
6122 source: source,
6123 line: util.getArg(mapping, 'originalLine', null),
6124 column: util.getArg(mapping, 'originalColumn', null),
6125 name: util.getArg(mapping, 'name', null)
6126 };
6127 }
6128 }
6129
6130 return {
6131 source: null,
6132 line: null,
6133 column: null,
6134 name: null
6135 };
6136 };
6137
6138 /**
6139 * Returns the original source content. The only argument is the url of the
6140 * original source file. Returns null if no original source content is
6141 * availible.
6142 */
6143 BasicSourceMapConsumer.prototype.sourceContentFor =
6144 function SourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {
6145 if (!this.sourcesContent) {
6146 return null;
6147 }
6148
6149 if (this.sourceRoot != null) {
6150 aSource = util.relative(this.sourceRoot, aSource);
6151 }
6152
6153 if (this._sources.has(aSource)) {
6154 return this.sourcesContent[this._sources.indexOf(aSource)];
6155 }
6156
6157 var url;
6158 if (this.sourceRoot != null
6159 && (url = util.urlParse(this.sourceRoot))) {
6160 // XXX: file:// URIs and absolute paths lead to unexpected behavior for
6161 // many users. We can help them out when they expect file:// URIs to
6162 // behave like it would if they were running a local HTTP server. See
6163 // https://bugzilla.mozilla.org/show_bug.cgi?id=885597.
6164 var fileUriAbsPath = aSource.replace(/^file:\/\//, "");
6165 if (url.scheme == "file"
6166 && this._sources.has(fileUriAbsPath)) {
6167 return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)]
6168 }
6169
6170 if ((!url.path || url.path == "/")
6171 && this._sources.has("/" + aSource)) {
6172 return this.sourcesContent[this._sources.indexOf("/" + aSource)];
6173 }
6174 }
6175
6176 // This function is used recursively from
6177 // IndexedSourceMapConsumer.prototype.sourceContentFor. In that case, we
6178 // don't want to throw if we can't find the source - we just want to
6179 // return null, so we provide a flag to exit gracefully.
6180 if (nullOnMissing) {
6181 return null;
6182 }
6183 else {
6184 throw new Error('"' + aSource + '" is not in the SourceMap.');
6185 }
6186 };
6187
6188 /**
6189 * Returns the generated line and column information for the original source,
6190 * line, and column positions provided. The only argument is an object with
6191 * the following properties:
6192 *
6193 * - source: The filename of the original source.
6194 * - line: The line number in the original source.
6195 * - column: The column number in the original source.
6196 *
6197 * and an object is returned with the following properties:
6198 *
6199 * - line: The line number in the generated source, or null.
6200 * - column: The column number in the generated source, or null.
6201 */
6202 BasicSourceMapConsumer.prototype.generatedPositionFor =
6203 function SourceMapConsumer_generatedPositionFor(aArgs) {
6204 var needle = {
6205 source: util.getArg(aArgs, 'source'),
6206 originalLine: util.getArg(aArgs, 'line'),
6207 originalColumn: util.getArg(aArgs, 'column')
6208 };
6209
6210 if (this.sourceRoot != null) {
6211 needle.source = util.relative(this.sourceRoot, needle.source);
6212 }
6213
6214 var index = this._findMapping(needle,
6215 this._originalMappings,
6216 "originalLine",
6217 "originalColumn",
6218 util.compareByOriginalPositions);
6219
6220 if (index >= 0) {
6221 var mapping = this._originalMappings[index];
6222
6223 return {
6224 line: util.getArg(mapping, 'generatedLine', null),
6225 column: util.getArg(mapping, 'generatedColumn', null),
6226 lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)
6227 };
6228 }
6229
6230 return {
6231 line: null,
6232 column: null,
6233 lastColumn: null
6234 };
6235 };
6236
6237 exports.BasicSourceMapConsumer = BasicSourceMapConsumer;
6238
6239});
6240
6241},{"./array-set":71,"./base64-vlq":72,"./binary-search":75,"./source-map-consumer":78,"./util":81,"amdefine":10}],75:[function(_dereq_,module,exports){
6242/* -*- Mode: js; js-indent-level: 2; -*- */
6243/*
6244 * Copyright 2011 Mozilla Foundation and contributors
6245 * Licensed under the New BSD license. See LICENSE or:
6246 * http://opensource.org/licenses/BSD-3-Clause
6247 */
6248if (typeof define !== 'function') {
6249 var define = _dereq_('amdefine')(module, _dereq_);
6250}
6251define(function (_dereq_, exports, module) {
6252
6253 /**
6254 * Recursive implementation of binary search.
6255 *
6256 * @param aLow Indices here and lower do not contain the needle.
6257 * @param aHigh Indices here and higher do not contain the needle.
6258 * @param aNeedle The element being searched for.
6259 * @param aHaystack The non-empty array being searched.
6260 * @param aCompare Function which takes two elements and returns -1, 0, or 1.
6261 */
6262 function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare) {
6263 // This function terminates when one of the following is true:
6264 //
6265 // 1. We find the exact element we are looking for.
6266 //
6267 // 2. We did not find the exact element, but we can return the index of
6268 // the next closest element that is less than that element.
6269 //
6270 // 3. We did not find the exact element, and there is no next-closest
6271 // element which is less than the one we are searching for, so we
6272 // return -1.
6273 var mid = Math.floor((aHigh - aLow) / 2) + aLow;
6274 var cmp = aCompare(aNeedle, aHaystack[mid], true);
6275 if (cmp === 0) {
6276 // Found the element we are looking for.
6277 return mid;
6278 }
6279 else if (cmp > 0) {
6280 // aHaystack[mid] is greater than our needle.
6281 if (aHigh - mid > 1) {
6282 // The element is in the upper half.
6283 return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare);
6284 }
6285 // We did not find an exact match, return the next closest one
6286 // (termination case 2).
6287 return mid;
6288 }
6289 else {
6290 // aHaystack[mid] is less than our needle.
6291 if (mid - aLow > 1) {
6292 // The element is in the lower half.
6293 return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare);
6294 }
6295 // The exact needle element was not found in this haystack. Determine if
6296 // we are in termination case (2) or (3) and return the appropriate thing.
6297 return aLow < 0 ? -1 : aLow;
6298 }
6299 }
6300
6301 /**
6302 * This is an implementation of binary search which will always try and return
6303 * the index of next lowest value checked if there is no exact hit. This is
6304 * because mappings between original and generated line/col pairs are single
6305 * points, and there is an implicit region between each of them, so a miss
6306 * just means that you aren't on the very start of a region.
6307 *
6308 * @param aNeedle The element you are looking for.
6309 * @param aHaystack The array that is being searched.
6310 * @param aCompare A function which takes the needle and an element in the
6311 * array and returns -1, 0, or 1 depending on whether the needle is less
6312 * than, equal to, or greater than the element, respectively.
6313 */
6314 exports.search = function search(aNeedle, aHaystack, aCompare) {
6315 if (aHaystack.length === 0) {
6316 return -1;
6317 }
6318 return recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack, aCompare)
6319 };
6320
6321});
6322
6323},{"amdefine":10}],76:[function(_dereq_,module,exports){
6324/* -*- Mode: js; js-indent-level: 2; -*- */
6325/*
6326 * Copyright 2011 Mozilla Foundation and contributors
6327 * Licensed under the New BSD license. See LICENSE or:
6328 * http://opensource.org/licenses/BSD-3-Clause
6329 */
6330if (typeof define !== 'function') {
6331 var define = _dereq_('amdefine')(module, _dereq_);
6332}
6333define(function (_dereq_, exports, module) {
6334
6335 var util = _dereq_('./util');
6336 var binarySearch = _dereq_('./binary-search');
6337 var SourceMapConsumer = _dereq_('./source-map-consumer').SourceMapConsumer;
6338 var BasicSourceMapConsumer = _dereq_('./basic-source-map-consumer').BasicSourceMapConsumer;
6339
6340 /**
6341 * An IndexedSourceMapConsumer instance represents a parsed source map which
6342 * we can query for information. It differs from BasicSourceMapConsumer in
6343 * that it takes "indexed" source maps (i.e. ones with a "sections" field) as
6344 * input.
6345 *
6346 * The only parameter is a raw source map (either as a JSON string, or already
6347 * parsed to an object). According to the spec for indexed source maps, they
6348 * have the following attributes:
6349 *
6350 * - version: Which version of the source map spec this map is following.
6351 * - file: Optional. The generated file this source map is associated with.
6352 * - sections: A list of section definitions.
6353 *
6354 * Each value under the "sections" field has two fields:
6355 * - offset: The offset into the original specified at which this section
6356 * begins to apply, defined as an object with a "line" and "column"
6357 * field.
6358 * - map: A source map definition. This source map could also be indexed,
6359 * but doesn't have to be.
6360 *
6361 * Instead of the "map" field, it's also possible to have a "url" field
6362 * specifying a URL to retrieve a source map from, but that's currently
6363 * unsupported.
6364 *
6365 * Here's an example source map, taken from the source map spec[0], but
6366 * modified to omit a section which uses the "url" field.
6367 *
6368 * {
6369 * version : 3,
6370 * file: "app.js",
6371 * sections: [{
6372 * offset: {line:100, column:10},
6373 * map: {
6374 * version : 3,
6375 * file: "section.js",
6376 * sources: ["foo.js", "bar.js"],
6377 * names: ["src", "maps", "are", "fun"],
6378 * mappings: "AAAA,E;;ABCDE;"
6379 * }
6380 * }],
6381 * }
6382 *
6383 * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit#heading=h.535es3xeprgt
6384 */
6385 function IndexedSourceMapConsumer(aSourceMap) {
6386 var sourceMap = aSourceMap;
6387 if (typeof aSourceMap === 'string') {
6388 sourceMap = JSON.parse(aSourceMap.replace(/^\)\]\}'/, ''));
6389 }
6390
6391 var version = util.getArg(sourceMap, 'version');
6392 var sections = util.getArg(sourceMap, 'sections');
6393
6394 if (version != this._version) {
6395 throw new Error('Unsupported version: ' + version);
6396 }
6397
6398 var lastOffset = {
6399 line: -1,
6400 column: 0
6401 };
6402 this._sections = sections.map(function (s) {
6403 if (s.url) {
6404 // The url field will require support for asynchronicity.
6405 // See https://github.com/mozilla/source-map/issues/16
6406 throw new Error('Support for url field in sections not implemented.');
6407 }
6408 var offset = util.getArg(s, 'offset');
6409 var offsetLine = util.getArg(offset, 'line');
6410 var offsetColumn = util.getArg(offset, 'column');
6411
6412 if (offsetLine < lastOffset.line ||
6413 (offsetLine === lastOffset.line && offsetColumn < lastOffset.column)) {
6414 throw new Error('Section offsets must be ordered and non-overlapping.');
6415 }
6416 lastOffset = offset;
6417
6418 return {
6419 generatedOffset: {
6420 // The offset fields are 0-based, but we use 1-based indices when
6421 // encoding/decoding from VLQ.
6422 generatedLine: offsetLine + 1,
6423 generatedColumn: offsetColumn + 1
6424 },
6425 consumer: new SourceMapConsumer(util.getArg(s, 'map'))
6426 }
6427 });
6428 }
6429
6430 IndexedSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype);
6431 IndexedSourceMapConsumer.prototype.constructor = SourceMapConsumer;
6432
6433 /**
6434 * The version of the source mapping spec that we are consuming.
6435 */
6436 IndexedSourceMapConsumer.prototype._version = 3;
6437
6438 /**
6439 * The list of original sources.
6440 */
6441 Object.defineProperty(IndexedSourceMapConsumer.prototype, 'sources', {
6442 get: function () {
6443 var sources = [];
6444 for (var i = 0; i < this._sections.length; i++) {
6445 for (var j = 0; j < this._sections[i].consumer.sources.length; j++) {
6446 sources.push(this._sections[i].consumer.sources[j]);
6447 }
6448 };
6449 return sources;
6450 }
6451 });
6452
6453 /**
6454 * Returns the original source, line, and column information for the generated
6455 * source's line and column positions provided. The only argument is an object
6456 * with the following properties:
6457 *
6458 * - line: The line number in the generated source.
6459 * - column: The column number in the generated source.
6460 *
6461 * and an object is returned with the following properties:
6462 *
6463 * - source: The original source file, or null.
6464 * - line: The line number in the original source, or null.
6465 * - column: The column number in the original source, or null.
6466 * - name: The original identifier, or null.
6467 */
6468 IndexedSourceMapConsumer.prototype.originalPositionFor =
6469 function IndexedSourceMapConsumer_originalPositionFor(aArgs) {
6470 var needle = {
6471 generatedLine: util.getArg(aArgs, 'line'),
6472 generatedColumn: util.getArg(aArgs, 'column')
6473 };
6474
6475 // Find the section containing the generated position we're trying to map
6476 // to an original position.
6477 var sectionIndex = binarySearch.search(needle, this._sections,
6478 function(needle, section) {
6479 var cmp = needle.generatedLine - section.generatedOffset.generatedLine;
6480 if (cmp) {
6481 return cmp;
6482 }
6483
6484 return (needle.generatedColumn -
6485 section.generatedOffset.generatedColumn);
6486 });
6487 var section = this._sections[sectionIndex];
6488
6489 if (!section) {
6490 return {
6491 source: null,
6492 line: null,
6493 column: null,
6494 name: null
6495 };
6496 }
6497
6498 return section.consumer.originalPositionFor({
6499 line: needle.generatedLine -
6500 (section.generatedOffset.generatedLine - 1),
6501 column: needle.generatedColumn -
6502 (section.generatedOffset.generatedLine === needle.generatedLine
6503 ? section.generatedOffset.generatedColumn - 1
6504 : 0)
6505 });
6506 };
6507
6508 /**
6509 * Returns the original source content. The only argument is the url of the
6510 * original source file. Returns null if no original source content is
6511 * available.
6512 */
6513 IndexedSourceMapConsumer.prototype.sourceContentFor =
6514 function IndexedSourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {
6515 for (var i = 0; i < this._sections.length; i++) {
6516 var section = this._sections[i];
6517
6518 var content = section.consumer.sourceContentFor(aSource, true);
6519 if (content) {
6520 return content;
6521 }
6522 }
6523 if (nullOnMissing) {
6524 return null;
6525 }
6526 else {
6527 throw new Error('"' + aSource + '" is not in the SourceMap.');
6528 }
6529 };
6530
6531 /**
6532 * Returns the generated line and column information for the original source,
6533 * line, and column positions provided. The only argument is an object with
6534 * the following properties:
6535 *
6536 * - source: The filename of the original source.
6537 * - line: The line number in the original source.
6538 * - column: The column number in the original source.
6539 *
6540 * and an object is returned with the following properties:
6541 *
6542 * - line: The line number in the generated source, or null.
6543 * - column: The column number in the generated source, or null.
6544 */
6545 IndexedSourceMapConsumer.prototype.generatedPositionFor =
6546 function IndexedSourceMapConsumer_generatedPositionFor(aArgs) {
6547 for (var i = 0; i < this._sections.length; i++) {
6548 var section = this._sections[i];
6549
6550 // Only consider this section if the requested source is in the list of
6551 // sources of the consumer.
6552 if (section.consumer.sources.indexOf(util.getArg(aArgs, 'source')) === -1) {
6553 continue;
6554 }
6555 var generatedPosition = section.consumer.generatedPositionFor(aArgs);
6556 if (generatedPosition) {
6557 var ret = {
6558 line: generatedPosition.line +
6559 (section.generatedOffset.generatedLine - 1),
6560 column: generatedPosition.column +
6561 (section.generatedOffset.generatedLine === generatedPosition.line
6562 ? section.generatedOffset.generatedColumn - 1
6563 : 0)
6564 };
6565 return ret;
6566 }
6567 }
6568
6569 return {
6570 line: null,
6571 column: null
6572 };
6573 };
6574
6575 /**
6576 * Parse the mappings in a string in to a data structure which we can easily
6577 * query (the ordered arrays in the `this.__generatedMappings` and
6578 * `this.__originalMappings` properties).
6579 */
6580 IndexedSourceMapConsumer.prototype._parseMappings =
6581 function IndexedSourceMapConsumer_parseMappings(aStr, aSourceRoot) {
6582 this.__generatedMappings = [];
6583 this.__originalMappings = [];
6584 for (var i = 0; i < this._sections.length; i++) {
6585 var section = this._sections[i];
6586 var sectionMappings = section.consumer._generatedMappings;
6587 for (var j = 0; j < sectionMappings.length; j++) {
6588 var mapping = sectionMappings[i];
6589
6590 var source = mapping.source;
6591 var sourceRoot = section.consumer.sourceRoot;
6592
6593 if (source != null && sourceRoot != null) {
6594 source = util.join(sourceRoot, source);
6595 }
6596
6597 // The mappings coming from the consumer for the section have
6598 // generated positions relative to the start of the section, so we
6599 // need to offset them to be relative to the start of the concatenated
6600 // generated file.
6601 var adjustedMapping = {
6602 source: source,
6603 generatedLine: mapping.generatedLine +
6604 (section.generatedOffset.generatedLine - 1),
6605 generatedColumn: mapping.column +
6606 (section.generatedOffset.generatedLine === mapping.generatedLine)
6607 ? section.generatedOffset.generatedColumn - 1
6608 : 0,
6609 originalLine: mapping.originalLine,
6610 originalColumn: mapping.originalColumn,
6611 name: mapping.name
6612 };
6613
6614 this.__generatedMappings.push(adjustedMapping);
6615 if (typeof adjustedMapping.originalLine === 'number') {
6616 this.__originalMappings.push(adjustedMapping);
6617 }
6618 };
6619 };
6620
6621 this.__generatedMappings.sort(util.compareByGeneratedPositions);
6622 this.__originalMappings.sort(util.compareByOriginalPositions);
6623 };
6624
6625 exports.IndexedSourceMapConsumer = IndexedSourceMapConsumer;
6626});
6627
6628},{"./basic-source-map-consumer":74,"./binary-search":75,"./source-map-consumer":78,"./util":81,"amdefine":10}],77:[function(_dereq_,module,exports){
6629/* -*- Mode: js; js-indent-level: 2; -*- */
6630/*
6631 * Copyright 2014 Mozilla Foundation and contributors
6632 * Licensed under the New BSD license. See LICENSE or:
6633 * http://opensource.org/licenses/BSD-3-Clause
6634 */
6635if (typeof define !== 'function') {
6636 var define = _dereq_('amdefine')(module, _dereq_);
6637}
6638define(function (_dereq_, exports, module) {
6639
6640 var util = _dereq_('./util');
6641
6642 /**
6643 * Determine whether mappingB is after mappingA with respect to generated
6644 * position.
6645 */
6646 function generatedPositionAfter(mappingA, mappingB) {
6647 // Optimized for most common case
6648 var lineA = mappingA.generatedLine;
6649 var lineB = mappingB.generatedLine;
6650 var columnA = mappingA.generatedColumn;
6651 var columnB = mappingB.generatedColumn;
6652 return lineB > lineA || lineB == lineA && columnB >= columnA ||
6653 util.compareByGeneratedPositions(mappingA, mappingB) <= 0;
6654 }
6655
6656 /**
6657 * A data structure to provide a sorted view of accumulated mappings in a
6658 * performance conscious manner. It trades a neglibable overhead in general
6659 * case for a large speedup in case of mappings being added in order.
6660 */
6661 function MappingList() {
6662 this._array = [];
6663 this._sorted = true;
6664 // Serves as infimum
6665 this._last = {generatedLine: -1, generatedColumn: 0};
6666 }
6667
6668 /**
6669 * Iterate through internal items. This method takes the same arguments that
6670 * `Array.prototype.forEach` takes.
6671 *
6672 * NOTE: The order of the mappings is NOT guaranteed.
6673 */
6674 MappingList.prototype.unsortedForEach =
6675 function MappingList_forEach(aCallback, aThisArg) {
6676 this._array.forEach(aCallback, aThisArg);
6677 };
6678
6679 /**
6680 * Add the given source mapping.
6681 *
6682 * @param Object aMapping
6683 */
6684 MappingList.prototype.add = function MappingList_add(aMapping) {
6685 var mapping;
6686 if (generatedPositionAfter(this._last, aMapping)) {
6687 this._last = aMapping;
6688 this._array.push(aMapping);
6689 } else {
6690 this._sorted = false;
6691 this._array.push(aMapping);
6692 }
6693 };
6694
6695 /**
6696 * Returns the flat, sorted array of mappings. The mappings are sorted by
6697 * generated position.
6698 *
6699 * WARNING: This method returns internal data without copying, for
6700 * performance. The return value must NOT be mutated, and should be treated as
6701 * an immutable borrow. If you want to take ownership, you must make your own
6702 * copy.
6703 */
6704 MappingList.prototype.toArray = function MappingList_toArray() {
6705 if (!this._sorted) {
6706 this._array.sort(util.compareByGeneratedPositions);
6707 this._sorted = true;
6708 }
6709 return this._array;
6710 };
6711
6712 exports.MappingList = MappingList;
6713
6714});
6715
6716},{"./util":81,"amdefine":10}],78:[function(_dereq_,module,exports){
6717/* -*- Mode: js; js-indent-level: 2; -*- */
6718/*
6719 * Copyright 2011 Mozilla Foundation and contributors
6720 * Licensed under the New BSD license. See LICENSE or:
6721 * http://opensource.org/licenses/BSD-3-Clause
6722 */
6723if (typeof define !== 'function') {
6724 var define = _dereq_('amdefine')(module, _dereq_);
6725}
6726define(function (_dereq_, exports, module) {
6727
6728 var util = _dereq_('./util');
6729
6730 function SourceMapConsumer(aSourceMap) {
6731 var sourceMap = aSourceMap;
6732 if (typeof aSourceMap === 'string') {
6733 sourceMap = JSON.parse(aSourceMap.replace(/^\)\]\}'/, ''));
6734 }
6735
6736 // We do late requires because the subclasses require() this file.
6737 if (sourceMap.sections != null) {
6738 var indexedSourceMapConsumer = _dereq_('./indexed-source-map-consumer');
6739 return new indexedSourceMapConsumer.IndexedSourceMapConsumer(sourceMap);
6740 } else {
6741 var basicSourceMapConsumer = _dereq_('./basic-source-map-consumer');
6742 return new basicSourceMapConsumer.BasicSourceMapConsumer(sourceMap);
6743 }
6744 }
6745
6746 SourceMapConsumer.fromSourceMap = function(aSourceMap) {
6747 var basicSourceMapConsumer = _dereq_('./basic-source-map-consumer');
6748 return basicSourceMapConsumer.BasicSourceMapConsumer
6749 .fromSourceMap(aSourceMap);
6750 }
6751
6752 /**
6753 * The version of the source mapping spec that we are consuming.
6754 */
6755 SourceMapConsumer.prototype._version = 3;
6756
6757
6758 // `__generatedMappings` and `__originalMappings` are arrays that hold the
6759 // parsed mapping coordinates from the source map's "mappings" attribute. They
6760 // are lazily instantiated, accessed via the `_generatedMappings` and
6761 // `_originalMappings` getters respectively, and we only parse the mappings
6762 // and create these arrays once queried for a source location. We jump through
6763 // these hoops because there can be many thousands of mappings, and parsing
6764 // them is expensive, so we only want to do it if we must.
6765 //
6766 // Each object in the arrays is of the form:
6767 //
6768 // {
6769 // generatedLine: The line number in the generated code,
6770 // generatedColumn: The column number in the generated code,
6771 // source: The path to the original source file that generated this
6772 // chunk of code,
6773 // originalLine: The line number in the original source that
6774 // corresponds to this chunk of generated code,
6775 // originalColumn: The column number in the original source that
6776 // corresponds to this chunk of generated code,
6777 // name: The name of the original symbol which generated this chunk of
6778 // code.
6779 // }
6780 //
6781 // All properties except for `generatedLine` and `generatedColumn` can be
6782 // `null`.
6783 //
6784 // `_generatedMappings` is ordered by the generated positions.
6785 //
6786 // `_originalMappings` is ordered by the original positions.
6787
6788 SourceMapConsumer.prototype.__generatedMappings = null;
6789 Object.defineProperty(SourceMapConsumer.prototype, '_generatedMappings', {
6790 get: function () {
6791 if (!this.__generatedMappings) {
6792 this.__generatedMappings = [];
6793 this.__originalMappings = [];
6794 this._parseMappings(this._mappings, this.sourceRoot);
6795 }
6796
6797 return this.__generatedMappings;
6798 }
6799 });
6800
6801 SourceMapConsumer.prototype.__originalMappings = null;
6802 Object.defineProperty(SourceMapConsumer.prototype, '_originalMappings', {
6803 get: function () {
6804 if (!this.__originalMappings) {
6805 this.__generatedMappings = [];
6806 this.__originalMappings = [];
6807 this._parseMappings(this._mappings, this.sourceRoot);
6808 }
6809
6810 return this.__originalMappings;
6811 }
6812 });
6813
6814 SourceMapConsumer.prototype._nextCharIsMappingSeparator =
6815 function SourceMapConsumer_nextCharIsMappingSeparator(aStr) {
6816 var c = aStr.charAt(0);
6817 return c === ";" || c === ",";
6818 };
6819
6820 /**
6821 * Parse the mappings in a string in to a data structure which we can easily
6822 * query (the ordered arrays in the `this.__generatedMappings` and
6823 * `this.__originalMappings` properties).
6824 */
6825 SourceMapConsumer.prototype._parseMappings =
6826 function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {
6827 throw new Error("Subclasses must implement _parseMappings");
6828 };
6829
6830 SourceMapConsumer.GENERATED_ORDER = 1;
6831 SourceMapConsumer.ORIGINAL_ORDER = 2;
6832
6833 /**
6834 * Iterate over each mapping between an original source/line/column and a
6835 * generated line/column in this source map.
6836 *
6837 * @param Function aCallback
6838 * The function that is called with each mapping.
6839 * @param Object aContext
6840 * Optional. If specified, this object will be the value of `this` every
6841 * time that `aCallback` is called.
6842 * @param aOrder
6843 * Either `SourceMapConsumer.GENERATED_ORDER` or
6844 * `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to
6845 * iterate over the mappings sorted by the generated file's line/column
6846 * order or the original's source/line/column order, respectively. Defaults to
6847 * `SourceMapConsumer.GENERATED_ORDER`.
6848 */
6849 SourceMapConsumer.prototype.eachMapping =
6850 function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) {
6851 var context = aContext || null;
6852 var order = aOrder || SourceMapConsumer.GENERATED_ORDER;
6853
6854 var mappings;
6855 switch (order) {
6856 case SourceMapConsumer.GENERATED_ORDER:
6857 mappings = this._generatedMappings;
6858 break;
6859 case SourceMapConsumer.ORIGINAL_ORDER:
6860 mappings = this._originalMappings;
6861 break;
6862 default:
6863 throw new Error("Unknown order of iteration.");
6864 }
6865
6866 var sourceRoot = this.sourceRoot;
6867 mappings.map(function (mapping) {
6868 var source = mapping.source;
6869 if (source != null && sourceRoot != null) {
6870 source = util.join(sourceRoot, source);
6871 }
6872 return {
6873 source: source,
6874 generatedLine: mapping.generatedLine,
6875 generatedColumn: mapping.generatedColumn,
6876 originalLine: mapping.originalLine,
6877 originalColumn: mapping.originalColumn,
6878 name: mapping.name
6879 };
6880 }).forEach(aCallback, context);
6881 };
6882
6883 /**
6884 * Returns all generated line and column information for the original source
6885 * and line provided. The only argument is an object with the following
6886 * properties:
6887 *
6888 * - source: The filename of the original source.
6889 * - line: The line number in the original source.
6890 *
6891 * and an array of objects is returned, each with the following properties:
6892 *
6893 * - line: The line number in the generated source, or null.
6894 * - column: The column number in the generated source, or null.
6895 */
6896 SourceMapConsumer.prototype.allGeneratedPositionsFor =
6897 function SourceMapConsumer_allGeneratedPositionsFor(aArgs) {
6898 // When there is no exact match, BasicSourceMapConsumer.prototype._findMapping
6899 // returns the index of the closest mapping less than the needle. By
6900 // setting needle.originalColumn to Infinity, we thus find the last
6901 // mapping for the given line, provided such a mapping exists.
6902 var needle = {
6903 source: util.getArg(aArgs, 'source'),
6904 originalLine: util.getArg(aArgs, 'line'),
6905 originalColumn: Infinity
6906 };
6907
6908 if (this.sourceRoot != null) {
6909 needle.source = util.relative(this.sourceRoot, needle.source);
6910 }
6911
6912 var mappings = [];
6913
6914 var index = this._findMapping(needle,
6915 this._originalMappings,
6916 "originalLine",
6917 "originalColumn",
6918 util.compareByOriginalPositions);
6919 if (index >= 0) {
6920 var mapping = this._originalMappings[index];
6921
6922 while (mapping && mapping.originalLine === needle.originalLine) {
6923 mappings.push({
6924 line: util.getArg(mapping, 'generatedLine', null),
6925 column: util.getArg(mapping, 'generatedColumn', null),
6926 lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)
6927 });
6928
6929 mapping = this._originalMappings[--index];
6930 }
6931 }
6932
6933 return mappings.reverse();
6934 };
6935
6936 exports.SourceMapConsumer = SourceMapConsumer;
6937
6938});
6939
6940},{"./basic-source-map-consumer":74,"./indexed-source-map-consumer":76,"./util":81,"amdefine":10}],79:[function(_dereq_,module,exports){
6941/* -*- Mode: js; js-indent-level: 2; -*- */
6942/*
6943 * Copyright 2011 Mozilla Foundation and contributors
6944 * Licensed under the New BSD license. See LICENSE or:
6945 * http://opensource.org/licenses/BSD-3-Clause
6946 */
6947if (typeof define !== 'function') {
6948 var define = _dereq_('amdefine')(module, _dereq_);
6949}
6950define(function (_dereq_, exports, module) {
6951
6952 var base64VLQ = _dereq_('./base64-vlq');
6953 var util = _dereq_('./util');
6954 var ArraySet = _dereq_('./array-set').ArraySet;
6955 var MappingList = _dereq_('./mapping-list').MappingList;
6956
6957 /**
6958 * An instance of the SourceMapGenerator represents a source map which is
6959 * being built incrementally. You may pass an object with the following
6960 * properties:
6961 *
6962 * - file: The filename of the generated source.
6963 * - sourceRoot: A root for all relative URLs in this source map.
6964 */
6965 function SourceMapGenerator(aArgs) {
6966 if (!aArgs) {
6967 aArgs = {};
6968 }
6969 this._file = util.getArg(aArgs, 'file', null);
6970 this._sourceRoot = util.getArg(aArgs, 'sourceRoot', null);
6971 this._skipValidation = util.getArg(aArgs, 'skipValidation', false);
6972 this._sources = new ArraySet();
6973 this._names = new ArraySet();
6974 this._mappings = new MappingList();
6975 this._sourcesContents = null;
6976 }
6977
6978 SourceMapGenerator.prototype._version = 3;
6979
6980 /**
6981 * Creates a new SourceMapGenerator based on a SourceMapConsumer
6982 *
6983 * @param aSourceMapConsumer The SourceMap.
6984 */
6985 SourceMapGenerator.fromSourceMap =
6986 function SourceMapGenerator_fromSourceMap(aSourceMapConsumer) {
6987 var sourceRoot = aSourceMapConsumer.sourceRoot;
6988 var generator = new SourceMapGenerator({
6989 file: aSourceMapConsumer.file,
6990 sourceRoot: sourceRoot
6991 });
6992 aSourceMapConsumer.eachMapping(function (mapping) {
6993 var newMapping = {
6994 generated: {
6995 line: mapping.generatedLine,
6996 column: mapping.generatedColumn
6997 }
6998 };
6999
7000 if (mapping.source != null) {
7001 newMapping.source = mapping.source;
7002 if (sourceRoot != null) {
7003 newMapping.source = util.relative(sourceRoot, newMapping.source);
7004 }
7005
7006 newMapping.original = {
7007 line: mapping.originalLine,
7008 column: mapping.originalColumn
7009 };
7010
7011 if (mapping.name != null) {
7012 newMapping.name = mapping.name;
7013 }
7014 }
7015
7016 generator.addMapping(newMapping);
7017 });
7018 aSourceMapConsumer.sources.forEach(function (sourceFile) {
7019 var content = aSourceMapConsumer.sourceContentFor(sourceFile);
7020 if (content != null) {
7021 generator.setSourceContent(sourceFile, content);
7022 }
7023 });
7024 return generator;
7025 };
7026
7027 /**
7028 * Add a single mapping from original source line and column to the generated
7029 * source's line and column for this source map being created. The mapping
7030 * object should have the following properties:
7031 *
7032 * - generated: An object with the generated line and column positions.
7033 * - original: An object with the original line and column positions.
7034 * - source: The original source file (relative to the sourceRoot).
7035 * - name: An optional original token name for this mapping.
7036 */
7037 SourceMapGenerator.prototype.addMapping =
7038 function SourceMapGenerator_addMapping(aArgs) {
7039 var generated = util.getArg(aArgs, 'generated');
7040 var original = util.getArg(aArgs, 'original', null);
7041 var source = util.getArg(aArgs, 'source', null);
7042 var name = util.getArg(aArgs, 'name', null);
7043
7044 if (!this._skipValidation) {
7045 this._validateMapping(generated, original, source, name);
7046 }
7047
7048 if (source != null && !this._sources.has(source)) {
7049 this._sources.add(source);
7050 }
7051
7052 if (name != null && !this._names.has(name)) {
7053 this._names.add(name);
7054 }
7055
7056 this._mappings.add({
7057 generatedLine: generated.line,
7058 generatedColumn: generated.column,
7059 originalLine: original != null && original.line,
7060 originalColumn: original != null && original.column,
7061 source: source,
7062 name: name
7063 });
7064 };
7065
7066 /**
7067 * Set the source content for a source file.
7068 */
7069 SourceMapGenerator.prototype.setSourceContent =
7070 function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) {
7071 var source = aSourceFile;
7072 if (this._sourceRoot != null) {
7073 source = util.relative(this._sourceRoot, source);
7074 }
7075
7076 if (aSourceContent != null) {
7077 // Add the source content to the _sourcesContents map.
7078 // Create a new _sourcesContents map if the property is null.
7079 if (!this._sourcesContents) {
7080 this._sourcesContents = {};
7081 }
7082 this._sourcesContents[util.toSetString(source)] = aSourceContent;
7083 } else if (this._sourcesContents) {
7084 // Remove the source file from the _sourcesContents map.
7085 // If the _sourcesContents map is empty, set the property to null.
7086 delete this._sourcesContents[util.toSetString(source)];
7087 if (Object.keys(this._sourcesContents).length === 0) {
7088 this._sourcesContents = null;
7089 }
7090 }
7091 };
7092
7093 /**
7094 * Applies the mappings of a sub-source-map for a specific source file to the
7095 * source map being generated. Each mapping to the supplied source file is
7096 * rewritten using the supplied source map. Note: The resolution for the
7097 * resulting mappings is the minimium of this map and the supplied map.
7098 *
7099 * @param aSourceMapConsumer The source map to be applied.
7100 * @param aSourceFile Optional. The filename of the source file.
7101 * If omitted, SourceMapConsumer's file property will be used.
7102 * @param aSourceMapPath Optional. The dirname of the path to the source map
7103 * to be applied. If relative, it is relative to the SourceMapConsumer.
7104 * This parameter is needed when the two source maps aren't in the same
7105 * directory, and the source map to be applied contains relative source
7106 * paths. If so, those relative source paths need to be rewritten
7107 * relative to the SourceMapGenerator.
7108 */
7109 SourceMapGenerator.prototype.applySourceMap =
7110 function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile, aSourceMapPath) {
7111 var sourceFile = aSourceFile;
7112 // If aSourceFile is omitted, we will use the file property of the SourceMap
7113 if (aSourceFile == null) {
7114 if (aSourceMapConsumer.file == null) {
7115 throw new Error(
7116 'SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, ' +
7117 'or the source map\'s "file" property. Both were omitted.'
7118 );
7119 }
7120 sourceFile = aSourceMapConsumer.file;
7121 }
7122 var sourceRoot = this._sourceRoot;
7123 // Make "sourceFile" relative if an absolute Url is passed.
7124 if (sourceRoot != null) {
7125 sourceFile = util.relative(sourceRoot, sourceFile);
7126 }
7127 // Applying the SourceMap can add and remove items from the sources and
7128 // the names array.
7129 var newSources = new ArraySet();
7130 var newNames = new ArraySet();
7131
7132 // Find mappings for the "sourceFile"
7133 this._mappings.unsortedForEach(function (mapping) {
7134 if (mapping.source === sourceFile && mapping.originalLine != null) {
7135 // Check if it can be mapped by the source map, then update the mapping.
7136 var original = aSourceMapConsumer.originalPositionFor({
7137 line: mapping.originalLine,
7138 column: mapping.originalColumn
7139 });
7140 if (original.source != null) {
7141 // Copy mapping
7142 mapping.source = original.source;
7143 if (aSourceMapPath != null) {
7144 mapping.source = util.join(aSourceMapPath, mapping.source)
7145 }
7146 if (sourceRoot != null) {
7147 mapping.source = util.relative(sourceRoot, mapping.source);
7148 }
7149 mapping.originalLine = original.line;
7150 mapping.originalColumn = original.column;
7151 if (original.name != null) {
7152 mapping.name = original.name;
7153 }
7154 }
7155 }
7156
7157 var source = mapping.source;
7158 if (source != null && !newSources.has(source)) {
7159 newSources.add(source);
7160 }
7161
7162 var name = mapping.name;
7163 if (name != null && !newNames.has(name)) {
7164 newNames.add(name);
7165 }
7166
7167 }, this);
7168 this._sources = newSources;
7169 this._names = newNames;
7170
7171 // Copy sourcesContents of applied map.
7172 aSourceMapConsumer.sources.forEach(function (sourceFile) {
7173 var content = aSourceMapConsumer.sourceContentFor(sourceFile);
7174 if (content != null) {
7175 if (aSourceMapPath != null) {
7176 sourceFile = util.join(aSourceMapPath, sourceFile);
7177 }
7178 if (sourceRoot != null) {
7179 sourceFile = util.relative(sourceRoot, sourceFile);
7180 }
7181 this.setSourceContent(sourceFile, content);
7182 }
7183 }, this);
7184 };
7185
7186 /**
7187 * A mapping can have one of the three levels of data:
7188 *
7189 * 1. Just the generated position.
7190 * 2. The Generated position, original position, and original source.
7191 * 3. Generated and original position, original source, as well as a name
7192 * token.
7193 *
7194 * To maintain consistency, we validate that any new mapping being added falls
7195 * in to one of these categories.
7196 */
7197 SourceMapGenerator.prototype._validateMapping =
7198 function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource,
7199 aName) {
7200 if (aGenerated && 'line' in aGenerated && 'column' in aGenerated
7201 && aGenerated.line > 0 && aGenerated.column >= 0
7202 && !aOriginal && !aSource && !aName) {
7203 // Case 1.
7204 return;
7205 }
7206 else if (aGenerated && 'line' in aGenerated && 'column' in aGenerated
7207 && aOriginal && 'line' in aOriginal && 'column' in aOriginal
7208 && aGenerated.line > 0 && aGenerated.column >= 0
7209 && aOriginal.line > 0 && aOriginal.column >= 0
7210 && aSource) {
7211 // Cases 2 and 3.
7212 return;
7213 }
7214 else {
7215 throw new Error('Invalid mapping: ' + JSON.stringify({
7216 generated: aGenerated,
7217 source: aSource,
7218 original: aOriginal,
7219 name: aName
7220 }));
7221 }
7222 };
7223
7224 /**
7225 * Serialize the accumulated mappings in to the stream of base 64 VLQs
7226 * specified by the source map format.
7227 */
7228 SourceMapGenerator.prototype._serializeMappings =
7229 function SourceMapGenerator_serializeMappings() {
7230 var previousGeneratedColumn = 0;
7231 var previousGeneratedLine = 1;
7232 var previousOriginalColumn = 0;
7233 var previousOriginalLine = 0;
7234 var previousName = 0;
7235 var previousSource = 0;
7236 var result = '';
7237 var mapping;
7238
7239 var mappings = this._mappings.toArray();
7240
7241 for (var i = 0, len = mappings.length; i < len; i++) {
7242 mapping = mappings[i];
7243
7244 if (mapping.generatedLine !== previousGeneratedLine) {
7245 previousGeneratedColumn = 0;
7246 while (mapping.generatedLine !== previousGeneratedLine) {
7247 result += ';';
7248 previousGeneratedLine++;
7249 }
7250 }
7251 else {
7252 if (i > 0) {
7253 if (!util.compareByGeneratedPositions(mapping, mappings[i - 1])) {
7254 continue;
7255 }
7256 result += ',';
7257 }
7258 }
7259
7260 result += base64VLQ.encode(mapping.generatedColumn
7261 - previousGeneratedColumn);
7262 previousGeneratedColumn = mapping.generatedColumn;
7263
7264 if (mapping.source != null) {
7265 result += base64VLQ.encode(this._sources.indexOf(mapping.source)
7266 - previousSource);
7267 previousSource = this._sources.indexOf(mapping.source);
7268
7269 // lines are stored 0-based in SourceMap spec version 3
7270 result += base64VLQ.encode(mapping.originalLine - 1
7271 - previousOriginalLine);
7272 previousOriginalLine = mapping.originalLine - 1;
7273
7274 result += base64VLQ.encode(mapping.originalColumn
7275 - previousOriginalColumn);
7276 previousOriginalColumn = mapping.originalColumn;
7277
7278 if (mapping.name != null) {
7279 result += base64VLQ.encode(this._names.indexOf(mapping.name)
7280 - previousName);
7281 previousName = this._names.indexOf(mapping.name);
7282 }
7283 }
7284 }
7285
7286 return result;
7287 };
7288
7289 SourceMapGenerator.prototype._generateSourcesContent =
7290 function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) {
7291 return aSources.map(function (source) {
7292 if (!this._sourcesContents) {
7293 return null;
7294 }
7295 if (aSourceRoot != null) {
7296 source = util.relative(aSourceRoot, source);
7297 }
7298 var key = util.toSetString(source);
7299 return Object.prototype.hasOwnProperty.call(this._sourcesContents,
7300 key)
7301 ? this._sourcesContents[key]
7302 : null;
7303 }, this);
7304 };
7305
7306 /**
7307 * Externalize the source map.
7308 */
7309 SourceMapGenerator.prototype.toJSON =
7310 function SourceMapGenerator_toJSON() {
7311 var map = {
7312 version: this._version,
7313 sources: this._sources.toArray(),
7314 names: this._names.toArray(),
7315 mappings: this._serializeMappings()
7316 };
7317 if (this._file != null) {
7318 map.file = this._file;
7319 }
7320 if (this._sourceRoot != null) {
7321 map.sourceRoot = this._sourceRoot;
7322 }
7323 if (this._sourcesContents) {
7324 map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot);
7325 }
7326
7327 return map;
7328 };
7329
7330 /**
7331 * Render the source map being generated to a string.
7332 */
7333 SourceMapGenerator.prototype.toString =
7334 function SourceMapGenerator_toString() {
7335 return JSON.stringify(this);
7336 };
7337
7338 exports.SourceMapGenerator = SourceMapGenerator;
7339
7340});
7341
7342},{"./array-set":71,"./base64-vlq":72,"./mapping-list":77,"./util":81,"amdefine":10}],80:[function(_dereq_,module,exports){
7343/* -*- Mode: js; js-indent-level: 2; -*- */
7344/*
7345 * Copyright 2011 Mozilla Foundation and contributors
7346 * Licensed under the New BSD license. See LICENSE or:
7347 * http://opensource.org/licenses/BSD-3-Clause
7348 */
7349if (typeof define !== 'function') {
7350 var define = _dereq_('amdefine')(module, _dereq_);
7351}
7352define(function (_dereq_, exports, module) {
7353
7354 var SourceMapGenerator = _dereq_('./source-map-generator').SourceMapGenerator;
7355 var util = _dereq_('./util');
7356
7357 // Matches a Windows-style `\r\n` newline or a `\n` newline used by all other
7358 // operating systems these days (capturing the result).
7359 var REGEX_NEWLINE = /(\r?\n)/;
7360
7361 // Newline character code for charCodeAt() comparisons
7362 var NEWLINE_CODE = 10;
7363
7364 // Private symbol for identifying `SourceNode`s when multiple versions of
7365 // the source-map library are loaded. This MUST NOT CHANGE across
7366 // versions!
7367 var isSourceNode = "$$$isSourceNode$$$";
7368
7369 /**
7370 * SourceNodes provide a way to abstract over interpolating/concatenating
7371 * snippets of generated JavaScript source code while maintaining the line and
7372 * column information associated with the original source code.
7373 *
7374 * @param aLine The original line number.
7375 * @param aColumn The original column number.
7376 * @param aSource The original source's filename.
7377 * @param aChunks Optional. An array of strings which are snippets of
7378 * generated JS, or other SourceNodes.
7379 * @param aName The original identifier.
7380 */
7381 function SourceNode(aLine, aColumn, aSource, aChunks, aName) {
7382 this.children = [];
7383 this.sourceContents = {};
7384 this.line = aLine == null ? null : aLine;
7385 this.column = aColumn == null ? null : aColumn;
7386 this.source = aSource == null ? null : aSource;
7387 this.name = aName == null ? null : aName;
7388 this[isSourceNode] = true;
7389 if (aChunks != null) this.add(aChunks);
7390 }
7391
7392 /**
7393 * Creates a SourceNode from generated code and a SourceMapConsumer.
7394 *
7395 * @param aGeneratedCode The generated code
7396 * @param aSourceMapConsumer The SourceMap for the generated code
7397 * @param aRelativePath Optional. The path that relative sources in the
7398 * SourceMapConsumer should be relative to.
7399 */
7400 SourceNode.fromStringWithSourceMap =
7401 function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer, aRelativePath) {
7402 // The SourceNode we want to fill with the generated code
7403 // and the SourceMap
7404 var node = new SourceNode();
7405
7406 // All even indices of this array are one line of the generated code,
7407 // while all odd indices are the newlines between two adjacent lines
7408 // (since `REGEX_NEWLINE` captures its match).
7409 // Processed fragments are removed from this array, by calling `shiftNextLine`.
7410 var remainingLines = aGeneratedCode.split(REGEX_NEWLINE);
7411 var shiftNextLine = function() {
7412 var lineContents = remainingLines.shift();
7413 // The last line of a file might not have a newline.
7414 var newLine = remainingLines.shift() || "";
7415 return lineContents + newLine;
7416 };
7417
7418 // We need to remember the position of "remainingLines"
7419 var lastGeneratedLine = 1, lastGeneratedColumn = 0;
7420
7421 // The generate SourceNodes we need a code range.
7422 // To extract it current and last mapping is used.
7423 // Here we store the last mapping.
7424 var lastMapping = null;
7425
7426 aSourceMapConsumer.eachMapping(function (mapping) {
7427 if (lastMapping !== null) {
7428 // We add the code from "lastMapping" to "mapping":
7429 // First check if there is a new line in between.
7430 if (lastGeneratedLine < mapping.generatedLine) {
7431 var code = "";
7432 // Associate first line with "lastMapping"
7433 addMappingWithCode(lastMapping, shiftNextLine());
7434 lastGeneratedLine++;
7435 lastGeneratedColumn = 0;
7436 // The remaining code is added without mapping
7437 } else {
7438 // There is no new line in between.
7439 // Associate the code between "lastGeneratedColumn" and
7440 // "mapping.generatedColumn" with "lastMapping"
7441 var nextLine = remainingLines[0];
7442 var code = nextLine.substr(0, mapping.generatedColumn -
7443 lastGeneratedColumn);
7444 remainingLines[0] = nextLine.substr(mapping.generatedColumn -
7445 lastGeneratedColumn);
7446 lastGeneratedColumn = mapping.generatedColumn;
7447 addMappingWithCode(lastMapping, code);
7448 // No more remaining code, continue
7449 lastMapping = mapping;
7450 return;
7451 }
7452 }
7453 // We add the generated code until the first mapping
7454 // to the SourceNode without any mapping.
7455 // Each line is added as separate string.
7456 while (lastGeneratedLine < mapping.generatedLine) {
7457 node.add(shiftNextLine());
7458 lastGeneratedLine++;
7459 }
7460 if (lastGeneratedColumn < mapping.generatedColumn) {
7461 var nextLine = remainingLines[0];
7462 node.add(nextLine.substr(0, mapping.generatedColumn));
7463 remainingLines[0] = nextLine.substr(mapping.generatedColumn);
7464 lastGeneratedColumn = mapping.generatedColumn;
7465 }
7466 lastMapping = mapping;
7467 }, this);
7468 // We have processed all mappings.
7469 if (remainingLines.length > 0) {
7470 if (lastMapping) {
7471 // Associate the remaining code in the current line with "lastMapping"
7472 addMappingWithCode(lastMapping, shiftNextLine());
7473 }
7474 // and add the remaining lines without any mapping
7475 node.add(remainingLines.join(""));
7476 }
7477
7478 // Copy sourcesContent into SourceNode
7479 aSourceMapConsumer.sources.forEach(function (sourceFile) {
7480 var content = aSourceMapConsumer.sourceContentFor(sourceFile);
7481 if (content != null) {
7482 if (aRelativePath != null) {
7483 sourceFile = util.join(aRelativePath, sourceFile);
7484 }
7485 node.setSourceContent(sourceFile, content);
7486 }
7487 });
7488
7489 return node;
7490
7491 function addMappingWithCode(mapping, code) {
7492 if (mapping === null || mapping.source === undefined) {
7493 node.add(code);
7494 } else {
7495 var source = aRelativePath
7496 ? util.join(aRelativePath, mapping.source)
7497 : mapping.source;
7498 node.add(new SourceNode(mapping.originalLine,
7499 mapping.originalColumn,
7500 source,
7501 code,
7502 mapping.name));
7503 }
7504 }
7505 };
7506
7507 /**
7508 * Add a chunk of generated JS to this source node.
7509 *
7510 * @param aChunk A string snippet of generated JS code, another instance of
7511 * SourceNode, or an array where each member is one of those things.
7512 */
7513 SourceNode.prototype.add = function SourceNode_add(aChunk) {
7514 if (Array.isArray(aChunk)) {
7515 aChunk.forEach(function (chunk) {
7516 this.add(chunk);
7517 }, this);
7518 }
7519 else if (aChunk[isSourceNode] || typeof aChunk === "string") {
7520 if (aChunk) {
7521 this.children.push(aChunk);
7522 }
7523 }
7524 else {
7525 throw new TypeError(
7526 "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk
7527 );
7528 }
7529 return this;
7530 };
7531
7532 /**
7533 * Add a chunk of generated JS to the beginning of this source node.
7534 *
7535 * @param aChunk A string snippet of generated JS code, another instance of
7536 * SourceNode, or an array where each member is one of those things.
7537 */
7538 SourceNode.prototype.prepend = function SourceNode_prepend(aChunk) {
7539 if (Array.isArray(aChunk)) {
7540 for (var i = aChunk.length-1; i >= 0; i--) {
7541 this.prepend(aChunk[i]);
7542 }
7543 }
7544 else if (aChunk[isSourceNode] || typeof aChunk === "string") {
7545 this.children.unshift(aChunk);
7546 }
7547 else {
7548 throw new TypeError(
7549 "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk
7550 );
7551 }
7552 return this;
7553 };
7554
7555 /**
7556 * Walk over the tree of JS snippets in this node and its children. The
7557 * walking function is called once for each snippet of JS and is passed that
7558 * snippet and the its original associated source's line/column location.
7559 *
7560 * @param aFn The traversal function.
7561 */
7562 SourceNode.prototype.walk = function SourceNode_walk(aFn) {
7563 var chunk;
7564 for (var i = 0, len = this.children.length; i < len; i++) {
7565 chunk = this.children[i];
7566 if (chunk[isSourceNode]) {
7567 chunk.walk(aFn);
7568 }
7569 else {
7570 if (chunk !== '') {
7571 aFn(chunk, { source: this.source,
7572 line: this.line,
7573 column: this.column,
7574 name: this.name });
7575 }
7576 }
7577 }
7578 };
7579
7580 /**
7581 * Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between
7582 * each of `this.children`.
7583 *
7584 * @param aSep The separator.
7585 */
7586 SourceNode.prototype.join = function SourceNode_join(aSep) {
7587 var newChildren;
7588 var i;
7589 var len = this.children.length;
7590 if (len > 0) {
7591 newChildren = [];
7592 for (i = 0; i < len-1; i++) {
7593 newChildren.push(this.children[i]);
7594 newChildren.push(aSep);
7595 }
7596 newChildren.push(this.children[i]);
7597 this.children = newChildren;
7598 }
7599 return this;
7600 };
7601
7602 /**
7603 * Call String.prototype.replace on the very right-most source snippet. Useful
7604 * for trimming whitespace from the end of a source node, etc.
7605 *
7606 * @param aPattern The pattern to replace.
7607 * @param aReplacement The thing to replace the pattern with.
7608 */
7609 SourceNode.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) {
7610 var lastChild = this.children[this.children.length - 1];
7611 if (lastChild[isSourceNode]) {
7612 lastChild.replaceRight(aPattern, aReplacement);
7613 }
7614 else if (typeof lastChild === 'string') {
7615 this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement);
7616 }
7617 else {
7618 this.children.push(''.replace(aPattern, aReplacement));
7619 }
7620 return this;
7621 };
7622
7623 /**
7624 * Set the source content for a source file. This will be added to the SourceMapGenerator
7625 * in the sourcesContent field.
7626 *
7627 * @param aSourceFile The filename of the source file
7628 * @param aSourceContent The content of the source file
7629 */
7630 SourceNode.prototype.setSourceContent =
7631 function SourceNode_setSourceContent(aSourceFile, aSourceContent) {
7632 this.sourceContents[util.toSetString(aSourceFile)] = aSourceContent;
7633 };
7634
7635 /**
7636 * Walk over the tree of SourceNodes. The walking function is called for each
7637 * source file content and is passed the filename and source content.
7638 *
7639 * @param aFn The traversal function.
7640 */
7641 SourceNode.prototype.walkSourceContents =
7642 function SourceNode_walkSourceContents(aFn) {
7643 for (var i = 0, len = this.children.length; i < len; i++) {
7644 if (this.children[i][isSourceNode]) {
7645 this.children[i].walkSourceContents(aFn);
7646 }
7647 }
7648
7649 var sources = Object.keys(this.sourceContents);
7650 for (var i = 0, len = sources.length; i < len; i++) {
7651 aFn(util.fromSetString(sources[i]), this.sourceContents[sources[i]]);
7652 }
7653 };
7654
7655 /**
7656 * Return the string representation of this source node. Walks over the tree
7657 * and concatenates all the various snippets together to one string.
7658 */
7659 SourceNode.prototype.toString = function SourceNode_toString() {
7660 var str = "";
7661 this.walk(function (chunk) {
7662 str += chunk;
7663 });
7664 return str;
7665 };
7666
7667 /**
7668 * Returns the string representation of this source node along with a source
7669 * map.
7670 */
7671 SourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) {
7672 var generated = {
7673 code: "",
7674 line: 1,
7675 column: 0
7676 };
7677 var map = new SourceMapGenerator(aArgs);
7678 var sourceMappingActive = false;
7679 var lastOriginalSource = null;
7680 var lastOriginalLine = null;
7681 var lastOriginalColumn = null;
7682 var lastOriginalName = null;
7683 this.walk(function (chunk, original) {
7684 generated.code += chunk;
7685 if (original.source !== null
7686 && original.line !== null
7687 && original.column !== null) {
7688 if(lastOriginalSource !== original.source
7689 || lastOriginalLine !== original.line
7690 || lastOriginalColumn !== original.column
7691 || lastOriginalName !== original.name) {
7692 map.addMapping({
7693 source: original.source,
7694 original: {
7695 line: original.line,
7696 column: original.column
7697 },
7698 generated: {
7699 line: generated.line,
7700 column: generated.column
7701 },
7702 name: original.name
7703 });
7704 }
7705 lastOriginalSource = original.source;
7706 lastOriginalLine = original.line;
7707 lastOriginalColumn = original.column;
7708 lastOriginalName = original.name;
7709 sourceMappingActive = true;
7710 } else if (sourceMappingActive) {
7711 map.addMapping({
7712 generated: {
7713 line: generated.line,
7714 column: generated.column
7715 }
7716 });
7717 lastOriginalSource = null;
7718 sourceMappingActive = false;
7719 }
7720 for (var idx = 0, length = chunk.length; idx < length; idx++) {
7721 if (chunk.charCodeAt(idx) === NEWLINE_CODE) {
7722 generated.line++;
7723 generated.column = 0;
7724 // Mappings end at eol
7725 if (idx + 1 === length) {
7726 lastOriginalSource = null;
7727 sourceMappingActive = false;
7728 } else if (sourceMappingActive) {
7729 map.addMapping({
7730 source: original.source,
7731 original: {
7732 line: original.line,
7733 column: original.column
7734 },
7735 generated: {
7736 line: generated.line,
7737 column: generated.column
7738 },
7739 name: original.name
7740 });
7741 }
7742 } else {
7743 generated.column++;
7744 }
7745 }
7746 });
7747 this.walkSourceContents(function (sourceFile, sourceContent) {
7748 map.setSourceContent(sourceFile, sourceContent);
7749 });
7750
7751 return { code: generated.code, map: map };
7752 };
7753
7754 exports.SourceNode = SourceNode;
7755
7756});
7757
7758},{"./source-map-generator":79,"./util":81,"amdefine":10}],81:[function(_dereq_,module,exports){
7759/* -*- Mode: js; js-indent-level: 2; -*- */
7760/*
7761 * Copyright 2011 Mozilla Foundation and contributors
7762 * Licensed under the New BSD license. See LICENSE or:
7763 * http://opensource.org/licenses/BSD-3-Clause
7764 */
7765if (typeof define !== 'function') {
7766 var define = _dereq_('amdefine')(module, _dereq_);
7767}
7768define(function (_dereq_, exports, module) {
7769
7770 /**
7771 * This is a helper function for getting values from parameter/options
7772 * objects.
7773 *
7774 * @param args The object we are extracting values from
7775 * @param name The name of the property we are getting.
7776 * @param defaultValue An optional value to return if the property is missing
7777 * from the object. If this is not specified and the property is missing, an
7778 * error will be thrown.
7779 */
7780 function getArg(aArgs, aName, aDefaultValue) {
7781 if (aName in aArgs) {
7782 return aArgs[aName];
7783 } else if (arguments.length === 3) {
7784 return aDefaultValue;
7785 } else {
7786 throw new Error('"' + aName + '" is a required argument.');
7787 }
7788 }
7789 exports.getArg = getArg;
7790
7791 var urlRegexp = /^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.]*)(?::(\d+))?(\S*)$/;
7792 var dataUrlRegexp = /^data:.+\,.+$/;
7793
7794 function urlParse(aUrl) {
7795 var match = aUrl.match(urlRegexp);
7796 if (!match) {
7797 return null;
7798 }
7799 return {
7800 scheme: match[1],
7801 auth: match[2],
7802 host: match[3],
7803 port: match[4],
7804 path: match[5]
7805 };
7806 }
7807 exports.urlParse = urlParse;
7808
7809 function urlGenerate(aParsedUrl) {
7810 var url = '';
7811 if (aParsedUrl.scheme) {
7812 url += aParsedUrl.scheme + ':';
7813 }
7814 url += '//';
7815 if (aParsedUrl.auth) {
7816 url += aParsedUrl.auth + '@';
7817 }
7818 if (aParsedUrl.host) {
7819 url += aParsedUrl.host;
7820 }
7821 if (aParsedUrl.port) {
7822 url += ":" + aParsedUrl.port
7823 }
7824 if (aParsedUrl.path) {
7825 url += aParsedUrl.path;
7826 }
7827 return url;
7828 }
7829 exports.urlGenerate = urlGenerate;
7830
7831 /**
7832 * Normalizes a path, or the path portion of a URL:
7833 *
7834 * - Replaces consequtive slashes with one slash.
7835 * - Removes unnecessary '.' parts.
7836 * - Removes unnecessary '<dir>/..' parts.
7837 *
7838 * Based on code in the Node.js 'path' core module.
7839 *
7840 * @param aPath The path or url to normalize.
7841 */
7842 function normalize(aPath) {
7843 var path = aPath;
7844 var url = urlParse(aPath);
7845 if (url) {
7846 if (!url.path) {
7847 return aPath;
7848 }
7849 path = url.path;
7850 }
7851 var isAbsolute = (path.charAt(0) === '/');
7852
7853 var parts = path.split(/\/+/);
7854 for (var part, up = 0, i = parts.length - 1; i >= 0; i--) {
7855 part = parts[i];
7856 if (part === '.') {
7857 parts.splice(i, 1);
7858 } else if (part === '..') {
7859 up++;
7860 } else if (up > 0) {
7861 if (part === '') {
7862 // The first part is blank if the path is absolute. Trying to go
7863 // above the root is a no-op. Therefore we can remove all '..' parts
7864 // directly after the root.
7865 parts.splice(i + 1, up);
7866 up = 0;
7867 } else {
7868 parts.splice(i, 2);
7869 up--;
7870 }
7871 }
7872 }
7873 path = parts.join('/');
7874
7875 if (path === '') {
7876 path = isAbsolute ? '/' : '.';
7877 }
7878
7879 if (url) {
7880 url.path = path;
7881 return urlGenerate(url);
7882 }
7883 return path;
7884 }
7885 exports.normalize = normalize;
7886
7887 /**
7888 * Joins two paths/URLs.
7889 *
7890 * @param aRoot The root path or URL.
7891 * @param aPath The path or URL to be joined with the root.
7892 *
7893 * - If aPath is a URL or a data URI, aPath is returned, unless aPath is a
7894 * scheme-relative URL: Then the scheme of aRoot, if any, is prepended
7895 * first.
7896 * - Otherwise aPath is a path. If aRoot is a URL, then its path portion
7897 * is updated with the result and aRoot is returned. Otherwise the result
7898 * is returned.
7899 * - If aPath is absolute, the result is aPath.
7900 * - Otherwise the two paths are joined with a slash.
7901 * - Joining for example 'http://' and 'www.example.com' is also supported.
7902 */
7903 function join(aRoot, aPath) {
7904 if (aRoot === "") {
7905 aRoot = ".";
7906 }
7907 if (aPath === "") {
7908 aPath = ".";
7909 }
7910 var aPathUrl = urlParse(aPath);
7911 var aRootUrl = urlParse(aRoot);
7912 if (aRootUrl) {
7913 aRoot = aRootUrl.path || '/';
7914 }
7915
7916 // `join(foo, '//www.example.org')`
7917 if (aPathUrl && !aPathUrl.scheme) {
7918 if (aRootUrl) {
7919 aPathUrl.scheme = aRootUrl.scheme;
7920 }
7921 return urlGenerate(aPathUrl);
7922 }
7923
7924 if (aPathUrl || aPath.match(dataUrlRegexp)) {
7925 return aPath;
7926 }
7927
7928 // `join('http://', 'www.example.com')`
7929 if (aRootUrl && !aRootUrl.host && !aRootUrl.path) {
7930 aRootUrl.host = aPath;
7931 return urlGenerate(aRootUrl);
7932 }
7933
7934 var joined = aPath.charAt(0) === '/'
7935 ? aPath
7936 : normalize(aRoot.replace(/\/+$/, '') + '/' + aPath);
7937
7938 if (aRootUrl) {
7939 aRootUrl.path = joined;
7940 return urlGenerate(aRootUrl);
7941 }
7942 return joined;
7943 }
7944 exports.join = join;
7945
7946 /**
7947 * Make a path relative to a URL or another path.
7948 *
7949 * @param aRoot The root path or URL.
7950 * @param aPath The path or URL to be made relative to aRoot.
7951 */
7952 function relative(aRoot, aPath) {
7953 if (aRoot === "") {
7954 aRoot = ".";
7955 }
7956
7957 aRoot = aRoot.replace(/\/$/, '');
7958
7959 // XXX: It is possible to remove this block, and the tests still pass!
7960 var url = urlParse(aRoot);
7961 if (aPath.charAt(0) == "/" && url && url.path == "/") {
7962 return aPath.slice(1);
7963 }
7964
7965 return aPath.indexOf(aRoot + '/') === 0
7966 ? aPath.substr(aRoot.length + 1)
7967 : aPath;
7968 }
7969 exports.relative = relative;
7970
7971 /**
7972 * Because behavior goes wacky when you set `__proto__` on objects, we
7973 * have to prefix all the strings in our set with an arbitrary character.
7974 *
7975 * See https://github.com/mozilla/source-map/pull/31 and
7976 * https://github.com/mozilla/source-map/issues/30
7977 *
7978 * @param String aStr
7979 */
7980 function toSetString(aStr) {
7981 return '$' + aStr;
7982 }
7983 exports.toSetString = toSetString;
7984
7985 function fromSetString(aStr) {
7986 return aStr.substr(1);
7987 }
7988 exports.fromSetString = fromSetString;
7989
7990 function strcmp(aStr1, aStr2) {
7991 var s1 = aStr1 || "";
7992 var s2 = aStr2 || "";
7993 return (s1 > s2) - (s1 < s2);
7994 }
7995
7996 /**
7997 * Comparator between two mappings where the original positions are compared.
7998 *
7999 * Optionally pass in `true` as `onlyCompareGenerated` to consider two
8000 * mappings with the same original source/line/column, but different generated
8001 * line and column the same. Useful when searching for a mapping with a
8002 * stubbed out mapping.
8003 */
8004 function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) {
8005 var cmp;
8006
8007 cmp = strcmp(mappingA.source, mappingB.source);
8008 if (cmp) {
8009 return cmp;
8010 }
8011
8012 cmp = mappingA.originalLine - mappingB.originalLine;
8013 if (cmp) {
8014 return cmp;
8015 }
8016
8017 cmp = mappingA.originalColumn - mappingB.originalColumn;
8018 if (cmp || onlyCompareOriginal) {
8019 return cmp;
8020 }
8021
8022 cmp = strcmp(mappingA.name, mappingB.name);
8023 if (cmp) {
8024 return cmp;
8025 }
8026
8027 cmp = mappingA.generatedLine - mappingB.generatedLine;
8028 if (cmp) {
8029 return cmp;
8030 }
8031
8032 return mappingA.generatedColumn - mappingB.generatedColumn;
8033 };
8034 exports.compareByOriginalPositions = compareByOriginalPositions;
8035
8036 /**
8037 * Comparator between two mappings where the generated positions are
8038 * compared.
8039 *
8040 * Optionally pass in `true` as `onlyCompareGenerated` to consider two
8041 * mappings with the same generated line and column, but different
8042 * source/name/original line and column the same. Useful when searching for a
8043 * mapping with a stubbed out mapping.
8044 */
8045 function compareByGeneratedPositions(mappingA, mappingB, onlyCompareGenerated) {
8046 var cmp;
8047
8048 cmp = mappingA.generatedLine - mappingB.generatedLine;
8049 if (cmp) {
8050 return cmp;
8051 }
8052
8053 cmp = mappingA.generatedColumn - mappingB.generatedColumn;
8054 if (cmp || onlyCompareGenerated) {
8055 return cmp;
8056 }
8057
8058 cmp = strcmp(mappingA.source, mappingB.source);
8059 if (cmp) {
8060 return cmp;
8061 }
8062
8063 cmp = mappingA.originalLine - mappingB.originalLine;
8064 if (cmp) {
8065 return cmp;
8066 }
8067
8068 cmp = mappingA.originalColumn - mappingB.originalColumn;
8069 if (cmp) {
8070 return cmp;
8071 }
8072
8073 return strcmp(mappingA.name, mappingB.name);
8074 };
8075 exports.compareByGeneratedPositions = compareByGeneratedPositions;
8076
8077});
8078
8079},{"amdefine":10}],82:[function(_dereq_,module,exports){
8080module.exports={"version":"1.8.0"}
8081},{}],83:[function(_dereq_,module,exports){
8082/**
8083 * espower-location-detector:
8084 * AST source location detection helper for power-assert
8085 *
8086 * https://github.com/twada/espower-location-detector
8087 *
8088 * Copyright (c) 2015-2016 Takuto Wada
8089 * Licensed under the MIT license.
8090 * https://github.com/twada/espower-location-detector/blob/master/MIT-LICENSE.txt
8091 */
8092'use strict';
8093
8094var PositionDetector = _dereq_('./lib/position-detector');
8095var SourceAdjuster = _dereq_('./lib/source-adjuster');
8096
8097function EspowerLocationDetector (options) {
8098 this.positionDetector = new PositionDetector(options.sourceMap);
8099 this.sourceAdjuster = new SourceAdjuster(options.sourceRoot, options.path, options.sourceMap);
8100}
8101
8102EspowerLocationDetector.prototype.locationFor = function (currentNode) {
8103 var pos = this.positionDetector.positionFor(currentNode);
8104 return {
8105 source: this.sourceAdjuster.relativize(pos.source, pos.mapped),
8106 line: pos.line,
8107 column: pos.column
8108 };
8109};
8110
8111module.exports = EspowerLocationDetector;
8112
8113},{"./lib/position-detector":84,"./lib/source-adjuster":85}],84:[function(_dereq_,module,exports){
8114'use strict';
8115
8116var SourceMapConsumer = _dereq_('source-map').SourceMapConsumer;
8117var extend = _dereq_('xtend');
8118
8119function isEmptyMapping (pos) {
8120 return ['source', 'line', 'column', 'name'].every(function (prop) {
8121 return pos[prop] === null;
8122 });
8123}
8124
8125function PositionDetector (sourceMap) {
8126 if (sourceMap) {
8127 this.sourceMapConsumer = new SourceMapConsumer(sourceMap);
8128 }
8129}
8130PositionDetector.prototype.positionFor = function (currentNode) {
8131 var currentPosition = {
8132 source: currentNode.loc.source,
8133 line: currentNode.loc.start.line,
8134 column: currentNode.loc.start.column
8135 };
8136 if (this.sourceMapConsumer) {
8137 var found = this.sourceMapConsumer.originalPositionFor(currentPosition);
8138 if (found && !isEmptyMapping(found)) {
8139 return extend({ mapped: true }, found);
8140 }
8141 }
8142 return extend({ mapped: false }, currentPosition);
8143};
8144
8145module.exports = PositionDetector;
8146
8147},{"source-map":113,"xtend":115}],85:[function(_dereq_,module,exports){
8148'use strict';
8149
8150var _path = _dereq_('path');
8151var isAbsolute = _dereq_('path-is-absolute');
8152var isUrl = _dereq_('is-url');
8153
8154function SourceAdjuster (sourceRoot, path, sourceMap) {
8155 this.path = path;
8156 this.sourceRoot = sourceRoot;
8157 if (typeof sourceMap === 'string') {
8158 this.sourceMap = JSON.parse(sourceMap.replace(/^\)\]\}'/, ''));
8159 } else {
8160 this.sourceMap = sourceMap;
8161 }
8162}
8163SourceAdjuster.prototype.relativize = function (filepathOrUrl, mappedWithSourceMap) {
8164 var filepath;
8165 if (mappedWithSourceMap && filepathOrUrl && this.sourceMap) {
8166 filepath = this.relativizeWithSourceMap(filepathOrUrl);
8167 } else {
8168 filepath = this.relativizeWithoutSourceMap(filepathOrUrl);
8169 }
8170 return fallbackOnBasename(filepath);
8171};
8172SourceAdjuster.prototype.relativizeWithSourceMap = function (filepathOrUrl) {
8173 var sourceMapRoot = this.sourceMap.sourceRoot;
8174 if (sourceMapRoot && isUrl(sourceMapRoot)) {
8175 return _path.relative(sourceMapRoot, filepathOrUrl);
8176 }
8177 if (this.sourceRoot && isAbsolute(this.sourceRoot) && isAbsolute(filepathOrUrl)) {
8178 return _path.relative(this.sourceRoot, filepathOrUrl);
8179 }
8180 if (sourceMapRoot && isAbsolute(sourceMapRoot) && isAbsolute(filepathOrUrl)) {
8181 return _path.relative(sourceMapRoot, filepathOrUrl);
8182 }
8183 if (isUrl(filepathOrUrl)) {
8184 return _path.basename(filepathOrUrl);
8185 }
8186 return filepathOrUrl;
8187};
8188SourceAdjuster.prototype.relativizeWithoutSourceMap = function (filepathOrUrl) {
8189 var tmpPath = this.path || filepathOrUrl;
8190 if (this.sourceRoot && isAbsolute(this.sourceRoot) && isAbsolute(tmpPath)) {
8191 return _path.relative(this.sourceRoot, tmpPath);
8192 } else {
8193 return this.path;
8194 }
8195};
8196
8197function fallbackOnBasename (filepath) {
8198 if (filepath) {
8199 if (filepath.split(_path.sep).indexOf('..') !== -1) {
8200 return _path.basename(filepath);
8201 } else if (isUrl(filepath)) {
8202 return _path.basename(filepath);
8203 } else if (isAbsolute(filepath)) {
8204 return _path.basename(filepath);
8205 }
8206 }
8207 return filepath;
8208}
8209
8210module.exports = SourceAdjuster;
8211
8212},{"is-url":98,"path":100,"path-is-absolute":101}],86:[function(_dereq_,module,exports){
8213/*
8214 Copyright (c) jQuery Foundation, Inc. and Contributors, All Rights Reserved.
8215
8216 Redistribution and use in source and binary forms, with or without
8217 modification, are permitted provided that the following conditions are met:
8218
8219 * Redistributions of source code must retain the above copyright
8220 notice, this list of conditions and the following disclaimer.
8221 * Redistributions in binary form must reproduce the above copyright
8222 notice, this list of conditions and the following disclaimer in the
8223 documentation and/or other materials provided with the distribution.
8224
8225 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
8226 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
8227 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
8228 ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
8229 DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
8230 (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
8231 LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
8232 ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
8233 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
8234 THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
8235*/
8236
8237(function (root, factory) {
8238 'use strict';
8239
8240 // Universal Module Definition (UMD) to support AMD, CommonJS/Node.js,
8241 // Rhino, and plain browser loading.
8242
8243 /* istanbul ignore next */
8244 if (typeof define === 'function' && define.amd) {
8245 define(['exports'], factory);
8246 } else if (typeof exports !== 'undefined') {
8247 factory(exports);
8248 } else {
8249 factory((root.esprima = {}));
8250 }
8251}(this, function (exports) {
8252 'use strict';
8253
8254 var Token,
8255 TokenName,
8256 FnExprTokens,
8257 Syntax,
8258 PlaceHolders,
8259 Messages,
8260 Regex,
8261 source,
8262 strict,
8263 index,
8264 lineNumber,
8265 lineStart,
8266 hasLineTerminator,
8267 lastIndex,
8268 lastLineNumber,
8269 lastLineStart,
8270 startIndex,
8271 startLineNumber,
8272 startLineStart,
8273 scanning,
8274 length,
8275 lookahead,
8276 state,
8277 extra,
8278 isBindingElement,
8279 isAssignmentTarget,
8280 firstCoverInitializedNameError;
8281
8282 Token = {
8283 BooleanLiteral: 1,
8284 EOF: 2,
8285 Identifier: 3,
8286 Keyword: 4,
8287 NullLiteral: 5,
8288 NumericLiteral: 6,
8289 Punctuator: 7,
8290 StringLiteral: 8,
8291 RegularExpression: 9,
8292 Template: 10
8293 };
8294
8295 TokenName = {};
8296 TokenName[Token.BooleanLiteral] = 'Boolean';
8297 TokenName[Token.EOF] = '<end>';
8298 TokenName[Token.Identifier] = 'Identifier';
8299 TokenName[Token.Keyword] = 'Keyword';
8300 TokenName[Token.NullLiteral] = 'Null';
8301 TokenName[Token.NumericLiteral] = 'Numeric';
8302 TokenName[Token.Punctuator] = 'Punctuator';
8303 TokenName[Token.StringLiteral] = 'String';
8304 TokenName[Token.RegularExpression] = 'RegularExpression';
8305 TokenName[Token.Template] = 'Template';
8306
8307 // A function following one of those tokens is an expression.
8308 FnExprTokens = ['(', '{', '[', 'in', 'typeof', 'instanceof', 'new',
8309 'return', 'case', 'delete', 'throw', 'void',
8310 // assignment operators
8311 '=', '+=', '-=', '*=', '/=', '%=', '<<=', '>>=', '>>>=',
8312 '&=', '|=', '^=', ',',
8313 // binary/unary operators
8314 '+', '-', '*', '/', '%', '++', '--', '<<', '>>', '>>>', '&',
8315 '|', '^', '!', '~', '&&', '||', '?', ':', '===', '==', '>=',
8316 '<=', '<', '>', '!=', '!=='];
8317
8318 Syntax = {
8319 AssignmentExpression: 'AssignmentExpression',
8320 AssignmentPattern: 'AssignmentPattern',
8321 ArrayExpression: 'ArrayExpression',
8322 ArrayPattern: 'ArrayPattern',
8323 ArrowFunctionExpression: 'ArrowFunctionExpression',
8324 BlockStatement: 'BlockStatement',
8325 BinaryExpression: 'BinaryExpression',
8326 BreakStatement: 'BreakStatement',
8327 CallExpression: 'CallExpression',
8328 CatchClause: 'CatchClause',
8329 ClassBody: 'ClassBody',
8330 ClassDeclaration: 'ClassDeclaration',
8331 ClassExpression: 'ClassExpression',
8332 ConditionalExpression: 'ConditionalExpression',
8333 ContinueStatement: 'ContinueStatement',
8334 DoWhileStatement: 'DoWhileStatement',
8335 DebuggerStatement: 'DebuggerStatement',
8336 EmptyStatement: 'EmptyStatement',
8337 ExportAllDeclaration: 'ExportAllDeclaration',
8338 ExportDefaultDeclaration: 'ExportDefaultDeclaration',
8339 ExportNamedDeclaration: 'ExportNamedDeclaration',
8340 ExportSpecifier: 'ExportSpecifier',
8341 ExpressionStatement: 'ExpressionStatement',
8342 ForStatement: 'ForStatement',
8343 ForOfStatement: 'ForOfStatement',
8344 ForInStatement: 'ForInStatement',
8345 FunctionDeclaration: 'FunctionDeclaration',
8346 FunctionExpression: 'FunctionExpression',
8347 Identifier: 'Identifier',
8348 IfStatement: 'IfStatement',
8349 ImportDeclaration: 'ImportDeclaration',
8350 ImportDefaultSpecifier: 'ImportDefaultSpecifier',
8351 ImportNamespaceSpecifier: 'ImportNamespaceSpecifier',
8352 ImportSpecifier: 'ImportSpecifier',
8353 Literal: 'Literal',
8354 LabeledStatement: 'LabeledStatement',
8355 LogicalExpression: 'LogicalExpression',
8356 MemberExpression: 'MemberExpression',
8357 MetaProperty: 'MetaProperty',
8358 MethodDefinition: 'MethodDefinition',
8359 NewExpression: 'NewExpression',
8360 ObjectExpression: 'ObjectExpression',
8361 ObjectPattern: 'ObjectPattern',
8362 Program: 'Program',
8363 Property: 'Property',
8364 RestElement: 'RestElement',
8365 ReturnStatement: 'ReturnStatement',
8366 SequenceExpression: 'SequenceExpression',
8367 SpreadElement: 'SpreadElement',
8368 Super: 'Super',
8369 SwitchCase: 'SwitchCase',
8370 SwitchStatement: 'SwitchStatement',
8371 TaggedTemplateExpression: 'TaggedTemplateExpression',
8372 TemplateElement: 'TemplateElement',
8373 TemplateLiteral: 'TemplateLiteral',
8374 ThisExpression: 'ThisExpression',
8375 ThrowStatement: 'ThrowStatement',
8376 TryStatement: 'TryStatement',
8377 UnaryExpression: 'UnaryExpression',
8378 UpdateExpression: 'UpdateExpression',
8379 VariableDeclaration: 'VariableDeclaration',
8380 VariableDeclarator: 'VariableDeclarator',
8381 WhileStatement: 'WhileStatement',
8382 WithStatement: 'WithStatement',
8383 YieldExpression: 'YieldExpression'
8384 };
8385
8386 PlaceHolders = {
8387 ArrowParameterPlaceHolder: 'ArrowParameterPlaceHolder'
8388 };
8389
8390 // Error messages should be identical to V8.
8391 Messages = {
8392 UnexpectedToken: 'Unexpected token %0',
8393 UnexpectedNumber: 'Unexpected number',
8394 UnexpectedString: 'Unexpected string',
8395 UnexpectedIdentifier: 'Unexpected identifier',
8396 UnexpectedReserved: 'Unexpected reserved word',
8397 UnexpectedTemplate: 'Unexpected quasi %0',
8398 UnexpectedEOS: 'Unexpected end of input',
8399 NewlineAfterThrow: 'Illegal newline after throw',
8400 InvalidRegExp: 'Invalid regular expression',
8401 UnterminatedRegExp: 'Invalid regular expression: missing /',
8402 InvalidLHSInAssignment: 'Invalid left-hand side in assignment',
8403 InvalidLHSInForIn: 'Invalid left-hand side in for-in',
8404 InvalidLHSInForLoop: 'Invalid left-hand side in for-loop',
8405 MultipleDefaultsInSwitch: 'More than one default clause in switch statement',
8406 NoCatchOrFinally: 'Missing catch or finally after try',
8407 UnknownLabel: 'Undefined label \'%0\'',
8408 Redeclaration: '%0 \'%1\' has already been declared',
8409 IllegalContinue: 'Illegal continue statement',
8410 IllegalBreak: 'Illegal break statement',
8411 IllegalReturn: 'Illegal return statement',
8412 StrictModeWith: 'Strict mode code may not include a with statement',
8413 StrictCatchVariable: 'Catch variable may not be eval or arguments in strict mode',
8414 StrictVarName: 'Variable name may not be eval or arguments in strict mode',
8415 StrictParamName: 'Parameter name eval or arguments is not allowed in strict mode',
8416 StrictParamDupe: 'Strict mode function may not have duplicate parameter names',
8417 StrictFunctionName: 'Function name may not be eval or arguments in strict mode',
8418 StrictOctalLiteral: 'Octal literals are not allowed in strict mode.',
8419 StrictDelete: 'Delete of an unqualified identifier in strict mode.',
8420 StrictLHSAssignment: 'Assignment to eval or arguments is not allowed in strict mode',
8421 StrictLHSPostfix: 'Postfix increment/decrement may not have eval or arguments operand in strict mode',
8422 StrictLHSPrefix: 'Prefix increment/decrement may not have eval or arguments operand in strict mode',
8423 StrictReservedWord: 'Use of future reserved word in strict mode',
8424 TemplateOctalLiteral: 'Octal literals are not allowed in template strings.',
8425 ParameterAfterRestParameter: 'Rest parameter must be last formal parameter',
8426 DefaultRestParameter: 'Unexpected token =',
8427 ObjectPatternAsRestParameter: 'Unexpected token {',
8428 DuplicateProtoProperty: 'Duplicate __proto__ fields are not allowed in object literals',
8429 ConstructorSpecialMethod: 'Class constructor may not be an accessor',
8430 DuplicateConstructor: 'A class may only have one constructor',
8431 StaticPrototype: 'Classes may not have static property named prototype',
8432 MissingFromClause: 'Unexpected token',
8433 NoAsAfterImportNamespace: 'Unexpected token',
8434 InvalidModuleSpecifier: 'Unexpected token',
8435 IllegalImportDeclaration: 'Unexpected token',
8436 IllegalExportDeclaration: 'Unexpected token',
8437 DuplicateBinding: 'Duplicate binding %0'
8438 };
8439
8440 // See also tools/generate-unicode-regex.js.
8441 Regex = {
8442 // ECMAScript 6/Unicode v7.0.0 NonAsciiIdentifierStart:
8443 NonAsciiIdentifierStart: /[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\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-\u08B2\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\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-\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-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\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\u2118-\u211D\u2124\u2126\u2128\u212A-\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\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309B-\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-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA78E\uA790-\uA7AD\uA7B0\uA7B1\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB5F\uAB64\uAB65\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]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDE80-\uDE9C\uDEA0-\uDED0\uDF00-\uDF1F\uDF30-\uDF4A\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00\uDE10-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE4\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48]|\uD804[\uDC03-\uDC37\uDC83-\uDCAF\uDCD0-\uDCE8\uDD03-\uDD26\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDDA\uDE00-\uDE11\uDE13-\uDE2B\uDEB0-\uDEDE\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF5D-\uDF61]|\uD805[\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDE00-\uDE2F\uDE44\uDE80-\uDEAA]|\uD806[\uDCA0-\uDCDF\uDCFF\uDEC0-\uDEF8]|\uD808[\uDC00-\uDF98]|\uD809[\uDC00-\uDC6E]|[\uD80C\uD840-\uD868\uD86A-\uD86C][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50\uDF93-\uDF9F]|\uD82C[\uDC00\uDC01]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB]|\uD83A[\uDC00-\uDCC4]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D]|\uD87E[\uDC00-\uDE1D]/,
8444
8445 // ECMAScript 6/Unicode v7.0.0 NonAsciiIdentifierPart:
8446 NonAsciiIdentifierPart: /[\xAA\xB5\xB7\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\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-\u08B2\u08E4-\u0963\u0966-\u096F\u0971-\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\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58\u0C59\u0C60-\u0C63\u0C66-\u0C6F\u0C81-\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\u0D01-\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\u0DE6-\u0DEF\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\u1369-\u1371\u1380-\u138F\u13A0-\u13F4\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\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-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19DA\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1CD0-\u1CD2\u1CD4-\u1CF6\u1CF8\u1CF9\u1D00-\u1DF5\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\u2118-\u211D\u2124\u2126\u2128\u212A-\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\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099-\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-\uA69D\uA69F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA78E\uA790-\uA7AD\uA7B0\uA7B1\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C4\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB5F\uAB64\uAB65\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-\uFE2D\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]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDDFD\uDE80-\uDE9C\uDEA0-\uDED0\uDEE0\uDF00-\uDF1F\uDF30-\uDF4A\uDF50-\uDF7A\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCA0-\uDCA9\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00-\uDE03\uDE05\uDE06\uDE0C-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE38-\uDE3A\uDE3F\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE6\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48]|\uD804[\uDC00-\uDC46\uDC66-\uDC6F\uDC7F-\uDCBA\uDCD0-\uDCE8\uDCF0-\uDCF9\uDD00-\uDD34\uDD36-\uDD3F\uDD50-\uDD73\uDD76\uDD80-\uDDC4\uDDD0-\uDDDA\uDE00-\uDE11\uDE13-\uDE37\uDEB0-\uDEEA\uDEF0-\uDEF9\uDF01-\uDF03\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3C-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF57\uDF5D-\uDF63\uDF66-\uDF6C\uDF70-\uDF74]|\uD805[\uDC80-\uDCC5\uDCC7\uDCD0-\uDCD9\uDD80-\uDDB5\uDDB8-\uDDC0\uDE00-\uDE40\uDE44\uDE50-\uDE59\uDE80-\uDEB7\uDEC0-\uDEC9]|\uD806[\uDCA0-\uDCE9\uDCFF\uDEC0-\uDEF8]|\uD808[\uDC00-\uDF98]|\uD809[\uDC00-\uDC6E]|[\uD80C\uD840-\uD868\uD86A-\uD86C][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDE60-\uDE69\uDED0-\uDEED\uDEF0-\uDEF4\uDF00-\uDF36\uDF40-\uDF43\uDF50-\uDF59\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50-\uDF7E\uDF8F-\uDF9F]|\uD82C[\uDC00\uDC01]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99\uDC9D\uDC9E]|\uD834[\uDD65-\uDD69\uDD6D-\uDD72\uDD7B-\uDD82\uDD85-\uDD8B\uDDAA-\uDDAD\uDE42-\uDE44]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB\uDFCE-\uDFFF]|\uD83A[\uDC00-\uDCC4\uDCD0-\uDCD6]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D]|\uD87E[\uDC00-\uDE1D]|\uDB40[\uDD00-\uDDEF]/
8447 };
8448
8449 // Ensure the condition is true, otherwise throw an error.
8450 // This is only to have a better contract semantic, i.e. another safety net
8451 // to catch a logic error. The condition shall be fulfilled in normal case.
8452 // Do NOT use this to enforce a certain condition on any user input.
8453
8454 function assert(condition, message) {
8455 /* istanbul ignore if */
8456 if (!condition) {
8457 throw new Error('ASSERT: ' + message);
8458 }
8459 }
8460
8461 function isDecimalDigit(ch) {
8462 return (ch >= 0x30 && ch <= 0x39); // 0..9
8463 }
8464
8465 function isHexDigit(ch) {
8466 return '0123456789abcdefABCDEF'.indexOf(ch) >= 0;
8467 }
8468
8469 function isOctalDigit(ch) {
8470 return '01234567'.indexOf(ch) >= 0;
8471 }
8472
8473 function octalToDecimal(ch) {
8474 // \0 is not octal escape sequence
8475 var octal = (ch !== '0'), code = '01234567'.indexOf(ch);
8476
8477 if (index < length && isOctalDigit(source[index])) {
8478 octal = true;
8479 code = code * 8 + '01234567'.indexOf(source[index++]);
8480
8481 // 3 digits are only allowed when string starts
8482 // with 0, 1, 2, 3
8483 if ('0123'.indexOf(ch) >= 0 &&
8484 index < length &&
8485 isOctalDigit(source[index])) {
8486 code = code * 8 + '01234567'.indexOf(source[index++]);
8487 }
8488 }
8489
8490 return {
8491 code: code,
8492 octal: octal
8493 };
8494 }
8495
8496 // ECMA-262 11.2 White Space
8497
8498 function isWhiteSpace(ch) {
8499 return (ch === 0x20) || (ch === 0x09) || (ch === 0x0B) || (ch === 0x0C) || (ch === 0xA0) ||
8500 (ch >= 0x1680 && [0x1680, 0x180E, 0x2000, 0x2001, 0x2002, 0x2003, 0x2004, 0x2005, 0x2006, 0x2007, 0x2008, 0x2009, 0x200A, 0x202F, 0x205F, 0x3000, 0xFEFF].indexOf(ch) >= 0);
8501 }
8502
8503 // ECMA-262 11.3 Line Terminators
8504
8505 function isLineTerminator(ch) {
8506 return (ch === 0x0A) || (ch === 0x0D) || (ch === 0x2028) || (ch === 0x2029);
8507 }
8508
8509 // ECMA-262 11.6 Identifier Names and Identifiers
8510
8511 function fromCodePoint(cp) {
8512 return (cp < 0x10000) ? String.fromCharCode(cp) :
8513 String.fromCharCode(0xD800 + ((cp - 0x10000) >> 10)) +
8514 String.fromCharCode(0xDC00 + ((cp - 0x10000) & 1023));
8515 }
8516
8517 function isIdentifierStart(ch) {
8518 return (ch === 0x24) || (ch === 0x5F) || // $ (dollar) and _ (underscore)
8519 (ch >= 0x41 && ch <= 0x5A) || // A..Z
8520 (ch >= 0x61 && ch <= 0x7A) || // a..z
8521 (ch === 0x5C) || // \ (backslash)
8522 ((ch >= 0x80) && Regex.NonAsciiIdentifierStart.test(fromCodePoint(ch)));
8523 }
8524
8525 function isIdentifierPart(ch) {
8526 return (ch === 0x24) || (ch === 0x5F) || // $ (dollar) and _ (underscore)
8527 (ch >= 0x41 && ch <= 0x5A) || // A..Z
8528 (ch >= 0x61 && ch <= 0x7A) || // a..z
8529 (ch >= 0x30 && ch <= 0x39) || // 0..9
8530 (ch === 0x5C) || // \ (backslash)
8531 ((ch >= 0x80) && Regex.NonAsciiIdentifierPart.test(fromCodePoint(ch)));
8532 }
8533
8534 // ECMA-262 11.6.2.2 Future Reserved Words
8535
8536 function isFutureReservedWord(id) {
8537 switch (id) {
8538 case 'enum':
8539 case 'export':
8540 case 'import':
8541 case 'super':
8542 return true;
8543 default:
8544 return false;
8545 }
8546 }
8547
8548 function isStrictModeReservedWord(id) {
8549 switch (id) {
8550 case 'implements':
8551 case 'interface':
8552 case 'package':
8553 case 'private':
8554 case 'protected':
8555 case 'public':
8556 case 'static':
8557 case 'yield':
8558 case 'let':
8559 return true;
8560 default:
8561 return false;
8562 }
8563 }
8564
8565 function isRestrictedWord(id) {
8566 return id === 'eval' || id === 'arguments';
8567 }
8568
8569 // ECMA-262 11.6.2.1 Keywords
8570
8571 function isKeyword(id) {
8572 switch (id.length) {
8573 case 2:
8574 return (id === 'if') || (id === 'in') || (id === 'do');
8575 case 3:
8576 return (id === 'var') || (id === 'for') || (id === 'new') ||
8577 (id === 'try') || (id === 'let');
8578 case 4:
8579 return (id === 'this') || (id === 'else') || (id === 'case') ||
8580 (id === 'void') || (id === 'with') || (id === 'enum');
8581 case 5:
8582 return (id === 'while') || (id === 'break') || (id === 'catch') ||
8583 (id === 'throw') || (id === 'const') || (id === 'yield') ||
8584 (id === 'class') || (id === 'super');
8585 case 6:
8586 return (id === 'return') || (id === 'typeof') || (id === 'delete') ||
8587 (id === 'switch') || (id === 'export') || (id === 'import');
8588 case 7:
8589 return (id === 'default') || (id === 'finally') || (id === 'extends');
8590 case 8:
8591 return (id === 'function') || (id === 'continue') || (id === 'debugger');
8592 case 10:
8593 return (id === 'instanceof');
8594 default:
8595 return false;
8596 }
8597 }
8598
8599 // ECMA-262 11.4 Comments
8600
8601 function addComment(type, value, start, end, loc) {
8602 var comment;
8603
8604 assert(typeof start === 'number', 'Comment must have valid position');
8605
8606 state.lastCommentStart = start;
8607
8608 comment = {
8609 type: type,
8610 value: value
8611 };
8612 if (extra.range) {
8613 comment.range = [start, end];
8614 }
8615 if (extra.loc) {
8616 comment.loc = loc;
8617 }
8618 extra.comments.push(comment);
8619 if (extra.attachComment) {
8620 extra.leadingComments.push(comment);
8621 extra.trailingComments.push(comment);
8622 }
8623 if (extra.tokenize) {
8624 comment.type = comment.type + 'Comment';
8625 if (extra.delegate) {
8626 comment = extra.delegate(comment);
8627 }
8628 extra.tokens.push(comment);
8629 }
8630 }
8631
8632 function skipSingleLineComment(offset) {
8633 var start, loc, ch, comment;
8634
8635 start = index - offset;
8636 loc = {
8637 start: {
8638 line: lineNumber,
8639 column: index - lineStart - offset
8640 }
8641 };
8642
8643 while (index < length) {
8644 ch = source.charCodeAt(index);
8645 ++index;
8646 if (isLineTerminator(ch)) {
8647 hasLineTerminator = true;
8648 if (extra.comments) {
8649 comment = source.slice(start + offset, index - 1);
8650 loc.end = {
8651 line: lineNumber,
8652 column: index - lineStart - 1
8653 };
8654 addComment('Line', comment, start, index - 1, loc);
8655 }
8656 if (ch === 13 && source.charCodeAt(index) === 10) {
8657 ++index;
8658 }
8659 ++lineNumber;
8660 lineStart = index;
8661 return;
8662 }
8663 }
8664
8665 if (extra.comments) {
8666 comment = source.slice(start + offset, index);
8667 loc.end = {
8668 line: lineNumber,
8669 column: index - lineStart
8670 };
8671 addComment('Line', comment, start, index, loc);
8672 }
8673 }
8674
8675 function skipMultiLineComment() {
8676 var start, loc, ch, comment;
8677
8678 if (extra.comments) {
8679 start = index - 2;
8680 loc = {
8681 start: {
8682 line: lineNumber,
8683 column: index - lineStart - 2
8684 }
8685 };
8686 }
8687
8688 while (index < length) {
8689 ch = source.charCodeAt(index);
8690 if (isLineTerminator(ch)) {
8691 if (ch === 0x0D && source.charCodeAt(index + 1) === 0x0A) {
8692 ++index;
8693 }
8694 hasLineTerminator = true;
8695 ++lineNumber;
8696 ++index;
8697 lineStart = index;
8698 } else if (ch === 0x2A) {
8699 // Block comment ends with '*/'.
8700 if (source.charCodeAt(index + 1) === 0x2F) {
8701 ++index;
8702 ++index;
8703 if (extra.comments) {
8704 comment = source.slice(start + 2, index - 2);
8705 loc.end = {
8706 line: lineNumber,
8707 column: index - lineStart
8708 };
8709 addComment('Block', comment, start, index, loc);
8710 }
8711 return;
8712 }
8713 ++index;
8714 } else {
8715 ++index;
8716 }
8717 }
8718
8719 // Ran off the end of the file - the whole thing is a comment
8720 if (extra.comments) {
8721 loc.end = {
8722 line: lineNumber,
8723 column: index - lineStart
8724 };
8725 comment = source.slice(start + 2, index);
8726 addComment('Block', comment, start, index, loc);
8727 }
8728 tolerateUnexpectedToken();
8729 }
8730
8731 function skipComment() {
8732 var ch, start;
8733 hasLineTerminator = false;
8734
8735 start = (index === 0);
8736 while (index < length) {
8737 ch = source.charCodeAt(index);
8738
8739 if (isWhiteSpace(ch)) {
8740 ++index;
8741 } else if (isLineTerminator(ch)) {
8742 hasLineTerminator = true;
8743 ++index;
8744 if (ch === 0x0D && source.charCodeAt(index) === 0x0A) {
8745 ++index;
8746 }
8747 ++lineNumber;
8748 lineStart = index;
8749 start = true;
8750 } else if (ch === 0x2F) { // U+002F is '/'
8751 ch = source.charCodeAt(index + 1);
8752 if (ch === 0x2F) {
8753 ++index;
8754 ++index;
8755 skipSingleLineComment(2);
8756 start = true;
8757 } else if (ch === 0x2A) { // U+002A is '*'
8758 ++index;
8759 ++index;
8760 skipMultiLineComment();
8761 } else {
8762 break;
8763 }
8764 } else if (start && ch === 0x2D) { // U+002D is '-'
8765 // U+003E is '>'
8766 if ((source.charCodeAt(index + 1) === 0x2D) && (source.charCodeAt(index + 2) === 0x3E)) {
8767 // '-->' is a single-line comment
8768 index += 3;
8769 skipSingleLineComment(3);
8770 } else {
8771 break;
8772 }
8773 } else if (ch === 0x3C) { // U+003C is '<'
8774 if (source.slice(index + 1, index + 4) === '!--') {
8775 ++index; // `<`
8776 ++index; // `!`
8777 ++index; // `-`
8778 ++index; // `-`
8779 skipSingleLineComment(4);
8780 } else {
8781 break;
8782 }
8783 } else {
8784 break;
8785 }
8786 }
8787 }
8788
8789 function scanHexEscape(prefix) {
8790 var i, len, ch, code = 0;
8791
8792 len = (prefix === 'u') ? 4 : 2;
8793 for (i = 0; i < len; ++i) {
8794 if (index < length && isHexDigit(source[index])) {
8795 ch = source[index++];
8796 code = code * 16 + '0123456789abcdef'.indexOf(ch.toLowerCase());
8797 } else {
8798 return '';
8799 }
8800 }
8801 return String.fromCharCode(code);
8802 }
8803
8804 function scanUnicodeCodePointEscape() {
8805 var ch, code;
8806
8807 ch = source[index];
8808 code = 0;
8809
8810 // At least, one hex digit is required.
8811 if (ch === '}') {
8812 throwUnexpectedToken();
8813 }
8814
8815 while (index < length) {
8816 ch = source[index++];
8817 if (!isHexDigit(ch)) {
8818 break;
8819 }
8820 code = code * 16 + '0123456789abcdef'.indexOf(ch.toLowerCase());
8821 }
8822
8823 if (code > 0x10FFFF || ch !== '}') {
8824 throwUnexpectedToken();
8825 }
8826
8827 return fromCodePoint(code);
8828 }
8829
8830 function codePointAt(i) {
8831 var cp, first, second;
8832
8833 cp = source.charCodeAt(i);
8834 if (cp >= 0xD800 && cp <= 0xDBFF) {
8835 second = source.charCodeAt(i + 1);
8836 if (second >= 0xDC00 && second <= 0xDFFF) {
8837 first = cp;
8838 cp = (first - 0xD800) * 0x400 + second - 0xDC00 + 0x10000;
8839 }
8840 }
8841
8842 return cp;
8843 }
8844
8845 function getComplexIdentifier() {
8846 var cp, ch, id;
8847
8848 cp = codePointAt(index);
8849 id = fromCodePoint(cp);
8850 index += id.length;
8851
8852 // '\u' (U+005C, U+0075) denotes an escaped character.
8853 if (cp === 0x5C) {
8854 if (source.charCodeAt(index) !== 0x75) {
8855 throwUnexpectedToken();
8856 }
8857 ++index;
8858 if (source[index] === '{') {
8859 ++index;
8860 ch = scanUnicodeCodePointEscape();
8861 } else {
8862 ch = scanHexEscape('u');
8863 cp = ch.charCodeAt(0);
8864 if (!ch || ch === '\\' || !isIdentifierStart(cp)) {
8865 throwUnexpectedToken();
8866 }
8867 }
8868 id = ch;
8869 }
8870
8871 while (index < length) {
8872 cp = codePointAt(index);
8873 if (!isIdentifierPart(cp)) {
8874 break;
8875 }
8876 ch = fromCodePoint(cp);
8877 id += ch;
8878 index += ch.length;
8879
8880 // '\u' (U+005C, U+0075) denotes an escaped character.
8881 if (cp === 0x5C) {
8882 id = id.substr(0, id.length - 1);
8883 if (source.charCodeAt(index) !== 0x75) {
8884 throwUnexpectedToken();
8885 }
8886 ++index;
8887 if (source[index] === '{') {
8888 ++index;
8889 ch = scanUnicodeCodePointEscape();
8890 } else {
8891 ch = scanHexEscape('u');
8892 cp = ch.charCodeAt(0);
8893 if (!ch || ch === '\\' || !isIdentifierPart(cp)) {
8894 throwUnexpectedToken();
8895 }
8896 }
8897 id += ch;
8898 }
8899 }
8900
8901 return id;
8902 }
8903
8904 function getIdentifier() {
8905 var start, ch;
8906
8907 start = index++;
8908 while (index < length) {
8909 ch = source.charCodeAt(index);
8910 if (ch === 0x5C) {
8911 // Blackslash (U+005C) marks Unicode escape sequence.
8912 index = start;
8913 return getComplexIdentifier();
8914 } else if (ch >= 0xD800 && ch < 0xDFFF) {
8915 // Need to handle surrogate pairs.
8916 index = start;
8917 return getComplexIdentifier();
8918 }
8919 if (isIdentifierPart(ch)) {
8920 ++index;
8921 } else {
8922 break;
8923 }
8924 }
8925
8926 return source.slice(start, index);
8927 }
8928
8929 function scanIdentifier() {
8930 var start, id, type;
8931
8932 start = index;
8933
8934 // Backslash (U+005C) starts an escaped character.
8935 id = (source.charCodeAt(index) === 0x5C) ? getComplexIdentifier() : getIdentifier();
8936
8937 // There is no keyword or literal with only one character.
8938 // Thus, it must be an identifier.
8939 if (id.length === 1) {
8940 type = Token.Identifier;
8941 } else if (isKeyword(id)) {
8942 type = Token.Keyword;
8943 } else if (id === 'null') {
8944 type = Token.NullLiteral;
8945 } else if (id === 'true' || id === 'false') {
8946 type = Token.BooleanLiteral;
8947 } else {
8948 type = Token.Identifier;
8949 }
8950
8951 return {
8952 type: type,
8953 value: id,
8954 lineNumber: lineNumber,
8955 lineStart: lineStart,
8956 start: start,
8957 end: index
8958 };
8959 }
8960
8961
8962 // ECMA-262 11.7 Punctuators
8963
8964 function scanPunctuator() {
8965 var token, str;
8966
8967 token = {
8968 type: Token.Punctuator,
8969 value: '',
8970 lineNumber: lineNumber,
8971 lineStart: lineStart,
8972 start: index,
8973 end: index
8974 };
8975
8976 // Check for most common single-character punctuators.
8977 str = source[index];
8978 switch (str) {
8979
8980 case '(':
8981 if (extra.tokenize) {
8982 extra.openParenToken = extra.tokenValues.length;
8983 }
8984 ++index;
8985 break;
8986
8987 case '{':
8988 if (extra.tokenize) {
8989 extra.openCurlyToken = extra.tokenValues.length;
8990 }
8991 state.curlyStack.push('{');
8992 ++index;
8993 break;
8994
8995 case '.':
8996 ++index;
8997 if (source[index] === '.' && source[index + 1] === '.') {
8998 // Spread operator: ...
8999 index += 2;
9000 str = '...';
9001 }
9002 break;
9003
9004 case '}':
9005 ++index;
9006 state.curlyStack.pop();
9007 break;
9008 case ')':
9009 case ';':
9010 case ',':
9011 case '[':
9012 case ']':
9013 case ':':
9014 case '?':
9015 case '~':
9016 ++index;
9017 break;
9018
9019 default:
9020 // 4-character punctuator.
9021 str = source.substr(index, 4);
9022 if (str === '>>>=') {
9023 index += 4;
9024 } else {
9025
9026 // 3-character punctuators.
9027 str = str.substr(0, 3);
9028 if (str === '===' || str === '!==' || str === '>>>' ||
9029 str === '<<=' || str === '>>=') {
9030 index += 3;
9031 } else {
9032
9033 // 2-character punctuators.
9034 str = str.substr(0, 2);
9035 if (str === '&&' || str === '||' || str === '==' || str === '!=' ||
9036 str === '+=' || str === '-=' || str === '*=' || str === '/=' ||
9037 str === '++' || str === '--' || str === '<<' || str === '>>' ||
9038 str === '&=' || str === '|=' || str === '^=' || str === '%=' ||
9039 str === '<=' || str === '>=' || str === '=>') {
9040 index += 2;
9041 } else {
9042
9043 // 1-character punctuators.
9044 str = source[index];
9045 if ('<>=!+-*%&|^/'.indexOf(str) >= 0) {
9046 ++index;
9047 }
9048 }
9049 }
9050 }
9051 }
9052
9053 if (index === token.start) {
9054 throwUnexpectedToken();
9055 }
9056
9057 token.end = index;
9058 token.value = str;
9059 return token;
9060 }
9061
9062 // ECMA-262 11.8.3 Numeric Literals
9063
9064 function scanHexLiteral(start) {
9065 var number = '';
9066
9067 while (index < length) {
9068 if (!isHexDigit(source[index])) {
9069 break;
9070 }
9071 number += source[index++];
9072 }
9073
9074 if (number.length === 0) {
9075 throwUnexpectedToken();
9076 }
9077
9078 if (isIdentifierStart(source.charCodeAt(index))) {
9079 throwUnexpectedToken();
9080 }
9081
9082 return {
9083 type: Token.NumericLiteral,
9084 value: parseInt('0x' + number, 16),
9085 lineNumber: lineNumber,
9086 lineStart: lineStart,
9087 start: start,
9088 end: index
9089 };
9090 }
9091
9092 function scanBinaryLiteral(start) {
9093 var ch, number;
9094
9095 number = '';
9096
9097 while (index < length) {
9098 ch = source[index];
9099 if (ch !== '0' && ch !== '1') {
9100 break;
9101 }
9102 number += source[index++];
9103 }
9104
9105 if (number.length === 0) {
9106 // only 0b or 0B
9107 throwUnexpectedToken();
9108 }
9109
9110 if (index < length) {
9111 ch = source.charCodeAt(index);
9112 /* istanbul ignore else */
9113 if (isIdentifierStart(ch) || isDecimalDigit(ch)) {
9114 throwUnexpectedToken();
9115 }
9116 }
9117
9118 return {
9119 type: Token.NumericLiteral,
9120 value: parseInt(number, 2),
9121 lineNumber: lineNumber,
9122 lineStart: lineStart,
9123 start: start,
9124 end: index
9125 };
9126 }
9127
9128 function scanOctalLiteral(prefix, start) {
9129 var number, octal;
9130
9131 if (isOctalDigit(prefix)) {
9132 octal = true;
9133 number = '0' + source[index++];
9134 } else {
9135 octal = false;
9136 ++index;
9137 number = '';
9138 }
9139
9140 while (index < length) {
9141 if (!isOctalDigit(source[index])) {
9142 break;
9143 }
9144 number += source[index++];
9145 }
9146
9147 if (!octal && number.length === 0) {
9148 // only 0o or 0O
9149 throwUnexpectedToken();
9150 }
9151
9152 if (isIdentifierStart(source.charCodeAt(index)) || isDecimalDigit(source.charCodeAt(index))) {
9153 throwUnexpectedToken();
9154 }
9155
9156 return {
9157 type: Token.NumericLiteral,
9158 value: parseInt(number, 8),
9159 octal: octal,
9160 lineNumber: lineNumber,
9161 lineStart: lineStart,
9162 start: start,
9163 end: index
9164 };
9165 }
9166
9167 function isImplicitOctalLiteral() {
9168 var i, ch;
9169
9170 // Implicit octal, unless there is a non-octal digit.
9171 // (Annex B.1.1 on Numeric Literals)
9172 for (i = index + 1; i < length; ++i) {
9173 ch = source[i];
9174 if (ch === '8' || ch === '9') {
9175 return false;
9176 }
9177 if (!isOctalDigit(ch)) {
9178 return true;
9179 }
9180 }
9181
9182 return true;
9183 }
9184
9185 function scanNumericLiteral() {
9186 var number, start, ch;
9187
9188 ch = source[index];
9189 assert(isDecimalDigit(ch.charCodeAt(0)) || (ch === '.'),
9190 'Numeric literal must start with a decimal digit or a decimal point');
9191
9192 start = index;
9193 number = '';
9194 if (ch !== '.') {
9195 number = source[index++];
9196 ch = source[index];
9197
9198 // Hex number starts with '0x'.
9199 // Octal number starts with '0'.
9200 // Octal number in ES6 starts with '0o'.
9201 // Binary number in ES6 starts with '0b'.
9202 if (number === '0') {
9203 if (ch === 'x' || ch === 'X') {
9204 ++index;
9205 return scanHexLiteral(start);
9206 }
9207 if (ch === 'b' || ch === 'B') {
9208 ++index;
9209 return scanBinaryLiteral(start);
9210 }
9211 if (ch === 'o' || ch === 'O') {
9212 return scanOctalLiteral(ch, start);
9213 }
9214
9215 if (isOctalDigit(ch)) {
9216 if (isImplicitOctalLiteral()) {
9217 return scanOctalLiteral(ch, start);
9218 }
9219 }
9220 }
9221
9222 while (isDecimalDigit(source.charCodeAt(index))) {
9223 number += source[index++];
9224 }
9225 ch = source[index];
9226 }
9227
9228 if (ch === '.') {
9229 number += source[index++];
9230 while (isDecimalDigit(source.charCodeAt(index))) {
9231 number += source[index++];
9232 }
9233 ch = source[index];
9234 }
9235
9236 if (ch === 'e' || ch === 'E') {
9237 number += source[index++];
9238
9239 ch = source[index];
9240 if (ch === '+' || ch === '-') {
9241 number += source[index++];
9242 }
9243 if (isDecimalDigit(source.charCodeAt(index))) {
9244 while (isDecimalDigit(source.charCodeAt(index))) {
9245 number += source[index++];
9246 }
9247 } else {
9248 throwUnexpectedToken();
9249 }
9250 }
9251
9252 if (isIdentifierStart(source.charCodeAt(index))) {
9253 throwUnexpectedToken();
9254 }
9255
9256 return {
9257 type: Token.NumericLiteral,
9258 value: parseFloat(number),
9259 lineNumber: lineNumber,
9260 lineStart: lineStart,
9261 start: start,
9262 end: index
9263 };
9264 }
9265
9266 // ECMA-262 11.8.4 String Literals
9267
9268 function scanStringLiteral() {
9269 var str = '', quote, start, ch, unescaped, octToDec, octal = false;
9270
9271 quote = source[index];
9272 assert((quote === '\'' || quote === '"'),
9273 'String literal must starts with a quote');
9274
9275 start = index;
9276 ++index;
9277
9278 while (index < length) {
9279 ch = source[index++];
9280
9281 if (ch === quote) {
9282 quote = '';
9283 break;
9284 } else if (ch === '\\') {
9285 ch = source[index++];
9286 if (!ch || !isLineTerminator(ch.charCodeAt(0))) {
9287 switch (ch) {
9288 case 'u':
9289 case 'x':
9290 if (source[index] === '{') {
9291 ++index;
9292 str += scanUnicodeCodePointEscape();
9293 } else {
9294 unescaped = scanHexEscape(ch);
9295 if (!unescaped) {
9296 throw throwUnexpectedToken();
9297 }
9298 str += unescaped;
9299 }
9300 break;
9301 case 'n':
9302 str += '\n';
9303 break;
9304 case 'r':
9305 str += '\r';
9306 break;
9307 case 't':
9308 str += '\t';
9309 break;
9310 case 'b':
9311 str += '\b';
9312 break;
9313 case 'f':
9314 str += '\f';
9315 break;
9316 case 'v':
9317 str += '\x0B';
9318 break;
9319 case '8':
9320 case '9':
9321 str += ch;
9322 tolerateUnexpectedToken();
9323 break;
9324
9325 default:
9326 if (isOctalDigit(ch)) {
9327 octToDec = octalToDecimal(ch);
9328
9329 octal = octToDec.octal || octal;
9330 str += String.fromCharCode(octToDec.code);
9331 } else {
9332 str += ch;
9333 }
9334 break;
9335 }
9336 } else {
9337 ++lineNumber;
9338 if (ch === '\r' && source[index] === '\n') {
9339 ++index;
9340 }
9341 lineStart = index;
9342 }
9343 } else if (isLineTerminator(ch.charCodeAt(0))) {
9344 break;
9345 } else {
9346 str += ch;
9347 }
9348 }
9349
9350 if (quote !== '') {
9351 index = start;
9352 throwUnexpectedToken();
9353 }
9354
9355 return {
9356 type: Token.StringLiteral,
9357 value: str,
9358 octal: octal,
9359 lineNumber: startLineNumber,
9360 lineStart: startLineStart,
9361 start: start,
9362 end: index
9363 };
9364 }
9365
9366 // ECMA-262 11.8.6 Template Literal Lexical Components
9367
9368 function scanTemplate() {
9369 var cooked = '', ch, start, rawOffset, terminated, head, tail, restore, unescaped;
9370
9371 terminated = false;
9372 tail = false;
9373 start = index;
9374 head = (source[index] === '`');
9375 rawOffset = 2;
9376
9377 ++index;
9378
9379 while (index < length) {
9380 ch = source[index++];
9381 if (ch === '`') {
9382 rawOffset = 1;
9383 tail = true;
9384 terminated = true;
9385 break;
9386 } else if (ch === '$') {
9387 if (source[index] === '{') {
9388 state.curlyStack.push('${');
9389 ++index;
9390 terminated = true;
9391 break;
9392 }
9393 cooked += ch;
9394 } else if (ch === '\\') {
9395 ch = source[index++];
9396 if (!isLineTerminator(ch.charCodeAt(0))) {
9397 switch (ch) {
9398 case 'n':
9399 cooked += '\n';
9400 break;
9401 case 'r':
9402 cooked += '\r';
9403 break;
9404 case 't':
9405 cooked += '\t';
9406 break;
9407 case 'u':
9408 case 'x':
9409 if (source[index] === '{') {
9410 ++index;
9411 cooked += scanUnicodeCodePointEscape();
9412 } else {
9413 restore = index;
9414 unescaped = scanHexEscape(ch);
9415 if (unescaped) {
9416 cooked += unescaped;
9417 } else {
9418 index = restore;
9419 cooked += ch;
9420 }
9421 }
9422 break;
9423 case 'b':
9424 cooked += '\b';
9425 break;
9426 case 'f':
9427 cooked += '\f';
9428 break;
9429 case 'v':
9430 cooked += '\v';
9431 break;
9432
9433 default:
9434 if (ch === '0') {
9435 if (isDecimalDigit(source.charCodeAt(index))) {
9436 // Illegal: \01 \02 and so on
9437 throwError(Messages.TemplateOctalLiteral);
9438 }
9439 cooked += '\0';
9440 } else if (isOctalDigit(ch)) {
9441 // Illegal: \1 \2
9442 throwError(Messages.TemplateOctalLiteral);
9443 } else {
9444 cooked += ch;
9445 }
9446 break;
9447 }
9448 } else {
9449 ++lineNumber;
9450 if (ch === '\r' && source[index] === '\n') {
9451 ++index;
9452 }
9453 lineStart = index;
9454 }
9455 } else if (isLineTerminator(ch.charCodeAt(0))) {
9456 ++lineNumber;
9457 if (ch === '\r' && source[index] === '\n') {
9458 ++index;
9459 }
9460 lineStart = index;
9461 cooked += '\n';
9462 } else {
9463 cooked += ch;
9464 }
9465 }
9466
9467 if (!terminated) {
9468 throwUnexpectedToken();
9469 }
9470
9471 if (!head) {
9472 state.curlyStack.pop();
9473 }
9474
9475 return {
9476 type: Token.Template,
9477 value: {
9478 cooked: cooked,
9479 raw: source.slice(start + 1, index - rawOffset)
9480 },
9481 head: head,
9482 tail: tail,
9483 lineNumber: lineNumber,
9484 lineStart: lineStart,
9485 start: start,
9486 end: index
9487 };
9488 }
9489
9490 // ECMA-262 11.8.5 Regular Expression Literals
9491
9492 function testRegExp(pattern, flags) {
9493 // The BMP character to use as a replacement for astral symbols when
9494 // translating an ES6 "u"-flagged pattern to an ES5-compatible
9495 // approximation.
9496 // Note: replacing with '\uFFFF' enables false positives in unlikely
9497 // scenarios. For example, `[\u{1044f}-\u{10440}]` is an invalid
9498 // pattern that would not be detected by this substitution.
9499 var astralSubstitute = '\uFFFF',
9500 tmp = pattern;
9501
9502 if (flags.indexOf('u') >= 0) {
9503 tmp = tmp
9504 // Replace every Unicode escape sequence with the equivalent
9505 // BMP character or a constant ASCII code point in the case of
9506 // astral symbols. (See the above note on `astralSubstitute`
9507 // for more information.)
9508 .replace(/\\u\{([0-9a-fA-F]+)\}|\\u([a-fA-F0-9]{4})/g, function ($0, $1, $2) {
9509 var codePoint = parseInt($1 || $2, 16);
9510 if (codePoint > 0x10FFFF) {
9511 throwUnexpectedToken(null, Messages.InvalidRegExp);
9512 }
9513 if (codePoint <= 0xFFFF) {
9514 return String.fromCharCode(codePoint);
9515 }
9516 return astralSubstitute;
9517 })
9518 // Replace each paired surrogate with a single ASCII symbol to
9519 // avoid throwing on regular expressions that are only valid in
9520 // combination with the "u" flag.
9521 .replace(
9522 /[\uD800-\uDBFF][\uDC00-\uDFFF]/g,
9523 astralSubstitute
9524 );
9525 }
9526
9527 // First, detect invalid regular expressions.
9528 try {
9529 RegExp(tmp);
9530 } catch (e) {
9531 throwUnexpectedToken(null, Messages.InvalidRegExp);
9532 }
9533
9534 // Return a regular expression object for this pattern-flag pair, or
9535 // `null` in case the current environment doesn't support the flags it
9536 // uses.
9537 try {
9538 return new RegExp(pattern, flags);
9539 } catch (exception) {
9540 return null;
9541 }
9542 }
9543
9544 function scanRegExpBody() {
9545 var ch, str, classMarker, terminated, body;
9546
9547 ch = source[index];
9548 assert(ch === '/', 'Regular expression literal must start with a slash');
9549 str = source[index++];
9550
9551 classMarker = false;
9552 terminated = false;
9553 while (index < length) {
9554 ch = source[index++];
9555 str += ch;
9556 if (ch === '\\') {
9557 ch = source[index++];
9558 // ECMA-262 7.8.5
9559 if (isLineTerminator(ch.charCodeAt(0))) {
9560 throwUnexpectedToken(null, Messages.UnterminatedRegExp);
9561 }
9562 str += ch;
9563 } else if (isLineTerminator(ch.charCodeAt(0))) {
9564 throwUnexpectedToken(null, Messages.UnterminatedRegExp);
9565 } else if (classMarker) {
9566 if (ch === ']') {
9567 classMarker = false;
9568 }
9569 } else {
9570 if (ch === '/') {
9571 terminated = true;
9572 break;
9573 } else if (ch === '[') {
9574 classMarker = true;
9575 }
9576 }
9577 }
9578
9579 if (!terminated) {
9580 throwUnexpectedToken(null, Messages.UnterminatedRegExp);
9581 }
9582
9583 // Exclude leading and trailing slash.
9584 body = str.substr(1, str.length - 2);
9585 return {
9586 value: body,
9587 literal: str
9588 };
9589 }
9590
9591 function scanRegExpFlags() {
9592 var ch, str, flags, restore;
9593
9594 str = '';
9595 flags = '';
9596 while (index < length) {
9597 ch = source[index];
9598 if (!isIdentifierPart(ch.charCodeAt(0))) {
9599 break;
9600 }
9601
9602 ++index;
9603 if (ch === '\\' && index < length) {
9604 ch = source[index];
9605 if (ch === 'u') {
9606 ++index;
9607 restore = index;
9608 ch = scanHexEscape('u');
9609 if (ch) {
9610 flags += ch;
9611 for (str += '\\u'; restore < index; ++restore) {
9612 str += source[restore];
9613 }
9614 } else {
9615 index = restore;
9616 flags += 'u';
9617 str += '\\u';
9618 }
9619 tolerateUnexpectedToken();
9620 } else {
9621 str += '\\';
9622 tolerateUnexpectedToken();
9623 }
9624 } else {
9625 flags += ch;
9626 str += ch;
9627 }
9628 }
9629
9630 return {
9631 value: flags,
9632 literal: str
9633 };
9634 }
9635
9636 function scanRegExp() {
9637 var start, body, flags, value;
9638 scanning = true;
9639
9640 lookahead = null;
9641 skipComment();
9642 start = index;
9643
9644 body = scanRegExpBody();
9645 flags = scanRegExpFlags();
9646 value = testRegExp(body.value, flags.value);
9647 scanning = false;
9648 if (extra.tokenize) {
9649 return {
9650 type: Token.RegularExpression,
9651 value: value,
9652 regex: {
9653 pattern: body.value,
9654 flags: flags.value
9655 },
9656 lineNumber: lineNumber,
9657 lineStart: lineStart,
9658 start: start,
9659 end: index
9660 };
9661 }
9662
9663 return {
9664 literal: body.literal + flags.literal,
9665 value: value,
9666 regex: {
9667 pattern: body.value,
9668 flags: flags.value
9669 },
9670 start: start,
9671 end: index
9672 };
9673 }
9674
9675 function collectRegex() {
9676 var pos, loc, regex, token;
9677
9678 skipComment();
9679
9680 pos = index;
9681 loc = {
9682 start: {
9683 line: lineNumber,
9684 column: index - lineStart
9685 }
9686 };
9687
9688 regex = scanRegExp();
9689
9690 loc.end = {
9691 line: lineNumber,
9692 column: index - lineStart
9693 };
9694
9695 /* istanbul ignore next */
9696 if (!extra.tokenize) {
9697 // Pop the previous token, which is likely '/' or '/='
9698 if (extra.tokens.length > 0) {
9699 token = extra.tokens[extra.tokens.length - 1];
9700 if (token.range[0] === pos && token.type === 'Punctuator') {
9701 if (token.value === '/' || token.value === '/=') {
9702 extra.tokens.pop();
9703 }
9704 }
9705 }
9706
9707 extra.tokens.push({
9708 type: 'RegularExpression',
9709 value: regex.literal,
9710 regex: regex.regex,
9711 range: [pos, index],
9712 loc: loc
9713 });
9714 }
9715
9716 return regex;
9717 }
9718
9719 function isIdentifierName(token) {
9720 return token.type === Token.Identifier ||
9721 token.type === Token.Keyword ||
9722 token.type === Token.BooleanLiteral ||
9723 token.type === Token.NullLiteral;
9724 }
9725
9726 // Using the following algorithm:
9727 // https://github.com/mozilla/sweet.js/wiki/design
9728
9729 function advanceSlash() {
9730 var regex, previous, check;
9731
9732 function testKeyword(value) {
9733 return value && (value.length > 1) && (value[0] >= 'a') && (value[0] <= 'z');
9734 }
9735
9736 previous = extra.tokenValues[extra.tokens.length - 1];
9737 regex = (previous !== null);
9738
9739 switch (previous) {
9740 case 'this':
9741 case ']':
9742 regex = false;
9743 break;
9744
9745 case ')':
9746 check = extra.tokenValues[extra.openParenToken - 1];
9747 regex = (check === 'if' || check === 'while' || check === 'for' || check === 'with');
9748 break;
9749
9750 case '}':
9751 // Dividing a function by anything makes little sense,
9752 // but we have to check for that.
9753 regex = false;
9754 if (testKeyword(extra.tokenValues[extra.openCurlyToken - 3])) {
9755 // Anonymous function, e.g. function(){} /42
9756 check = extra.tokenValues[extra.openCurlyToken - 4];
9757 regex = check ? (FnExprTokens.indexOf(check) < 0) : false;
9758 } else if (testKeyword(extra.tokenValues[extra.openCurlyToken - 4])) {
9759 // Named function, e.g. function f(){} /42/
9760 check = extra.tokenValues[extra.openCurlyToken - 5];
9761 regex = check ? (FnExprTokens.indexOf(check) < 0) : true;
9762 }
9763 }
9764
9765 return regex ? collectRegex() : scanPunctuator();
9766 }
9767
9768 function advance() {
9769 var cp, token;
9770
9771 if (index >= length) {
9772 return {
9773 type: Token.EOF,
9774 lineNumber: lineNumber,
9775 lineStart: lineStart,
9776 start: index,
9777 end: index
9778 };
9779 }
9780
9781 cp = source.charCodeAt(index);
9782
9783 if (isIdentifierStart(cp)) {
9784 token = scanIdentifier();
9785 if (strict && isStrictModeReservedWord(token.value)) {
9786 token.type = Token.Keyword;
9787 }
9788 return token;
9789 }
9790
9791 // Very common: ( and ) and ;
9792 if (cp === 0x28 || cp === 0x29 || cp === 0x3B) {
9793 return scanPunctuator();
9794 }
9795
9796 // String literal starts with single quote (U+0027) or double quote (U+0022).
9797 if (cp === 0x27 || cp === 0x22) {
9798 return scanStringLiteral();
9799 }
9800
9801 // Dot (.) U+002E can also start a floating-point number, hence the need
9802 // to check the next character.
9803 if (cp === 0x2E) {
9804 if (isDecimalDigit(source.charCodeAt(index + 1))) {
9805 return scanNumericLiteral();
9806 }
9807 return scanPunctuator();
9808 }
9809
9810 if (isDecimalDigit(cp)) {
9811 return scanNumericLiteral();
9812 }
9813
9814 // Slash (/) U+002F can also start a regex.
9815 if (extra.tokenize && cp === 0x2F) {
9816 return advanceSlash();
9817 }
9818
9819 // Template literals start with ` (U+0060) for template head
9820 // or } (U+007D) for template middle or template tail.
9821 if (cp === 0x60 || (cp === 0x7D && state.curlyStack[state.curlyStack.length - 1] === '${')) {
9822 return scanTemplate();
9823 }
9824
9825 // Possible identifier start in a surrogate pair.
9826 if (cp >= 0xD800 && cp < 0xDFFF) {
9827 cp = codePointAt(index);
9828 if (isIdentifierStart(cp)) {
9829 return scanIdentifier();
9830 }
9831 }
9832
9833 return scanPunctuator();
9834 }
9835
9836 function collectToken() {
9837 var loc, token, value, entry;
9838
9839 loc = {
9840 start: {
9841 line: lineNumber,
9842 column: index - lineStart
9843 }
9844 };
9845
9846 token = advance();
9847 loc.end = {
9848 line: lineNumber,
9849 column: index - lineStart
9850 };
9851
9852 if (token.type !== Token.EOF) {
9853 value = source.slice(token.start, token.end);
9854 entry = {
9855 type: TokenName[token.type],
9856 value: value,
9857 range: [token.start, token.end],
9858 loc: loc
9859 };
9860 if (token.regex) {
9861 entry.regex = {
9862 pattern: token.regex.pattern,
9863 flags: token.regex.flags
9864 };
9865 }
9866 if (extra.tokenValues) {
9867 extra.tokenValues.push((entry.type === 'Punctuator' || entry.type === 'Keyword') ? entry.value : null);
9868 }
9869 if (extra.tokenize) {
9870 if (!extra.range) {
9871 delete entry.range;
9872 }
9873 if (!extra.loc) {
9874 delete entry.loc;
9875 }
9876 if (extra.delegate) {
9877 entry = extra.delegate(entry);
9878 }
9879 }
9880 extra.tokens.push(entry);
9881 }
9882
9883 return token;
9884 }
9885
9886 function lex() {
9887 var token;
9888 scanning = true;
9889
9890 lastIndex = index;
9891 lastLineNumber = lineNumber;
9892 lastLineStart = lineStart;
9893
9894 skipComment();
9895
9896 token = lookahead;
9897
9898 startIndex = index;
9899 startLineNumber = lineNumber;
9900 startLineStart = lineStart;
9901
9902 lookahead = (typeof extra.tokens !== 'undefined') ? collectToken() : advance();
9903 scanning = false;
9904 return token;
9905 }
9906
9907 function peek() {
9908 scanning = true;
9909
9910 skipComment();
9911
9912 lastIndex = index;
9913 lastLineNumber = lineNumber;
9914 lastLineStart = lineStart;
9915
9916 startIndex = index;
9917 startLineNumber = lineNumber;
9918 startLineStart = lineStart;
9919
9920 lookahead = (typeof extra.tokens !== 'undefined') ? collectToken() : advance();
9921 scanning = false;
9922 }
9923
9924 function Position() {
9925 this.line = startLineNumber;
9926 this.column = startIndex - startLineStart;
9927 }
9928
9929 function SourceLocation() {
9930 this.start = new Position();
9931 this.end = null;
9932 }
9933
9934 function WrappingSourceLocation(startToken) {
9935 this.start = {
9936 line: startToken.lineNumber,
9937 column: startToken.start - startToken.lineStart
9938 };
9939 this.end = null;
9940 }
9941
9942 function Node() {
9943 if (extra.range) {
9944 this.range = [startIndex, 0];
9945 }
9946 if (extra.loc) {
9947 this.loc = new SourceLocation();
9948 }
9949 }
9950
9951 function WrappingNode(startToken) {
9952 if (extra.range) {
9953 this.range = [startToken.start, 0];
9954 }
9955 if (extra.loc) {
9956 this.loc = new WrappingSourceLocation(startToken);
9957 }
9958 }
9959
9960 WrappingNode.prototype = Node.prototype = {
9961
9962 processComment: function () {
9963 var lastChild,
9964 innerComments,
9965 leadingComments,
9966 trailingComments,
9967 bottomRight = extra.bottomRightStack,
9968 i,
9969 comment,
9970 last = bottomRight[bottomRight.length - 1];
9971
9972 if (this.type === Syntax.Program) {
9973 if (this.body.length > 0) {
9974 return;
9975 }
9976 }
9977 /**
9978 * patch innnerComments for properties empty block
9979 * `function a() {/** comments **\/}`
9980 */
9981
9982 if (this.type === Syntax.BlockStatement && this.body.length === 0) {
9983 innerComments = [];
9984 for (i = extra.leadingComments.length - 1; i >= 0; --i) {
9985 comment = extra.leadingComments[i];
9986 if (this.range[1] >= comment.range[1]) {
9987 innerComments.unshift(comment);
9988 extra.leadingComments.splice(i, 1);
9989 extra.trailingComments.splice(i, 1);
9990 }
9991 }
9992 if (innerComments.length) {
9993 this.innerComments = innerComments;
9994 //bottomRight.push(this);
9995 return;
9996 }
9997 }
9998
9999 if (extra.trailingComments.length > 0) {
10000 trailingComments = [];
10001 for (i = extra.trailingComments.length - 1; i >= 0; --i) {
10002 comment = extra.trailingComments[i];
10003 if (comment.range[0] >= this.range[1]) {
10004 trailingComments.unshift(comment);
10005 extra.trailingComments.splice(i, 1);
10006 }
10007 }
10008 extra.trailingComments = [];
10009 } else {
10010 if (last && last.trailingComments && last.trailingComments[0].range[0] >= this.range[1]) {
10011 trailingComments = last.trailingComments;
10012 delete last.trailingComments;
10013 }
10014 }
10015
10016 // Eating the stack.
10017 while (last && last.range[0] >= this.range[0]) {
10018 lastChild = bottomRight.pop();
10019 last = bottomRight[bottomRight.length - 1];
10020 }
10021
10022 if (lastChild) {
10023 if (lastChild.leadingComments) {
10024 leadingComments = [];
10025 for (i = lastChild.leadingComments.length - 1; i >= 0; --i) {
10026 comment = lastChild.leadingComments[i];
10027 if (comment.range[1] <= this.range[0]) {
10028 leadingComments.unshift(comment);
10029 lastChild.leadingComments.splice(i, 1);
10030 }
10031 }
10032
10033 if (!lastChild.leadingComments.length) {
10034 lastChild.leadingComments = undefined;
10035 }
10036 }
10037 } else if (extra.leadingComments.length > 0) {
10038 leadingComments = [];
10039 for (i = extra.leadingComments.length - 1; i >= 0; --i) {
10040 comment = extra.leadingComments[i];
10041 if (comment.range[1] <= this.range[0]) {
10042 leadingComments.unshift(comment);
10043 extra.leadingComments.splice(i, 1);
10044 }
10045 }
10046 }
10047
10048
10049 if (leadingComments && leadingComments.length > 0) {
10050 this.leadingComments = leadingComments;
10051 }
10052 if (trailingComments && trailingComments.length > 0) {
10053 this.trailingComments = trailingComments;
10054 }
10055
10056 bottomRight.push(this);
10057 },
10058
10059 finish: function () {
10060 if (extra.range) {
10061 this.range[1] = lastIndex;
10062 }
10063 if (extra.loc) {
10064 this.loc.end = {
10065 line: lastLineNumber,
10066 column: lastIndex - lastLineStart
10067 };
10068 if (extra.source) {
10069 this.loc.source = extra.source;
10070 }
10071 }
10072
10073 if (extra.attachComment) {
10074 this.processComment();
10075 }
10076 },
10077
10078 finishArrayExpression: function (elements) {
10079 this.type = Syntax.ArrayExpression;
10080 this.elements = elements;
10081 this.finish();
10082 return this;
10083 },
10084
10085 finishArrayPattern: function (elements) {
10086 this.type = Syntax.ArrayPattern;
10087 this.elements = elements;
10088 this.finish();
10089 return this;
10090 },
10091
10092 finishArrowFunctionExpression: function (params, defaults, body, expression) {
10093 this.type = Syntax.ArrowFunctionExpression;
10094 this.id = null;
10095 this.params = params;
10096 this.defaults = defaults;
10097 this.body = body;
10098 this.generator = false;
10099 this.expression = expression;
10100 this.finish();
10101 return this;
10102 },
10103
10104 finishAssignmentExpression: function (operator, left, right) {
10105 this.type = Syntax.AssignmentExpression;
10106 this.operator = operator;
10107 this.left = left;
10108 this.right = right;
10109 this.finish();
10110 return this;
10111 },
10112
10113 finishAssignmentPattern: function (left, right) {
10114 this.type = Syntax.AssignmentPattern;
10115 this.left = left;
10116 this.right = right;
10117 this.finish();
10118 return this;
10119 },
10120
10121 finishBinaryExpression: function (operator, left, right) {
10122 this.type = (operator === '||' || operator === '&&') ? Syntax.LogicalExpression : Syntax.BinaryExpression;
10123 this.operator = operator;
10124 this.left = left;
10125 this.right = right;
10126 this.finish();
10127 return this;
10128 },
10129
10130 finishBlockStatement: function (body) {
10131 this.type = Syntax.BlockStatement;
10132 this.body = body;
10133 this.finish();
10134 return this;
10135 },
10136
10137 finishBreakStatement: function (label) {
10138 this.type = Syntax.BreakStatement;
10139 this.label = label;
10140 this.finish();
10141 return this;
10142 },
10143
10144 finishCallExpression: function (callee, args) {
10145 this.type = Syntax.CallExpression;
10146 this.callee = callee;
10147 this.arguments = args;
10148 this.finish();
10149 return this;
10150 },
10151
10152 finishCatchClause: function (param, body) {
10153 this.type = Syntax.CatchClause;
10154 this.param = param;
10155 this.body = body;
10156 this.finish();
10157 return this;
10158 },
10159
10160 finishClassBody: function (body) {
10161 this.type = Syntax.ClassBody;
10162 this.body = body;
10163 this.finish();
10164 return this;
10165 },
10166
10167 finishClassDeclaration: function (id, superClass, body) {
10168 this.type = Syntax.ClassDeclaration;
10169 this.id = id;
10170 this.superClass = superClass;
10171 this.body = body;
10172 this.finish();
10173 return this;
10174 },
10175
10176 finishClassExpression: function (id, superClass, body) {
10177 this.type = Syntax.ClassExpression;
10178 this.id = id;
10179 this.superClass = superClass;
10180 this.body = body;
10181 this.finish();
10182 return this;
10183 },
10184
10185 finishConditionalExpression: function (test, consequent, alternate) {
10186 this.type = Syntax.ConditionalExpression;
10187 this.test = test;
10188 this.consequent = consequent;
10189 this.alternate = alternate;
10190 this.finish();
10191 return this;
10192 },
10193
10194 finishContinueStatement: function (label) {
10195 this.type = Syntax.ContinueStatement;
10196 this.label = label;
10197 this.finish();
10198 return this;
10199 },
10200
10201 finishDebuggerStatement: function () {
10202 this.type = Syntax.DebuggerStatement;
10203 this.finish();
10204 return this;
10205 },
10206
10207 finishDoWhileStatement: function (body, test) {
10208 this.type = Syntax.DoWhileStatement;
10209 this.body = body;
10210 this.test = test;
10211 this.finish();
10212 return this;
10213 },
10214
10215 finishEmptyStatement: function () {
10216 this.type = Syntax.EmptyStatement;
10217 this.finish();
10218 return this;
10219 },
10220
10221 finishExpressionStatement: function (expression) {
10222 this.type = Syntax.ExpressionStatement;
10223 this.expression = expression;
10224 this.finish();
10225 return this;
10226 },
10227
10228 finishForStatement: function (init, test, update, body) {
10229 this.type = Syntax.ForStatement;
10230 this.init = init;
10231 this.test = test;
10232 this.update = update;
10233 this.body = body;
10234 this.finish();
10235 return this;
10236 },
10237
10238 finishForOfStatement: function (left, right, body) {
10239 this.type = Syntax.ForOfStatement;
10240 this.left = left;
10241 this.right = right;
10242 this.body = body;
10243 this.finish();
10244 return this;
10245 },
10246
10247 finishForInStatement: function (left, right, body) {
10248 this.type = Syntax.ForInStatement;
10249 this.left = left;
10250 this.right = right;
10251 this.body = body;
10252 this.each = false;
10253 this.finish();
10254 return this;
10255 },
10256
10257 finishFunctionDeclaration: function (id, params, defaults, body, generator) {
10258 this.type = Syntax.FunctionDeclaration;
10259 this.id = id;
10260 this.params = params;
10261 this.defaults = defaults;
10262 this.body = body;
10263 this.generator = generator;
10264 this.expression = false;
10265 this.finish();
10266 return this;
10267 },
10268
10269 finishFunctionExpression: function (id, params, defaults, body, generator) {
10270 this.type = Syntax.FunctionExpression;
10271 this.id = id;
10272 this.params = params;
10273 this.defaults = defaults;
10274 this.body = body;
10275 this.generator = generator;
10276 this.expression = false;
10277 this.finish();
10278 return this;
10279 },
10280
10281 finishIdentifier: function (name) {
10282 this.type = Syntax.Identifier;
10283 this.name = name;
10284 this.finish();
10285 return this;
10286 },
10287
10288 finishIfStatement: function (test, consequent, alternate) {
10289 this.type = Syntax.IfStatement;
10290 this.test = test;
10291 this.consequent = consequent;
10292 this.alternate = alternate;
10293 this.finish();
10294 return this;
10295 },
10296
10297 finishLabeledStatement: function (label, body) {
10298 this.type = Syntax.LabeledStatement;
10299 this.label = label;
10300 this.body = body;
10301 this.finish();
10302 return this;
10303 },
10304
10305 finishLiteral: function (token) {
10306 this.type = Syntax.Literal;
10307 this.value = token.value;
10308 this.raw = source.slice(token.start, token.end);
10309 if (token.regex) {
10310 this.regex = token.regex;
10311 }
10312 this.finish();
10313 return this;
10314 },
10315
10316 finishMemberExpression: function (accessor, object, property) {
10317 this.type = Syntax.MemberExpression;
10318 this.computed = accessor === '[';
10319 this.object = object;
10320 this.property = property;
10321 this.finish();
10322 return this;
10323 },
10324
10325 finishMetaProperty: function (meta, property) {
10326 this.type = Syntax.MetaProperty;
10327 this.meta = meta;
10328 this.property = property;
10329 this.finish();
10330 return this;
10331 },
10332
10333 finishNewExpression: function (callee, args) {
10334 this.type = Syntax.NewExpression;
10335 this.callee = callee;
10336 this.arguments = args;
10337 this.finish();
10338 return this;
10339 },
10340
10341 finishObjectExpression: function (properties) {
10342 this.type = Syntax.ObjectExpression;
10343 this.properties = properties;
10344 this.finish();
10345 return this;
10346 },
10347
10348 finishObjectPattern: function (properties) {
10349 this.type = Syntax.ObjectPattern;
10350 this.properties = properties;
10351 this.finish();
10352 return this;
10353 },
10354
10355 finishPostfixExpression: function (operator, argument) {
10356 this.type = Syntax.UpdateExpression;
10357 this.operator = operator;
10358 this.argument = argument;
10359 this.prefix = false;
10360 this.finish();
10361 return this;
10362 },
10363
10364 finishProgram: function (body, sourceType) {
10365 this.type = Syntax.Program;
10366 this.body = body;
10367 this.sourceType = sourceType;
10368 this.finish();
10369 return this;
10370 },
10371
10372 finishProperty: function (kind, key, computed, value, method, shorthand) {
10373 this.type = Syntax.Property;
10374 this.key = key;
10375 this.computed = computed;
10376 this.value = value;
10377 this.kind = kind;
10378 this.method = method;
10379 this.shorthand = shorthand;
10380 this.finish();
10381 return this;
10382 },
10383
10384 finishRestElement: function (argument) {
10385 this.type = Syntax.RestElement;
10386 this.argument = argument;
10387 this.finish();
10388 return this;
10389 },
10390
10391 finishReturnStatement: function (argument) {
10392 this.type = Syntax.ReturnStatement;
10393 this.argument = argument;
10394 this.finish();
10395 return this;
10396 },
10397
10398 finishSequenceExpression: function (expressions) {
10399 this.type = Syntax.SequenceExpression;
10400 this.expressions = expressions;
10401 this.finish();
10402 return this;
10403 },
10404
10405 finishSpreadElement: function (argument) {
10406 this.type = Syntax.SpreadElement;
10407 this.argument = argument;
10408 this.finish();
10409 return this;
10410 },
10411
10412 finishSwitchCase: function (test, consequent) {
10413 this.type = Syntax.SwitchCase;
10414 this.test = test;
10415 this.consequent = consequent;
10416 this.finish();
10417 return this;
10418 },
10419
10420 finishSuper: function () {
10421 this.type = Syntax.Super;
10422 this.finish();
10423 return this;
10424 },
10425
10426 finishSwitchStatement: function (discriminant, cases) {
10427 this.type = Syntax.SwitchStatement;
10428 this.discriminant = discriminant;
10429 this.cases = cases;
10430 this.finish();
10431 return this;
10432 },
10433
10434 finishTaggedTemplateExpression: function (tag, quasi) {
10435 this.type = Syntax.TaggedTemplateExpression;
10436 this.tag = tag;
10437 this.quasi = quasi;
10438 this.finish();
10439 return this;
10440 },
10441
10442 finishTemplateElement: function (value, tail) {
10443 this.type = Syntax.TemplateElement;
10444 this.value = value;
10445 this.tail = tail;
10446 this.finish();
10447 return this;
10448 },
10449
10450 finishTemplateLiteral: function (quasis, expressions) {
10451 this.type = Syntax.TemplateLiteral;
10452 this.quasis = quasis;
10453 this.expressions = expressions;
10454 this.finish();
10455 return this;
10456 },
10457
10458 finishThisExpression: function () {
10459 this.type = Syntax.ThisExpression;
10460 this.finish();
10461 return this;
10462 },
10463
10464 finishThrowStatement: function (argument) {
10465 this.type = Syntax.ThrowStatement;
10466 this.argument = argument;
10467 this.finish();
10468 return this;
10469 },
10470
10471 finishTryStatement: function (block, handler, finalizer) {
10472 this.type = Syntax.TryStatement;
10473 this.block = block;
10474 this.guardedHandlers = [];
10475 this.handlers = handler ? [handler] : [];
10476 this.handler = handler;
10477 this.finalizer = finalizer;
10478 this.finish();
10479 return this;
10480 },
10481
10482 finishUnaryExpression: function (operator, argument) {
10483 this.type = (operator === '++' || operator === '--') ? Syntax.UpdateExpression : Syntax.UnaryExpression;
10484 this.operator = operator;
10485 this.argument = argument;
10486 this.prefix = true;
10487 this.finish();
10488 return this;
10489 },
10490
10491 finishVariableDeclaration: function (declarations) {
10492 this.type = Syntax.VariableDeclaration;
10493 this.declarations = declarations;
10494 this.kind = 'var';
10495 this.finish();
10496 return this;
10497 },
10498
10499 finishLexicalDeclaration: function (declarations, kind) {
10500 this.type = Syntax.VariableDeclaration;
10501 this.declarations = declarations;
10502 this.kind = kind;
10503 this.finish();
10504 return this;
10505 },
10506
10507 finishVariableDeclarator: function (id, init) {
10508 this.type = Syntax.VariableDeclarator;
10509 this.id = id;
10510 this.init = init;
10511 this.finish();
10512 return this;
10513 },
10514
10515 finishWhileStatement: function (test, body) {
10516 this.type = Syntax.WhileStatement;
10517 this.test = test;
10518 this.body = body;
10519 this.finish();
10520 return this;
10521 },
10522
10523 finishWithStatement: function (object, body) {
10524 this.type = Syntax.WithStatement;
10525 this.object = object;
10526 this.body = body;
10527 this.finish();
10528 return this;
10529 },
10530
10531 finishExportSpecifier: function (local, exported) {
10532 this.type = Syntax.ExportSpecifier;
10533 this.exported = exported || local;
10534 this.local = local;
10535 this.finish();
10536 return this;
10537 },
10538
10539 finishImportDefaultSpecifier: function (local) {
10540 this.type = Syntax.ImportDefaultSpecifier;
10541 this.local = local;
10542 this.finish();
10543 return this;
10544 },
10545
10546 finishImportNamespaceSpecifier: function (local) {
10547 this.type = Syntax.ImportNamespaceSpecifier;
10548 this.local = local;
10549 this.finish();
10550 return this;
10551 },
10552
10553 finishExportNamedDeclaration: function (declaration, specifiers, src) {
10554 this.type = Syntax.ExportNamedDeclaration;
10555 this.declaration = declaration;
10556 this.specifiers = specifiers;
10557 this.source = src;
10558 this.finish();
10559 return this;
10560 },
10561
10562 finishExportDefaultDeclaration: function (declaration) {
10563 this.type = Syntax.ExportDefaultDeclaration;
10564 this.declaration = declaration;
10565 this.finish();
10566 return this;
10567 },
10568
10569 finishExportAllDeclaration: function (src) {
10570 this.type = Syntax.ExportAllDeclaration;
10571 this.source = src;
10572 this.finish();
10573 return this;
10574 },
10575
10576 finishImportSpecifier: function (local, imported) {
10577 this.type = Syntax.ImportSpecifier;
10578 this.local = local || imported;
10579 this.imported = imported;
10580 this.finish();
10581 return this;
10582 },
10583
10584 finishImportDeclaration: function (specifiers, src) {
10585 this.type = Syntax.ImportDeclaration;
10586 this.specifiers = specifiers;
10587 this.source = src;
10588 this.finish();
10589 return this;
10590 },
10591
10592 finishYieldExpression: function (argument, delegate) {
10593 this.type = Syntax.YieldExpression;
10594 this.argument = argument;
10595 this.delegate = delegate;
10596 this.finish();
10597 return this;
10598 }
10599 };
10600
10601
10602 function recordError(error) {
10603 var e, existing;
10604
10605 for (e = 0; e < extra.errors.length; e++) {
10606 existing = extra.errors[e];
10607 // Prevent duplicated error.
10608 /* istanbul ignore next */
10609 if (existing.index === error.index && existing.message === error.message) {
10610 return;
10611 }
10612 }
10613
10614 extra.errors.push(error);
10615 }
10616
10617 function constructError(msg, column) {
10618 var error = new Error(msg);
10619 try {
10620 throw error;
10621 } catch (base) {
10622 /* istanbul ignore else */
10623 if (Object.create && Object.defineProperty) {
10624 error = Object.create(base);
10625 Object.defineProperty(error, 'column', { value: column });
10626 }
10627 } finally {
10628 return error;
10629 }
10630 }
10631
10632 function createError(line, pos, description) {
10633 var msg, column, error;
10634
10635 msg = 'Line ' + line + ': ' + description;
10636 column = pos - (scanning ? lineStart : lastLineStart) + 1;
10637 error = constructError(msg, column);
10638 error.lineNumber = line;
10639 error.description = description;
10640 error.index = pos;
10641 return error;
10642 }
10643
10644 // Throw an exception
10645
10646 function throwError(messageFormat) {
10647 var args, msg;
10648
10649 args = Array.prototype.slice.call(arguments, 1);
10650 msg = messageFormat.replace(/%(\d)/g,
10651 function (whole, idx) {
10652 assert(idx < args.length, 'Message reference must be in range');
10653 return args[idx];
10654 }
10655 );
10656
10657 throw createError(lastLineNumber, lastIndex, msg);
10658 }
10659
10660 function tolerateError(messageFormat) {
10661 var args, msg, error;
10662
10663 args = Array.prototype.slice.call(arguments, 1);
10664 /* istanbul ignore next */
10665 msg = messageFormat.replace(/%(\d)/g,
10666 function (whole, idx) {
10667 assert(idx < args.length, 'Message reference must be in range');
10668 return args[idx];
10669 }
10670 );
10671
10672 error = createError(lineNumber, lastIndex, msg);
10673 if (extra.errors) {
10674 recordError(error);
10675 } else {
10676 throw error;
10677 }
10678 }
10679
10680 // Throw an exception because of the token.
10681
10682 function unexpectedTokenError(token, message) {
10683 var value, msg = message || Messages.UnexpectedToken;
10684
10685 if (token) {
10686 if (!message) {
10687 msg = (token.type === Token.EOF) ? Messages.UnexpectedEOS :
10688 (token.type === Token.Identifier) ? Messages.UnexpectedIdentifier :
10689 (token.type === Token.NumericLiteral) ? Messages.UnexpectedNumber :
10690 (token.type === Token.StringLiteral) ? Messages.UnexpectedString :
10691 (token.type === Token.Template) ? Messages.UnexpectedTemplate :
10692 Messages.UnexpectedToken;
10693
10694 if (token.type === Token.Keyword) {
10695 if (isFutureReservedWord(token.value)) {
10696 msg = Messages.UnexpectedReserved;
10697 } else if (strict && isStrictModeReservedWord(token.value)) {
10698 msg = Messages.StrictReservedWord;
10699 }
10700 }
10701 }
10702
10703 value = (token.type === Token.Template) ? token.value.raw : token.value;
10704 } else {
10705 value = 'ILLEGAL';
10706 }
10707
10708 msg = msg.replace('%0', value);
10709
10710 return (token && typeof token.lineNumber === 'number') ?
10711 createError(token.lineNumber, token.start, msg) :
10712 createError(scanning ? lineNumber : lastLineNumber, scanning ? index : lastIndex, msg);
10713 }
10714
10715 function throwUnexpectedToken(token, message) {
10716 throw unexpectedTokenError(token, message);
10717 }
10718
10719 function tolerateUnexpectedToken(token, message) {
10720 var error = unexpectedTokenError(token, message);
10721 if (extra.errors) {
10722 recordError(error);
10723 } else {
10724 throw error;
10725 }
10726 }
10727
10728 // Expect the next token to match the specified punctuator.
10729 // If not, an exception will be thrown.
10730
10731 function expect(value) {
10732 var token = lex();
10733 if (token.type !== Token.Punctuator || token.value !== value) {
10734 throwUnexpectedToken(token);
10735 }
10736 }
10737
10738 /**
10739 * @name expectCommaSeparator
10740 * @description Quietly expect a comma when in tolerant mode, otherwise delegates
10741 * to <code>expect(value)</code>
10742 * @since 2.0
10743 */
10744 function expectCommaSeparator() {
10745 var token;
10746
10747 if (extra.errors) {
10748 token = lookahead;
10749 if (token.type === Token.Punctuator && token.value === ',') {
10750 lex();
10751 } else if (token.type === Token.Punctuator && token.value === ';') {
10752 lex();
10753 tolerateUnexpectedToken(token);
10754 } else {
10755 tolerateUnexpectedToken(token, Messages.UnexpectedToken);
10756 }
10757 } else {
10758 expect(',');
10759 }
10760 }
10761
10762 // Expect the next token to match the specified keyword.
10763 // If not, an exception will be thrown.
10764
10765 function expectKeyword(keyword) {
10766 var token = lex();
10767 if (token.type !== Token.Keyword || token.value !== keyword) {
10768 throwUnexpectedToken(token);
10769 }
10770 }
10771
10772 // Return true if the next token matches the specified punctuator.
10773
10774 function match(value) {
10775 return lookahead.type === Token.Punctuator && lookahead.value === value;
10776 }
10777
10778 // Return true if the next token matches the specified keyword
10779
10780 function matchKeyword(keyword) {
10781 return lookahead.type === Token.Keyword && lookahead.value === keyword;
10782 }
10783
10784 // Return true if the next token matches the specified contextual keyword
10785 // (where an identifier is sometimes a keyword depending on the context)
10786
10787 function matchContextualKeyword(keyword) {
10788 return lookahead.type === Token.Identifier && lookahead.value === keyword;
10789 }
10790
10791 // Return true if the next token is an assignment operator
10792
10793 function matchAssign() {
10794 var op;
10795
10796 if (lookahead.type !== Token.Punctuator) {
10797 return false;
10798 }
10799 op = lookahead.value;
10800 return op === '=' ||
10801 op === '*=' ||
10802 op === '/=' ||
10803 op === '%=' ||
10804 op === '+=' ||
10805 op === '-=' ||
10806 op === '<<=' ||
10807 op === '>>=' ||
10808 op === '>>>=' ||
10809 op === '&=' ||
10810 op === '^=' ||
10811 op === '|=';
10812 }
10813
10814 function consumeSemicolon() {
10815 // Catch the very common case first: immediately a semicolon (U+003B).
10816 if (source.charCodeAt(startIndex) === 0x3B || match(';')) {
10817 lex();
10818 return;
10819 }
10820
10821 if (hasLineTerminator) {
10822 return;
10823 }
10824
10825 // FIXME(ikarienator): this is seemingly an issue in the previous location info convention.
10826 lastIndex = startIndex;
10827 lastLineNumber = startLineNumber;
10828 lastLineStart = startLineStart;
10829
10830 if (lookahead.type !== Token.EOF && !match('}')) {
10831 throwUnexpectedToken(lookahead);
10832 }
10833 }
10834
10835 // Cover grammar support.
10836 //
10837 // When an assignment expression position starts with an left parenthesis, the determination of the type
10838 // of the syntax is to be deferred arbitrarily long until the end of the parentheses pair (plus a lookahead)
10839 // or the first comma. This situation also defers the determination of all the expressions nested in the pair.
10840 //
10841 // There are three productions that can be parsed in a parentheses pair that needs to be determined
10842 // after the outermost pair is closed. They are:
10843 //
10844 // 1. AssignmentExpression
10845 // 2. BindingElements
10846 // 3. AssignmentTargets
10847 //
10848 // In order to avoid exponential backtracking, we use two flags to denote if the production can be
10849 // binding element or assignment target.
10850 //
10851 // The three productions have the relationship:
10852 //
10853 // BindingElements ⊆ AssignmentTargets ⊆ AssignmentExpression
10854 //
10855 // with a single exception that CoverInitializedName when used directly in an Expression, generates
10856 // an early error. Therefore, we need the third state, firstCoverInitializedNameError, to track the
10857 // first usage of CoverInitializedName and report it when we reached the end of the parentheses pair.
10858 //
10859 // isolateCoverGrammar function runs the given parser function with a new cover grammar context, and it does not
10860 // effect the current flags. This means the production the parser parses is only used as an expression. Therefore
10861 // the CoverInitializedName check is conducted.
10862 //
10863 // inheritCoverGrammar function runs the given parse function with a new cover grammar context, and it propagates
10864 // the flags outside of the parser. This means the production the parser parses is used as a part of a potential
10865 // pattern. The CoverInitializedName check is deferred.
10866 function isolateCoverGrammar(parser) {
10867 var oldIsBindingElement = isBindingElement,
10868 oldIsAssignmentTarget = isAssignmentTarget,
10869 oldFirstCoverInitializedNameError = firstCoverInitializedNameError,
10870 result;
10871 isBindingElement = true;
10872 isAssignmentTarget = true;
10873 firstCoverInitializedNameError = null;
10874 result = parser();
10875 if (firstCoverInitializedNameError !== null) {
10876 throwUnexpectedToken(firstCoverInitializedNameError);
10877 }
10878 isBindingElement = oldIsBindingElement;
10879 isAssignmentTarget = oldIsAssignmentTarget;
10880 firstCoverInitializedNameError = oldFirstCoverInitializedNameError;
10881 return result;
10882 }
10883
10884 function inheritCoverGrammar(parser) {
10885 var oldIsBindingElement = isBindingElement,
10886 oldIsAssignmentTarget = isAssignmentTarget,
10887 oldFirstCoverInitializedNameError = firstCoverInitializedNameError,
10888 result;
10889 isBindingElement = true;
10890 isAssignmentTarget = true;
10891 firstCoverInitializedNameError = null;
10892 result = parser();
10893 isBindingElement = isBindingElement && oldIsBindingElement;
10894 isAssignmentTarget = isAssignmentTarget && oldIsAssignmentTarget;
10895 firstCoverInitializedNameError = oldFirstCoverInitializedNameError || firstCoverInitializedNameError;
10896 return result;
10897 }
10898
10899 // ECMA-262 13.3.3 Destructuring Binding Patterns
10900
10901 function parseArrayPattern(params, kind) {
10902 var node = new Node(), elements = [], rest, restNode;
10903 expect('[');
10904
10905 while (!match(']')) {
10906 if (match(',')) {
10907 lex();
10908 elements.push(null);
10909 } else {
10910 if (match('...')) {
10911 restNode = new Node();
10912 lex();
10913 params.push(lookahead);
10914 rest = parseVariableIdentifier(kind);
10915 elements.push(restNode.finishRestElement(rest));
10916 break;
10917 } else {
10918 elements.push(parsePatternWithDefault(params, kind));
10919 }
10920 if (!match(']')) {
10921 expect(',');
10922 }
10923 }
10924
10925 }
10926
10927 expect(']');
10928
10929 return node.finishArrayPattern(elements);
10930 }
10931
10932 function parsePropertyPattern(params, kind) {
10933 var node = new Node(), key, keyToken, computed = match('['), init;
10934 if (lookahead.type === Token.Identifier) {
10935 keyToken = lookahead;
10936 key = parseVariableIdentifier();
10937 if (match('=')) {
10938 params.push(keyToken);
10939 lex();
10940 init = parseAssignmentExpression();
10941
10942 return node.finishProperty(
10943 'init', key, false,
10944 new WrappingNode(keyToken).finishAssignmentPattern(key, init), false, true);
10945 } else if (!match(':')) {
10946 params.push(keyToken);
10947 return node.finishProperty('init', key, false, key, false, true);
10948 }
10949 } else {
10950 key = parseObjectPropertyKey();
10951 }
10952 expect(':');
10953 init = parsePatternWithDefault(params, kind);
10954 return node.finishProperty('init', key, computed, init, false, false);
10955 }
10956
10957 function parseObjectPattern(params, kind) {
10958 var node = new Node(), properties = [];
10959
10960 expect('{');
10961
10962 while (!match('}')) {
10963 properties.push(parsePropertyPattern(params, kind));
10964 if (!match('}')) {
10965 expect(',');
10966 }
10967 }
10968
10969 lex();
10970
10971 return node.finishObjectPattern(properties);
10972 }
10973
10974 function parsePattern(params, kind) {
10975 if (match('[')) {
10976 return parseArrayPattern(params, kind);
10977 } else if (match('{')) {
10978 return parseObjectPattern(params, kind);
10979 } else if (matchKeyword('let')) {
10980 if (kind === 'const' || kind === 'let') {
10981 tolerateUnexpectedToken(lookahead, Messages.UnexpectedToken);
10982 }
10983 }
10984
10985 params.push(lookahead);
10986 return parseVariableIdentifier(kind);
10987 }
10988
10989 function parsePatternWithDefault(params, kind) {
10990 var startToken = lookahead, pattern, previousAllowYield, right;
10991 pattern = parsePattern(params, kind);
10992 if (match('=')) {
10993 lex();
10994 previousAllowYield = state.allowYield;
10995 state.allowYield = true;
10996 right = isolateCoverGrammar(parseAssignmentExpression);
10997 state.allowYield = previousAllowYield;
10998 pattern = new WrappingNode(startToken).finishAssignmentPattern(pattern, right);
10999 }
11000 return pattern;
11001 }
11002
11003 // ECMA-262 12.2.5 Array Initializer
11004
11005 function parseArrayInitializer() {
11006 var elements = [], node = new Node(), restSpread;
11007
11008 expect('[');
11009
11010 while (!match(']')) {
11011 if (match(',')) {
11012 lex();
11013 elements.push(null);
11014 } else if (match('...')) {
11015 restSpread = new Node();
11016 lex();
11017 restSpread.finishSpreadElement(inheritCoverGrammar(parseAssignmentExpression));
11018
11019 if (!match(']')) {
11020 isAssignmentTarget = isBindingElement = false;
11021 expect(',');
11022 }
11023 elements.push(restSpread);
11024 } else {
11025 elements.push(inheritCoverGrammar(parseAssignmentExpression));
11026
11027 if (!match(']')) {
11028 expect(',');
11029 }
11030 }
11031 }
11032
11033 lex();
11034
11035 return node.finishArrayExpression(elements);
11036 }
11037
11038 // ECMA-262 12.2.6 Object Initializer
11039
11040 function parsePropertyFunction(node, paramInfo, isGenerator) {
11041 var previousStrict, body;
11042
11043 isAssignmentTarget = isBindingElement = false;
11044
11045 previousStrict = strict;
11046 body = isolateCoverGrammar(parseFunctionSourceElements);
11047
11048 if (strict && paramInfo.firstRestricted) {
11049 tolerateUnexpectedToken(paramInfo.firstRestricted, paramInfo.message);
11050 }
11051 if (strict && paramInfo.stricted) {
11052 tolerateUnexpectedToken(paramInfo.stricted, paramInfo.message);
11053 }
11054
11055 strict = previousStrict;
11056 return node.finishFunctionExpression(null, paramInfo.params, paramInfo.defaults, body, isGenerator);
11057 }
11058
11059 function parsePropertyMethodFunction() {
11060 var params, method, node = new Node(),
11061 previousAllowYield = state.allowYield;
11062
11063 state.allowYield = false;
11064 params = parseParams();
11065 state.allowYield = previousAllowYield;
11066
11067 state.allowYield = false;
11068 method = parsePropertyFunction(node, params, false);
11069 state.allowYield = previousAllowYield;
11070
11071 return method;
11072 }
11073
11074 function parseObjectPropertyKey() {
11075 var token, node = new Node(), expr;
11076
11077 token = lex();
11078
11079 // Note: This function is called only from parseObjectProperty(), where
11080 // EOF and Punctuator tokens are already filtered out.
11081
11082 switch (token.type) {
11083 case Token.StringLiteral:
11084 case Token.NumericLiteral:
11085 if (strict && token.octal) {
11086 tolerateUnexpectedToken(token, Messages.StrictOctalLiteral);
11087 }
11088 return node.finishLiteral(token);
11089 case Token.Identifier:
11090 case Token.BooleanLiteral:
11091 case Token.NullLiteral:
11092 case Token.Keyword:
11093 return node.finishIdentifier(token.value);
11094 case Token.Punctuator:
11095 if (token.value === '[') {
11096 expr = isolateCoverGrammar(parseAssignmentExpression);
11097 expect(']');
11098 return expr;
11099 }
11100 break;
11101 }
11102 throwUnexpectedToken(token);
11103 }
11104
11105 function lookaheadPropertyName() {
11106 switch (lookahead.type) {
11107 case Token.Identifier:
11108 case Token.StringLiteral:
11109 case Token.BooleanLiteral:
11110 case Token.NullLiteral:
11111 case Token.NumericLiteral:
11112 case Token.Keyword:
11113 return true;
11114 case Token.Punctuator:
11115 return lookahead.value === '[';
11116 }
11117 return false;
11118 }
11119
11120 // This function is to try to parse a MethodDefinition as defined in 14.3. But in the case of object literals,
11121 // it might be called at a position where there is in fact a short hand identifier pattern or a data property.
11122 // This can only be determined after we consumed up to the left parentheses.
11123 //
11124 // In order to avoid back tracking, it returns `null` if the position is not a MethodDefinition and the caller
11125 // is responsible to visit other options.
11126 function tryParseMethodDefinition(token, key, computed, node) {
11127 var value, options, methodNode, params,
11128 previousAllowYield = state.allowYield;
11129
11130 if (token.type === Token.Identifier) {
11131 // check for `get` and `set`;
11132
11133 if (token.value === 'get' && lookaheadPropertyName()) {
11134 computed = match('[');
11135 key = parseObjectPropertyKey();
11136 methodNode = new Node();
11137 expect('(');
11138 expect(')');
11139
11140 state.allowYield = false;
11141 value = parsePropertyFunction(methodNode, {
11142 params: [],
11143 defaults: [],
11144 stricted: null,
11145 firstRestricted: null,
11146 message: null
11147 }, false);
11148 state.allowYield = previousAllowYield;
11149
11150 return node.finishProperty('get', key, computed, value, false, false);
11151 } else if (token.value === 'set' && lookaheadPropertyName()) {
11152 computed = match('[');
11153 key = parseObjectPropertyKey();
11154 methodNode = new Node();
11155 expect('(');
11156
11157 options = {
11158 params: [],
11159 defaultCount: 0,
11160 defaults: [],
11161 firstRestricted: null,
11162 paramSet: {}
11163 };
11164 if (match(')')) {
11165 tolerateUnexpectedToken(lookahead);
11166 } else {
11167 state.allowYield = false;
11168 parseParam(options);
11169 state.allowYield = previousAllowYield;
11170 if (options.defaultCount === 0) {
11171 options.defaults = [];
11172 }
11173 }
11174 expect(')');
11175
11176 state.allowYield = false;
11177 value = parsePropertyFunction(methodNode, options, false);
11178 state.allowYield = previousAllowYield;
11179
11180 return node.finishProperty('set', key, computed, value, false, false);
11181 }
11182 } else if (token.type === Token.Punctuator && token.value === '*' && lookaheadPropertyName()) {
11183 computed = match('[');
11184 key = parseObjectPropertyKey();
11185 methodNode = new Node();
11186
11187 state.allowYield = true;
11188 params = parseParams();
11189 state.allowYield = previousAllowYield;
11190
11191 state.allowYield = false;
11192 value = parsePropertyFunction(methodNode, params, true);
11193 state.allowYield = previousAllowYield;
11194
11195 return node.finishProperty('init', key, computed, value, true, false);
11196 }
11197
11198 if (key && match('(')) {
11199 value = parsePropertyMethodFunction();
11200 return node.finishProperty('init', key, computed, value, true, false);
11201 }
11202
11203 // Not a MethodDefinition.
11204 return null;
11205 }
11206
11207 function parseObjectProperty(hasProto) {
11208 var token = lookahead, node = new Node(), computed, key, maybeMethod, proto, value;
11209
11210 computed = match('[');
11211 if (match('*')) {
11212 lex();
11213 } else {
11214 key = parseObjectPropertyKey();
11215 }
11216 maybeMethod = tryParseMethodDefinition(token, key, computed, node);
11217 if (maybeMethod) {
11218 return maybeMethod;
11219 }
11220
11221 if (!key) {
11222 throwUnexpectedToken(lookahead);
11223 }
11224
11225 // Check for duplicated __proto__
11226 if (!computed) {
11227 proto = (key.type === Syntax.Identifier && key.name === '__proto__') ||
11228 (key.type === Syntax.Literal && key.value === '__proto__');
11229 if (hasProto.value && proto) {
11230 tolerateError(Messages.DuplicateProtoProperty);
11231 }
11232 hasProto.value |= proto;
11233 }
11234
11235 if (match(':')) {
11236 lex();
11237 value = inheritCoverGrammar(parseAssignmentExpression);
11238 return node.finishProperty('init', key, computed, value, false, false);
11239 }
11240
11241 if (token.type === Token.Identifier) {
11242 if (match('=')) {
11243 firstCoverInitializedNameError = lookahead;
11244 lex();
11245 value = isolateCoverGrammar(parseAssignmentExpression);
11246 return node.finishProperty('init', key, computed,
11247 new WrappingNode(token).finishAssignmentPattern(key, value), false, true);
11248 }
11249 return node.finishProperty('init', key, computed, key, false, true);
11250 }
11251
11252 throwUnexpectedToken(lookahead);
11253 }
11254
11255 function parseObjectInitializer() {
11256 var properties = [], hasProto = {value: false}, node = new Node();
11257
11258 expect('{');
11259
11260 while (!match('}')) {
11261 properties.push(parseObjectProperty(hasProto));
11262
11263 if (!match('}')) {
11264 expectCommaSeparator();
11265 }
11266 }
11267
11268 expect('}');
11269
11270 return node.finishObjectExpression(properties);
11271 }
11272
11273 function reinterpretExpressionAsPattern(expr) {
11274 var i;
11275 switch (expr.type) {
11276 case Syntax.Identifier:
11277 case Syntax.MemberExpression:
11278 case Syntax.RestElement:
11279 case Syntax.AssignmentPattern:
11280 break;
11281 case Syntax.SpreadElement:
11282 expr.type = Syntax.RestElement;
11283 reinterpretExpressionAsPattern(expr.argument);
11284 break;
11285 case Syntax.ArrayExpression:
11286 expr.type = Syntax.ArrayPattern;
11287 for (i = 0; i < expr.elements.length; i++) {
11288 if (expr.elements[i] !== null) {
11289 reinterpretExpressionAsPattern(expr.elements[i]);
11290 }
11291 }
11292 break;
11293 case Syntax.ObjectExpression:
11294 expr.type = Syntax.ObjectPattern;
11295 for (i = 0; i < expr.properties.length; i++) {
11296 reinterpretExpressionAsPattern(expr.properties[i].value);
11297 }
11298 break;
11299 case Syntax.AssignmentExpression:
11300 expr.type = Syntax.AssignmentPattern;
11301 reinterpretExpressionAsPattern(expr.left);
11302 break;
11303 default:
11304 // Allow other node type for tolerant parsing.
11305 break;
11306 }
11307 }
11308
11309 // ECMA-262 12.2.9 Template Literals
11310
11311 function parseTemplateElement(option) {
11312 var node, token;
11313
11314 if (lookahead.type !== Token.Template || (option.head && !lookahead.head)) {
11315 throwUnexpectedToken();
11316 }
11317
11318 node = new Node();
11319 token = lex();
11320
11321 return node.finishTemplateElement({ raw: token.value.raw, cooked: token.value.cooked }, token.tail);
11322 }
11323
11324 function parseTemplateLiteral() {
11325 var quasi, quasis, expressions, node = new Node();
11326
11327 quasi = parseTemplateElement({ head: true });
11328 quasis = [quasi];
11329 expressions = [];
11330
11331 while (!quasi.tail) {
11332 expressions.push(parseExpression());
11333 quasi = parseTemplateElement({ head: false });
11334 quasis.push(quasi);
11335 }
11336
11337 return node.finishTemplateLiteral(quasis, expressions);
11338 }
11339
11340 // ECMA-262 12.2.10 The Grouping Operator
11341
11342 function parseGroupExpression() {
11343 var expr, expressions, startToken, i, params = [];
11344
11345 expect('(');
11346
11347 if (match(')')) {
11348 lex();
11349 if (!match('=>')) {
11350 expect('=>');
11351 }
11352 return {
11353 type: PlaceHolders.ArrowParameterPlaceHolder,
11354 params: [],
11355 rawParams: []
11356 };
11357 }
11358
11359 startToken = lookahead;
11360 if (match('...')) {
11361 expr = parseRestElement(params);
11362 expect(')');
11363 if (!match('=>')) {
11364 expect('=>');
11365 }
11366 return {
11367 type: PlaceHolders.ArrowParameterPlaceHolder,
11368 params: [expr]
11369 };
11370 }
11371
11372 isBindingElement = true;
11373 expr = inheritCoverGrammar(parseAssignmentExpression);
11374
11375 if (match(',')) {
11376 isAssignmentTarget = false;
11377 expressions = [expr];
11378
11379 while (startIndex < length) {
11380 if (!match(',')) {
11381 break;
11382 }
11383 lex();
11384
11385 if (match('...')) {
11386 if (!isBindingElement) {
11387 throwUnexpectedToken(lookahead);
11388 }
11389 expressions.push(parseRestElement(params));
11390 expect(')');
11391 if (!match('=>')) {
11392 expect('=>');
11393 }
11394 isBindingElement = false;
11395 for (i = 0; i < expressions.length; i++) {
11396 reinterpretExpressionAsPattern(expressions[i]);
11397 }
11398 return {
11399 type: PlaceHolders.ArrowParameterPlaceHolder,
11400 params: expressions
11401 };
11402 }
11403
11404 expressions.push(inheritCoverGrammar(parseAssignmentExpression));
11405 }
11406
11407 expr = new WrappingNode(startToken).finishSequenceExpression(expressions);
11408 }
11409
11410
11411 expect(')');
11412
11413 if (match('=>')) {
11414 if (expr.type === Syntax.Identifier && expr.name === 'yield') {
11415 return {
11416 type: PlaceHolders.ArrowParameterPlaceHolder,
11417 params: [expr]
11418 };
11419 }
11420
11421 if (!isBindingElement) {
11422 throwUnexpectedToken(lookahead);
11423 }
11424
11425 if (expr.type === Syntax.SequenceExpression) {
11426 for (i = 0; i < expr.expressions.length; i++) {
11427 reinterpretExpressionAsPattern(expr.expressions[i]);
11428 }
11429 } else {
11430 reinterpretExpressionAsPattern(expr);
11431 }
11432
11433 expr = {
11434 type: PlaceHolders.ArrowParameterPlaceHolder,
11435 params: expr.type === Syntax.SequenceExpression ? expr.expressions : [expr]
11436 };
11437 }
11438 isBindingElement = false;
11439 return expr;
11440 }
11441
11442
11443 // ECMA-262 12.2 Primary Expressions
11444
11445 function parsePrimaryExpression() {
11446 var type, token, expr, node;
11447
11448 if (match('(')) {
11449 isBindingElement = false;
11450 return inheritCoverGrammar(parseGroupExpression);
11451 }
11452
11453 if (match('[')) {
11454 return inheritCoverGrammar(parseArrayInitializer);
11455 }
11456
11457 if (match('{')) {
11458 return inheritCoverGrammar(parseObjectInitializer);
11459 }
11460
11461 type = lookahead.type;
11462 node = new Node();
11463
11464 if (type === Token.Identifier) {
11465 if (state.sourceType === 'module' && lookahead.value === 'await') {
11466 tolerateUnexpectedToken(lookahead);
11467 }
11468 expr = node.finishIdentifier(lex().value);
11469 } else if (type === Token.StringLiteral || type === Token.NumericLiteral) {
11470 isAssignmentTarget = isBindingElement = false;
11471 if (strict && lookahead.octal) {
11472 tolerateUnexpectedToken(lookahead, Messages.StrictOctalLiteral);
11473 }
11474 expr = node.finishLiteral(lex());
11475 } else if (type === Token.Keyword) {
11476 if (!strict && state.allowYield && matchKeyword('yield')) {
11477 return parseNonComputedProperty();
11478 }
11479 if (!strict && matchKeyword('let')) {
11480 return node.finishIdentifier(lex().value);
11481 }
11482 isAssignmentTarget = isBindingElement = false;
11483 if (matchKeyword('function')) {
11484 return parseFunctionExpression();
11485 }
11486 if (matchKeyword('this')) {
11487 lex();
11488 return node.finishThisExpression();
11489 }
11490 if (matchKeyword('class')) {
11491 return parseClassExpression();
11492 }
11493 throwUnexpectedToken(lex());
11494 } else if (type === Token.BooleanLiteral) {
11495 isAssignmentTarget = isBindingElement = false;
11496 token = lex();
11497 token.value = (token.value === 'true');
11498 expr = node.finishLiteral(token);
11499 } else if (type === Token.NullLiteral) {
11500 isAssignmentTarget = isBindingElement = false;
11501 token = lex();
11502 token.value = null;
11503 expr = node.finishLiteral(token);
11504 } else if (match('/') || match('/=')) {
11505 isAssignmentTarget = isBindingElement = false;
11506 index = startIndex;
11507
11508 if (typeof extra.tokens !== 'undefined') {
11509 token = collectRegex();
11510 } else {
11511 token = scanRegExp();
11512 }
11513 lex();
11514 expr = node.finishLiteral(token);
11515 } else if (type === Token.Template) {
11516 expr = parseTemplateLiteral();
11517 } else {
11518 throwUnexpectedToken(lex());
11519 }
11520
11521 return expr;
11522 }
11523
11524 // ECMA-262 12.3 Left-Hand-Side Expressions
11525
11526 function parseArguments() {
11527 var args = [], expr;
11528
11529 expect('(');
11530
11531 if (!match(')')) {
11532 while (startIndex < length) {
11533 if (match('...')) {
11534 expr = new Node();
11535 lex();
11536 expr.finishSpreadElement(isolateCoverGrammar(parseAssignmentExpression));
11537 } else {
11538 expr = isolateCoverGrammar(parseAssignmentExpression);
11539 }
11540 args.push(expr);
11541 if (match(')')) {
11542 break;
11543 }
11544 expectCommaSeparator();
11545 }
11546 }
11547
11548 expect(')');
11549
11550 return args;
11551 }
11552
11553 function parseNonComputedProperty() {
11554 var token, node = new Node();
11555
11556 token = lex();
11557
11558 if (!isIdentifierName(token)) {
11559 throwUnexpectedToken(token);
11560 }
11561
11562 return node.finishIdentifier(token.value);
11563 }
11564
11565 function parseNonComputedMember() {
11566 expect('.');
11567
11568 return parseNonComputedProperty();
11569 }
11570
11571 function parseComputedMember() {
11572 var expr;
11573
11574 expect('[');
11575
11576 expr = isolateCoverGrammar(parseExpression);
11577
11578 expect(']');
11579
11580 return expr;
11581 }
11582
11583 // ECMA-262 12.3.3 The new Operator
11584
11585 function parseNewExpression() {
11586 var callee, args, node = new Node();
11587
11588 expectKeyword('new');
11589
11590 if (match('.')) {
11591 lex();
11592 if (lookahead.type === Token.Identifier && lookahead.value === 'target') {
11593 if (state.inFunctionBody) {
11594 lex();
11595 return node.finishMetaProperty('new', 'target');
11596 }
11597 }
11598 throwUnexpectedToken(lookahead);
11599 }
11600
11601 callee = isolateCoverGrammar(parseLeftHandSideExpression);
11602 args = match('(') ? parseArguments() : [];
11603
11604 isAssignmentTarget = isBindingElement = false;
11605
11606 return node.finishNewExpression(callee, args);
11607 }
11608
11609 // ECMA-262 12.3.4 Function Calls
11610
11611 function parseLeftHandSideExpressionAllowCall() {
11612 var quasi, expr, args, property, startToken, previousAllowIn = state.allowIn;
11613
11614 startToken = lookahead;
11615 state.allowIn = true;
11616
11617 if (matchKeyword('super') && state.inFunctionBody) {
11618 expr = new Node();
11619 lex();
11620 expr = expr.finishSuper();
11621 if (!match('(') && !match('.') && !match('[')) {
11622 throwUnexpectedToken(lookahead);
11623 }
11624 } else {
11625 expr = inheritCoverGrammar(matchKeyword('new') ? parseNewExpression : parsePrimaryExpression);
11626 }
11627
11628 for (;;) {
11629 if (match('.')) {
11630 isBindingElement = false;
11631 isAssignmentTarget = true;
11632 property = parseNonComputedMember();
11633 expr = new WrappingNode(startToken).finishMemberExpression('.', expr, property);
11634 } else if (match('(')) {
11635 isBindingElement = false;
11636 isAssignmentTarget = false;
11637 args = parseArguments();
11638 expr = new WrappingNode(startToken).finishCallExpression(expr, args);
11639 } else if (match('[')) {
11640 isBindingElement = false;
11641 isAssignmentTarget = true;
11642 property = parseComputedMember();
11643 expr = new WrappingNode(startToken).finishMemberExpression('[', expr, property);
11644 } else if (lookahead.type === Token.Template && lookahead.head) {
11645 quasi = parseTemplateLiteral();
11646 expr = new WrappingNode(startToken).finishTaggedTemplateExpression(expr, quasi);
11647 } else {
11648 break;
11649 }
11650 }
11651 state.allowIn = previousAllowIn;
11652
11653 return expr;
11654 }
11655
11656 // ECMA-262 12.3 Left-Hand-Side Expressions
11657
11658 function parseLeftHandSideExpression() {
11659 var quasi, expr, property, startToken;
11660 assert(state.allowIn, 'callee of new expression always allow in keyword.');
11661
11662 startToken = lookahead;
11663
11664 if (matchKeyword('super') && state.inFunctionBody) {
11665 expr = new Node();
11666 lex();
11667 expr = expr.finishSuper();
11668 if (!match('[') && !match('.')) {
11669 throwUnexpectedToken(lookahead);
11670 }
11671 } else {
11672 expr = inheritCoverGrammar(matchKeyword('new') ? parseNewExpression : parsePrimaryExpression);
11673 }
11674
11675 for (;;) {
11676 if (match('[')) {
11677 isBindingElement = false;
11678 isAssignmentTarget = true;
11679 property = parseComputedMember();
11680 expr = new WrappingNode(startToken).finishMemberExpression('[', expr, property);
11681 } else if (match('.')) {
11682 isBindingElement = false;
11683 isAssignmentTarget = true;
11684 property = parseNonComputedMember();
11685 expr = new WrappingNode(startToken).finishMemberExpression('.', expr, property);
11686 } else if (lookahead.type === Token.Template && lookahead.head) {
11687 quasi = parseTemplateLiteral();
11688 expr = new WrappingNode(startToken).finishTaggedTemplateExpression(expr, quasi);
11689 } else {
11690 break;
11691 }
11692 }
11693 return expr;
11694 }
11695
11696 // ECMA-262 12.4 Postfix Expressions
11697
11698 function parsePostfixExpression() {
11699 var expr, token, startToken = lookahead;
11700
11701 expr = inheritCoverGrammar(parseLeftHandSideExpressionAllowCall);
11702
11703 if (!hasLineTerminator && lookahead.type === Token.Punctuator) {
11704 if (match('++') || match('--')) {
11705 // ECMA-262 11.3.1, 11.3.2
11706 if (strict && expr.type === Syntax.Identifier && isRestrictedWord(expr.name)) {
11707 tolerateError(Messages.StrictLHSPostfix);
11708 }
11709
11710 if (!isAssignmentTarget) {
11711 tolerateError(Messages.InvalidLHSInAssignment);
11712 }
11713
11714 isAssignmentTarget = isBindingElement = false;
11715
11716 token = lex();
11717 expr = new WrappingNode(startToken).finishPostfixExpression(token.value, expr);
11718 }
11719 }
11720
11721 return expr;
11722 }
11723
11724 // ECMA-262 12.5 Unary Operators
11725
11726 function parseUnaryExpression() {
11727 var token, expr, startToken;
11728
11729 if (lookahead.type !== Token.Punctuator && lookahead.type !== Token.Keyword) {
11730 expr = parsePostfixExpression();
11731 } else if (match('++') || match('--')) {
11732 startToken = lookahead;
11733 token = lex();
11734 expr = inheritCoverGrammar(parseUnaryExpression);
11735 // ECMA-262 11.4.4, 11.4.5
11736 if (strict && expr.type === Syntax.Identifier && isRestrictedWord(expr.name)) {
11737 tolerateError(Messages.StrictLHSPrefix);
11738 }
11739
11740 if (!isAssignmentTarget) {
11741 tolerateError(Messages.InvalidLHSInAssignment);
11742 }
11743 expr = new WrappingNode(startToken).finishUnaryExpression(token.value, expr);
11744 isAssignmentTarget = isBindingElement = false;
11745 } else if (match('+') || match('-') || match('~') || match('!')) {
11746 startToken = lookahead;
11747 token = lex();
11748 expr = inheritCoverGrammar(parseUnaryExpression);
11749 expr = new WrappingNode(startToken).finishUnaryExpression(token.value, expr);
11750 isAssignmentTarget = isBindingElement = false;
11751 } else if (matchKeyword('delete') || matchKeyword('void') || matchKeyword('typeof')) {
11752 startToken = lookahead;
11753 token = lex();
11754 expr = inheritCoverGrammar(parseUnaryExpression);
11755 expr = new WrappingNode(startToken).finishUnaryExpression(token.value, expr);
11756 if (strict && expr.operator === 'delete' && expr.argument.type === Syntax.Identifier) {
11757 tolerateError(Messages.StrictDelete);
11758 }
11759 isAssignmentTarget = isBindingElement = false;
11760 } else {
11761 expr = parsePostfixExpression();
11762 }
11763
11764 return expr;
11765 }
11766
11767 function binaryPrecedence(token, allowIn) {
11768 var prec = 0;
11769
11770 if (token.type !== Token.Punctuator && token.type !== Token.Keyword) {
11771 return 0;
11772 }
11773
11774 switch (token.value) {
11775 case '||':
11776 prec = 1;
11777 break;
11778
11779 case '&&':
11780 prec = 2;
11781 break;
11782
11783 case '|':
11784 prec = 3;
11785 break;
11786
11787 case '^':
11788 prec = 4;
11789 break;
11790
11791 case '&':
11792 prec = 5;
11793 break;
11794
11795 case '==':
11796 case '!=':
11797 case '===':
11798 case '!==':
11799 prec = 6;
11800 break;
11801
11802 case '<':
11803 case '>':
11804 case '<=':
11805 case '>=':
11806 case 'instanceof':
11807 prec = 7;
11808 break;
11809
11810 case 'in':
11811 prec = allowIn ? 7 : 0;
11812 break;
11813
11814 case '<<':
11815 case '>>':
11816 case '>>>':
11817 prec = 8;
11818 break;
11819
11820 case '+':
11821 case '-':
11822 prec = 9;
11823 break;
11824
11825 case '*':
11826 case '/':
11827 case '%':
11828 prec = 11;
11829 break;
11830
11831 default:
11832 break;
11833 }
11834
11835 return prec;
11836 }
11837
11838 // ECMA-262 12.6 Multiplicative Operators
11839 // ECMA-262 12.7 Additive Operators
11840 // ECMA-262 12.8 Bitwise Shift Operators
11841 // ECMA-262 12.9 Relational Operators
11842 // ECMA-262 12.10 Equality Operators
11843 // ECMA-262 12.11 Binary Bitwise Operators
11844 // ECMA-262 12.12 Binary Logical Operators
11845
11846 function parseBinaryExpression() {
11847 var marker, markers, expr, token, prec, stack, right, operator, left, i;
11848
11849 marker = lookahead;
11850 left = inheritCoverGrammar(parseUnaryExpression);
11851
11852 token = lookahead;
11853 prec = binaryPrecedence(token, state.allowIn);
11854 if (prec === 0) {
11855 return left;
11856 }
11857 isAssignmentTarget = isBindingElement = false;
11858 token.prec = prec;
11859 lex();
11860
11861 markers = [marker, lookahead];
11862 right = isolateCoverGrammar(parseUnaryExpression);
11863
11864 stack = [left, token, right];
11865
11866 while ((prec = binaryPrecedence(lookahead, state.allowIn)) > 0) {
11867
11868 // Reduce: make a binary expression from the three topmost entries.
11869 while ((stack.length > 2) && (prec <= stack[stack.length - 2].prec)) {
11870 right = stack.pop();
11871 operator = stack.pop().value;
11872 left = stack.pop();
11873 markers.pop();
11874 expr = new WrappingNode(markers[markers.length - 1]).finishBinaryExpression(operator, left, right);
11875 stack.push(expr);
11876 }
11877
11878 // Shift.
11879 token = lex();
11880 token.prec = prec;
11881 stack.push(token);
11882 markers.push(lookahead);
11883 expr = isolateCoverGrammar(parseUnaryExpression);
11884 stack.push(expr);
11885 }
11886
11887 // Final reduce to clean-up the stack.
11888 i = stack.length - 1;
11889 expr = stack[i];
11890 markers.pop();
11891 while (i > 1) {
11892 expr = new WrappingNode(markers.pop()).finishBinaryExpression(stack[i - 1].value, stack[i - 2], expr);
11893 i -= 2;
11894 }
11895
11896 return expr;
11897 }
11898
11899
11900 // ECMA-262 12.13 Conditional Operator
11901
11902 function parseConditionalExpression() {
11903 var expr, previousAllowIn, consequent, alternate, startToken;
11904
11905 startToken = lookahead;
11906
11907 expr = inheritCoverGrammar(parseBinaryExpression);
11908 if (match('?')) {
11909 lex();
11910 previousAllowIn = state.allowIn;
11911 state.allowIn = true;
11912 consequent = isolateCoverGrammar(parseAssignmentExpression);
11913 state.allowIn = previousAllowIn;
11914 expect(':');
11915 alternate = isolateCoverGrammar(parseAssignmentExpression);
11916
11917 expr = new WrappingNode(startToken).finishConditionalExpression(expr, consequent, alternate);
11918 isAssignmentTarget = isBindingElement = false;
11919 }
11920
11921 return expr;
11922 }
11923
11924 // ECMA-262 14.2 Arrow Function Definitions
11925
11926 function parseConciseBody() {
11927 if (match('{')) {
11928 return parseFunctionSourceElements();
11929 }
11930 return isolateCoverGrammar(parseAssignmentExpression);
11931 }
11932
11933 function checkPatternParam(options, param) {
11934 var i;
11935 switch (param.type) {
11936 case Syntax.Identifier:
11937 validateParam(options, param, param.name);
11938 break;
11939 case Syntax.RestElement:
11940 checkPatternParam(options, param.argument);
11941 break;
11942 case Syntax.AssignmentPattern:
11943 checkPatternParam(options, param.left);
11944 break;
11945 case Syntax.ArrayPattern:
11946 for (i = 0; i < param.elements.length; i++) {
11947 if (param.elements[i] !== null) {
11948 checkPatternParam(options, param.elements[i]);
11949 }
11950 }
11951 break;
11952 case Syntax.YieldExpression:
11953 break;
11954 default:
11955 assert(param.type === Syntax.ObjectPattern, 'Invalid type');
11956 for (i = 0; i < param.properties.length; i++) {
11957 checkPatternParam(options, param.properties[i].value);
11958 }
11959 break;
11960 }
11961 }
11962 function reinterpretAsCoverFormalsList(expr) {
11963 var i, len, param, params, defaults, defaultCount, options, token;
11964
11965 defaults = [];
11966 defaultCount = 0;
11967 params = [expr];
11968
11969 switch (expr.type) {
11970 case Syntax.Identifier:
11971 break;
11972 case PlaceHolders.ArrowParameterPlaceHolder:
11973 params = expr.params;
11974 break;
11975 default:
11976 return null;
11977 }
11978
11979 options = {
11980 paramSet: {}
11981 };
11982
11983 for (i = 0, len = params.length; i < len; i += 1) {
11984 param = params[i];
11985 switch (param.type) {
11986 case Syntax.AssignmentPattern:
11987 params[i] = param.left;
11988 if (param.right.type === Syntax.YieldExpression) {
11989 if (param.right.argument) {
11990 throwUnexpectedToken(lookahead);
11991 }
11992 param.right.type = Syntax.Identifier;
11993 param.right.name = 'yield';
11994 delete param.right.argument;
11995 delete param.right.delegate;
11996 }
11997 defaults.push(param.right);
11998 ++defaultCount;
11999 checkPatternParam(options, param.left);
12000 break;
12001 default:
12002 checkPatternParam(options, param);
12003 params[i] = param;
12004 defaults.push(null);
12005 break;
12006 }
12007 }
12008
12009 if (strict || !state.allowYield) {
12010 for (i = 0, len = params.length; i < len; i += 1) {
12011 param = params[i];
12012 if (param.type === Syntax.YieldExpression) {
12013 throwUnexpectedToken(lookahead);
12014 }
12015 }
12016 }
12017
12018 if (options.message === Messages.StrictParamDupe) {
12019 token = strict ? options.stricted : options.firstRestricted;
12020 throwUnexpectedToken(token, options.message);
12021 }
12022
12023 if (defaultCount === 0) {
12024 defaults = [];
12025 }
12026
12027 return {
12028 params: params,
12029 defaults: defaults,
12030 stricted: options.stricted,
12031 firstRestricted: options.firstRestricted,
12032 message: options.message
12033 };
12034 }
12035
12036 function parseArrowFunctionExpression(options, node) {
12037 var previousStrict, previousAllowYield, body;
12038
12039 if (hasLineTerminator) {
12040 tolerateUnexpectedToken(lookahead);
12041 }
12042 expect('=>');
12043
12044 previousStrict = strict;
12045 previousAllowYield = state.allowYield;
12046 state.allowYield = true;
12047
12048 body = parseConciseBody();
12049
12050 if (strict && options.firstRestricted) {
12051 throwUnexpectedToken(options.firstRestricted, options.message);
12052 }
12053 if (strict && options.stricted) {
12054 tolerateUnexpectedToken(options.stricted, options.message);
12055 }
12056
12057 strict = previousStrict;
12058 state.allowYield = previousAllowYield;
12059
12060 return node.finishArrowFunctionExpression(options.params, options.defaults, body, body.type !== Syntax.BlockStatement);
12061 }
12062
12063 // ECMA-262 14.4 Yield expression
12064
12065 function parseYieldExpression() {
12066 var argument, expr, delegate, previousAllowYield;
12067
12068 argument = null;
12069 expr = new Node();
12070 delegate = false;
12071
12072 expectKeyword('yield');
12073
12074 if (!hasLineTerminator) {
12075 previousAllowYield = state.allowYield;
12076 state.allowYield = false;
12077 delegate = match('*');
12078 if (delegate) {
12079 lex();
12080 argument = parseAssignmentExpression();
12081 } else {
12082 if (!match(';') && !match('}') && !match(')') && lookahead.type !== Token.EOF) {
12083 argument = parseAssignmentExpression();
12084 }
12085 }
12086 state.allowYield = previousAllowYield;
12087 }
12088
12089 return expr.finishYieldExpression(argument, delegate);
12090 }
12091
12092 // ECMA-262 12.14 Assignment Operators
12093
12094 function parseAssignmentExpression() {
12095 var token, expr, right, list, startToken;
12096
12097 startToken = lookahead;
12098 token = lookahead;
12099
12100 if (!state.allowYield && matchKeyword('yield')) {
12101 return parseYieldExpression();
12102 }
12103
12104 expr = parseConditionalExpression();
12105
12106 if (expr.type === PlaceHolders.ArrowParameterPlaceHolder || match('=>')) {
12107 isAssignmentTarget = isBindingElement = false;
12108 list = reinterpretAsCoverFormalsList(expr);
12109
12110 if (list) {
12111 firstCoverInitializedNameError = null;
12112 return parseArrowFunctionExpression(list, new WrappingNode(startToken));
12113 }
12114
12115 return expr;
12116 }
12117
12118 if (matchAssign()) {
12119 if (!isAssignmentTarget) {
12120 tolerateError(Messages.InvalidLHSInAssignment);
12121 }
12122
12123 // ECMA-262 12.1.1
12124 if (strict && expr.type === Syntax.Identifier) {
12125 if (isRestrictedWord(expr.name)) {
12126 tolerateUnexpectedToken(token, Messages.StrictLHSAssignment);
12127 }
12128 if (isStrictModeReservedWord(expr.name)) {
12129 tolerateUnexpectedToken(token, Messages.StrictReservedWord);
12130 }
12131 }
12132
12133 if (!match('=')) {
12134 isAssignmentTarget = isBindingElement = false;
12135 } else {
12136 reinterpretExpressionAsPattern(expr);
12137 }
12138
12139 token = lex();
12140 right = isolateCoverGrammar(parseAssignmentExpression);
12141 expr = new WrappingNode(startToken).finishAssignmentExpression(token.value, expr, right);
12142 firstCoverInitializedNameError = null;
12143 }
12144
12145 return expr;
12146 }
12147
12148 // ECMA-262 12.15 Comma Operator
12149
12150 function parseExpression() {
12151 var expr, startToken = lookahead, expressions;
12152
12153 expr = isolateCoverGrammar(parseAssignmentExpression);
12154
12155 if (match(',')) {
12156 expressions = [expr];
12157
12158 while (startIndex < length) {
12159 if (!match(',')) {
12160 break;
12161 }
12162 lex();
12163 expressions.push(isolateCoverGrammar(parseAssignmentExpression));
12164 }
12165
12166 expr = new WrappingNode(startToken).finishSequenceExpression(expressions);
12167 }
12168
12169 return expr;
12170 }
12171
12172 // ECMA-262 13.2 Block
12173
12174 function parseStatementListItem() {
12175 if (lookahead.type === Token.Keyword) {
12176 switch (lookahead.value) {
12177 case 'export':
12178 if (state.sourceType !== 'module') {
12179 tolerateUnexpectedToken(lookahead, Messages.IllegalExportDeclaration);
12180 }
12181 return parseExportDeclaration();
12182 case 'import':
12183 if (state.sourceType !== 'module') {
12184 tolerateUnexpectedToken(lookahead, Messages.IllegalImportDeclaration);
12185 }
12186 return parseImportDeclaration();
12187 case 'const':
12188 return parseLexicalDeclaration({inFor: false});
12189 case 'function':
12190 return parseFunctionDeclaration(new Node());
12191 case 'class':
12192 return parseClassDeclaration();
12193 }
12194 }
12195
12196 if (matchKeyword('let') && isLexicalDeclaration()) {
12197 return parseLexicalDeclaration({inFor: false});
12198 }
12199
12200 return parseStatement();
12201 }
12202
12203 function parseStatementList() {
12204 var list = [];
12205 while (startIndex < length) {
12206 if (match('}')) {
12207 break;
12208 }
12209 list.push(parseStatementListItem());
12210 }
12211
12212 return list;
12213 }
12214
12215 function parseBlock() {
12216 var block, node = new Node();
12217
12218 expect('{');
12219
12220 block = parseStatementList();
12221
12222 expect('}');
12223
12224 return node.finishBlockStatement(block);
12225 }
12226
12227 // ECMA-262 13.3.2 Variable Statement
12228
12229 function parseVariableIdentifier(kind) {
12230 var token, node = new Node();
12231
12232 token = lex();
12233
12234 if (token.type === Token.Keyword && token.value === 'yield') {
12235 if (strict) {
12236 tolerateUnexpectedToken(token, Messages.StrictReservedWord);
12237 } if (!state.allowYield) {
12238 throwUnexpectedToken(token);
12239 }
12240 } else if (token.type !== Token.Identifier) {
12241 if (strict && token.type === Token.Keyword && isStrictModeReservedWord(token.value)) {
12242 tolerateUnexpectedToken(token, Messages.StrictReservedWord);
12243 } else {
12244 if (strict || token.value !== 'let' || kind !== 'var') {
12245 throwUnexpectedToken(token);
12246 }
12247 }
12248 } else if (state.sourceType === 'module' && token.type === Token.Identifier && token.value === 'await') {
12249 tolerateUnexpectedToken(token);
12250 }
12251
12252 return node.finishIdentifier(token.value);
12253 }
12254
12255 function parseVariableDeclaration(options) {
12256 var init = null, id, node = new Node(), params = [];
12257
12258 id = parsePattern(params, 'var');
12259
12260 // ECMA-262 12.2.1
12261 if (strict && isRestrictedWord(id.name)) {
12262 tolerateError(Messages.StrictVarName);
12263 }
12264
12265 if (match('=')) {
12266 lex();
12267 init = isolateCoverGrammar(parseAssignmentExpression);
12268 } else if (id.type !== Syntax.Identifier && !options.inFor) {
12269 expect('=');
12270 }
12271
12272 return node.finishVariableDeclarator(id, init);
12273 }
12274
12275 function parseVariableDeclarationList(options) {
12276 var opt, list;
12277
12278 opt = { inFor: options.inFor };
12279 list = [parseVariableDeclaration(opt)];
12280
12281 while (match(',')) {
12282 lex();
12283 list.push(parseVariableDeclaration(opt));
12284 }
12285
12286 return list;
12287 }
12288
12289 function parseVariableStatement(node) {
12290 var declarations;
12291
12292 expectKeyword('var');
12293
12294 declarations = parseVariableDeclarationList({ inFor: false });
12295
12296 consumeSemicolon();
12297
12298 return node.finishVariableDeclaration(declarations);
12299 }
12300
12301 // ECMA-262 13.3.1 Let and Const Declarations
12302
12303 function parseLexicalBinding(kind, options) {
12304 var init = null, id, node = new Node(), params = [];
12305
12306 id = parsePattern(params, kind);
12307
12308 // ECMA-262 12.2.1
12309 if (strict && id.type === Syntax.Identifier && isRestrictedWord(id.name)) {
12310 tolerateError(Messages.StrictVarName);
12311 }
12312
12313 if (kind === 'const') {
12314 if (!matchKeyword('in') && !matchContextualKeyword('of')) {
12315 expect('=');
12316 init = isolateCoverGrammar(parseAssignmentExpression);
12317 }
12318 } else if ((!options.inFor && id.type !== Syntax.Identifier) || match('=')) {
12319 expect('=');
12320 init = isolateCoverGrammar(parseAssignmentExpression);
12321 }
12322
12323 return node.finishVariableDeclarator(id, init);
12324 }
12325
12326 function parseBindingList(kind, options) {
12327 var list = [parseLexicalBinding(kind, options)];
12328
12329 while (match(',')) {
12330 lex();
12331 list.push(parseLexicalBinding(kind, options));
12332 }
12333
12334 return list;
12335 }
12336
12337
12338 function tokenizerState() {
12339 return {
12340 index: index,
12341 lineNumber: lineNumber,
12342 lineStart: lineStart,
12343 hasLineTerminator: hasLineTerminator,
12344 lastIndex: lastIndex,
12345 lastLineNumber: lastLineNumber,
12346 lastLineStart: lastLineStart,
12347 startIndex: startIndex,
12348 startLineNumber: startLineNumber,
12349 startLineStart: startLineStart,
12350 lookahead: lookahead,
12351 tokenCount: extra.tokens ? extra.tokens.length : 0
12352 };
12353 }
12354
12355 function resetTokenizerState(ts) {
12356 index = ts.index;
12357 lineNumber = ts.lineNumber;
12358 lineStart = ts.lineStart;
12359 hasLineTerminator = ts.hasLineTerminator;
12360 lastIndex = ts.lastIndex;
12361 lastLineNumber = ts.lastLineNumber;
12362 lastLineStart = ts.lastLineStart;
12363 startIndex = ts.startIndex;
12364 startLineNumber = ts.startLineNumber;
12365 startLineStart = ts.startLineStart;
12366 lookahead = ts.lookahead;
12367 if (extra.tokens) {
12368 extra.tokens.splice(ts.tokenCount, extra.tokens.length);
12369 }
12370 }
12371
12372 function isLexicalDeclaration() {
12373 var lexical, ts;
12374
12375 ts = tokenizerState();
12376
12377 lex();
12378 lexical = (lookahead.type === Token.Identifier) || match('[') || match('{') ||
12379 matchKeyword('let') || matchKeyword('yield');
12380
12381 resetTokenizerState(ts);
12382
12383 return lexical;
12384 }
12385
12386 function parseLexicalDeclaration(options) {
12387 var kind, declarations, node = new Node();
12388
12389 kind = lex().value;
12390 assert(kind === 'let' || kind === 'const', 'Lexical declaration must be either let or const');
12391
12392 declarations = parseBindingList(kind, options);
12393
12394 consumeSemicolon();
12395
12396 return node.finishLexicalDeclaration(declarations, kind);
12397 }
12398
12399 function parseRestElement(params) {
12400 var param, node = new Node();
12401
12402 lex();
12403
12404 if (match('{')) {
12405 throwError(Messages.ObjectPatternAsRestParameter);
12406 }
12407
12408 params.push(lookahead);
12409
12410 param = parseVariableIdentifier();
12411
12412 if (match('=')) {
12413 throwError(Messages.DefaultRestParameter);
12414 }
12415
12416 if (!match(')')) {
12417 throwError(Messages.ParameterAfterRestParameter);
12418 }
12419
12420 return node.finishRestElement(param);
12421 }
12422
12423 // ECMA-262 13.4 Empty Statement
12424
12425 function parseEmptyStatement(node) {
12426 expect(';');
12427 return node.finishEmptyStatement();
12428 }
12429
12430 // ECMA-262 12.4 Expression Statement
12431
12432 function parseExpressionStatement(node) {
12433 var expr = parseExpression();
12434 consumeSemicolon();
12435 return node.finishExpressionStatement(expr);
12436 }
12437
12438 // ECMA-262 13.6 If statement
12439
12440 function parseIfStatement(node) {
12441 var test, consequent, alternate;
12442
12443 expectKeyword('if');
12444
12445 expect('(');
12446
12447 test = parseExpression();
12448
12449 expect(')');
12450
12451 consequent = parseStatement();
12452
12453 if (matchKeyword('else')) {
12454 lex();
12455 alternate = parseStatement();
12456 } else {
12457 alternate = null;
12458 }
12459
12460 return node.finishIfStatement(test, consequent, alternate);
12461 }
12462
12463 // ECMA-262 13.7 Iteration Statements
12464
12465 function parseDoWhileStatement(node) {
12466 var body, test, oldInIteration;
12467
12468 expectKeyword('do');
12469
12470 oldInIteration = state.inIteration;
12471 state.inIteration = true;
12472
12473 body = parseStatement();
12474
12475 state.inIteration = oldInIteration;
12476
12477 expectKeyword('while');
12478
12479 expect('(');
12480
12481 test = parseExpression();
12482
12483 expect(')');
12484
12485 if (match(';')) {
12486 lex();
12487 }
12488
12489 return node.finishDoWhileStatement(body, test);
12490 }
12491
12492 function parseWhileStatement(node) {
12493 var test, body, oldInIteration;
12494
12495 expectKeyword('while');
12496
12497 expect('(');
12498
12499 test = parseExpression();
12500
12501 expect(')');
12502
12503 oldInIteration = state.inIteration;
12504 state.inIteration = true;
12505
12506 body = parseStatement();
12507
12508 state.inIteration = oldInIteration;
12509
12510 return node.finishWhileStatement(test, body);
12511 }
12512
12513 function parseForStatement(node) {
12514 var init, forIn, initSeq, initStartToken, test, update, left, right, kind, declarations,
12515 body, oldInIteration, previousAllowIn = state.allowIn;
12516
12517 init = test = update = null;
12518 forIn = true;
12519
12520 expectKeyword('for');
12521
12522 expect('(');
12523
12524 if (match(';')) {
12525 lex();
12526 } else {
12527 if (matchKeyword('var')) {
12528 init = new Node();
12529 lex();
12530
12531 state.allowIn = false;
12532 declarations = parseVariableDeclarationList({ inFor: true });
12533 state.allowIn = previousAllowIn;
12534
12535 if (declarations.length === 1 && matchKeyword('in')) {
12536 init = init.finishVariableDeclaration(declarations);
12537 lex();
12538 left = init;
12539 right = parseExpression();
12540 init = null;
12541 } else if (declarations.length === 1 && declarations[0].init === null && matchContextualKeyword('of')) {
12542 init = init.finishVariableDeclaration(declarations);
12543 lex();
12544 left = init;
12545 right = parseAssignmentExpression();
12546 init = null;
12547 forIn = false;
12548 } else {
12549 init = init.finishVariableDeclaration(declarations);
12550 expect(';');
12551 }
12552 } else if (matchKeyword('const') || matchKeyword('let')) {
12553 init = new Node();
12554 kind = lex().value;
12555
12556 if (!strict && lookahead.value === 'in') {
12557 init = init.finishIdentifier(kind);
12558 lex();
12559 left = init;
12560 right = parseExpression();
12561 init = null;
12562 } else {
12563 state.allowIn = false;
12564 declarations = parseBindingList(kind, {inFor: true});
12565 state.allowIn = previousAllowIn;
12566
12567 if (declarations.length === 1 && declarations[0].init === null && matchKeyword('in')) {
12568 init = init.finishLexicalDeclaration(declarations, kind);
12569 lex();
12570 left = init;
12571 right = parseExpression();
12572 init = null;
12573 } else if (declarations.length === 1 && declarations[0].init === null && matchContextualKeyword('of')) {
12574 init = init.finishLexicalDeclaration(declarations, kind);
12575 lex();
12576 left = init;
12577 right = parseAssignmentExpression();
12578 init = null;
12579 forIn = false;
12580 } else {
12581 consumeSemicolon();
12582 init = init.finishLexicalDeclaration(declarations, kind);
12583 }
12584 }
12585 } else {
12586 initStartToken = lookahead;
12587 state.allowIn = false;
12588 init = inheritCoverGrammar(parseAssignmentExpression);
12589 state.allowIn = previousAllowIn;
12590
12591 if (matchKeyword('in')) {
12592 if (!isAssignmentTarget) {
12593 tolerateError(Messages.InvalidLHSInForIn);
12594 }
12595
12596 lex();
12597 reinterpretExpressionAsPattern(init);
12598 left = init;
12599 right = parseExpression();
12600 init = null;
12601 } else if (matchContextualKeyword('of')) {
12602 if (!isAssignmentTarget) {
12603 tolerateError(Messages.InvalidLHSInForLoop);
12604 }
12605
12606 lex();
12607 reinterpretExpressionAsPattern(init);
12608 left = init;
12609 right = parseAssignmentExpression();
12610 init = null;
12611 forIn = false;
12612 } else {
12613 if (match(',')) {
12614 initSeq = [init];
12615 while (match(',')) {
12616 lex();
12617 initSeq.push(isolateCoverGrammar(parseAssignmentExpression));
12618 }
12619 init = new WrappingNode(initStartToken).finishSequenceExpression(initSeq);
12620 }
12621 expect(';');
12622 }
12623 }
12624 }
12625
12626 if (typeof left === 'undefined') {
12627
12628 if (!match(';')) {
12629 test = parseExpression();
12630 }
12631 expect(';');
12632
12633 if (!match(')')) {
12634 update = parseExpression();
12635 }
12636 }
12637
12638 expect(')');
12639
12640 oldInIteration = state.inIteration;
12641 state.inIteration = true;
12642
12643 body = isolateCoverGrammar(parseStatement);
12644
12645 state.inIteration = oldInIteration;
12646
12647 return (typeof left === 'undefined') ?
12648 node.finishForStatement(init, test, update, body) :
12649 forIn ? node.finishForInStatement(left, right, body) :
12650 node.finishForOfStatement(left, right, body);
12651 }
12652
12653 // ECMA-262 13.8 The continue statement
12654
12655 function parseContinueStatement(node) {
12656 var label = null, key;
12657
12658 expectKeyword('continue');
12659
12660 // Optimize the most common form: 'continue;'.
12661 if (source.charCodeAt(startIndex) === 0x3B) {
12662 lex();
12663
12664 if (!state.inIteration) {
12665 throwError(Messages.IllegalContinue);
12666 }
12667
12668 return node.finishContinueStatement(null);
12669 }
12670
12671 if (hasLineTerminator) {
12672 if (!state.inIteration) {
12673 throwError(Messages.IllegalContinue);
12674 }
12675
12676 return node.finishContinueStatement(null);
12677 }
12678
12679 if (lookahead.type === Token.Identifier) {
12680 label = parseVariableIdentifier();
12681
12682 key = '$' + label.name;
12683 if (!Object.prototype.hasOwnProperty.call(state.labelSet, key)) {
12684 throwError(Messages.UnknownLabel, label.name);
12685 }
12686 }
12687
12688 consumeSemicolon();
12689
12690 if (label === null && !state.inIteration) {
12691 throwError(Messages.IllegalContinue);
12692 }
12693
12694 return node.finishContinueStatement(label);
12695 }
12696
12697 // ECMA-262 13.9 The break statement
12698
12699 function parseBreakStatement(node) {
12700 var label = null, key;
12701
12702 expectKeyword('break');
12703
12704 // Catch the very common case first: immediately a semicolon (U+003B).
12705 if (source.charCodeAt(lastIndex) === 0x3B) {
12706 lex();
12707
12708 if (!(state.inIteration || state.inSwitch)) {
12709 throwError(Messages.IllegalBreak);
12710 }
12711
12712 return node.finishBreakStatement(null);
12713 }
12714
12715 if (hasLineTerminator) {
12716 if (!(state.inIteration || state.inSwitch)) {
12717 throwError(Messages.IllegalBreak);
12718 }
12719 } else if (lookahead.type === Token.Identifier) {
12720 label = parseVariableIdentifier();
12721
12722 key = '$' + label.name;
12723 if (!Object.prototype.hasOwnProperty.call(state.labelSet, key)) {
12724 throwError(Messages.UnknownLabel, label.name);
12725 }
12726 }
12727
12728 consumeSemicolon();
12729
12730 if (label === null && !(state.inIteration || state.inSwitch)) {
12731 throwError(Messages.IllegalBreak);
12732 }
12733
12734 return node.finishBreakStatement(label);
12735 }
12736
12737 // ECMA-262 13.10 The return statement
12738
12739 function parseReturnStatement(node) {
12740 var argument = null;
12741
12742 expectKeyword('return');
12743
12744 if (!state.inFunctionBody) {
12745 tolerateError(Messages.IllegalReturn);
12746 }
12747
12748 // 'return' followed by a space and an identifier is very common.
12749 if (source.charCodeAt(lastIndex) === 0x20) {
12750 if (isIdentifierStart(source.charCodeAt(lastIndex + 1))) {
12751 argument = parseExpression();
12752 consumeSemicolon();
12753 return node.finishReturnStatement(argument);
12754 }
12755 }
12756
12757 if (hasLineTerminator) {
12758 // HACK
12759 return node.finishReturnStatement(null);
12760 }
12761
12762 if (!match(';')) {
12763 if (!match('}') && lookahead.type !== Token.EOF) {
12764 argument = parseExpression();
12765 }
12766 }
12767
12768 consumeSemicolon();
12769
12770 return node.finishReturnStatement(argument);
12771 }
12772
12773 // ECMA-262 13.11 The with statement
12774
12775 function parseWithStatement(node) {
12776 var object, body;
12777
12778 if (strict) {
12779 tolerateError(Messages.StrictModeWith);
12780 }
12781
12782 expectKeyword('with');
12783
12784 expect('(');
12785
12786 object = parseExpression();
12787
12788 expect(')');
12789
12790 body = parseStatement();
12791
12792 return node.finishWithStatement(object, body);
12793 }
12794
12795 // ECMA-262 13.12 The switch statement
12796
12797 function parseSwitchCase() {
12798 var test, consequent = [], statement, node = new Node();
12799
12800 if (matchKeyword('default')) {
12801 lex();
12802 test = null;
12803 } else {
12804 expectKeyword('case');
12805 test = parseExpression();
12806 }
12807 expect(':');
12808
12809 while (startIndex < length) {
12810 if (match('}') || matchKeyword('default') || matchKeyword('case')) {
12811 break;
12812 }
12813 statement = parseStatementListItem();
12814 consequent.push(statement);
12815 }
12816
12817 return node.finishSwitchCase(test, consequent);
12818 }
12819
12820 function parseSwitchStatement(node) {
12821 var discriminant, cases, clause, oldInSwitch, defaultFound;
12822
12823 expectKeyword('switch');
12824
12825 expect('(');
12826
12827 discriminant = parseExpression();
12828
12829 expect(')');
12830
12831 expect('{');
12832
12833 cases = [];
12834
12835 if (match('}')) {
12836 lex();
12837 return node.finishSwitchStatement(discriminant, cases);
12838 }
12839
12840 oldInSwitch = state.inSwitch;
12841 state.inSwitch = true;
12842 defaultFound = false;
12843
12844 while (startIndex < length) {
12845 if (match('}')) {
12846 break;
12847 }
12848 clause = parseSwitchCase();
12849 if (clause.test === null) {
12850 if (defaultFound) {
12851 throwError(Messages.MultipleDefaultsInSwitch);
12852 }
12853 defaultFound = true;
12854 }
12855 cases.push(clause);
12856 }
12857
12858 state.inSwitch = oldInSwitch;
12859
12860 expect('}');
12861
12862 return node.finishSwitchStatement(discriminant, cases);
12863 }
12864
12865 // ECMA-262 13.14 The throw statement
12866
12867 function parseThrowStatement(node) {
12868 var argument;
12869
12870 expectKeyword('throw');
12871
12872 if (hasLineTerminator) {
12873 throwError(Messages.NewlineAfterThrow);
12874 }
12875
12876 argument = parseExpression();
12877
12878 consumeSemicolon();
12879
12880 return node.finishThrowStatement(argument);
12881 }
12882
12883 // ECMA-262 13.15 The try statement
12884
12885 function parseCatchClause() {
12886 var param, params = [], paramMap = {}, key, i, body, node = new Node();
12887
12888 expectKeyword('catch');
12889
12890 expect('(');
12891 if (match(')')) {
12892 throwUnexpectedToken(lookahead);
12893 }
12894
12895 param = parsePattern(params);
12896 for (i = 0; i < params.length; i++) {
12897 key = '$' + params[i].value;
12898 if (Object.prototype.hasOwnProperty.call(paramMap, key)) {
12899 tolerateError(Messages.DuplicateBinding, params[i].value);
12900 }
12901 paramMap[key] = true;
12902 }
12903
12904 // ECMA-262 12.14.1
12905 if (strict && isRestrictedWord(param.name)) {
12906 tolerateError(Messages.StrictCatchVariable);
12907 }
12908
12909 expect(')');
12910 body = parseBlock();
12911 return node.finishCatchClause(param, body);
12912 }
12913
12914 function parseTryStatement(node) {
12915 var block, handler = null, finalizer = null;
12916
12917 expectKeyword('try');
12918
12919 block = parseBlock();
12920
12921 if (matchKeyword('catch')) {
12922 handler = parseCatchClause();
12923 }
12924
12925 if (matchKeyword('finally')) {
12926 lex();
12927 finalizer = parseBlock();
12928 }
12929
12930 if (!handler && !finalizer) {
12931 throwError(Messages.NoCatchOrFinally);
12932 }
12933
12934 return node.finishTryStatement(block, handler, finalizer);
12935 }
12936
12937 // ECMA-262 13.16 The debugger statement
12938
12939 function parseDebuggerStatement(node) {
12940 expectKeyword('debugger');
12941
12942 consumeSemicolon();
12943
12944 return node.finishDebuggerStatement();
12945 }
12946
12947 // 13 Statements
12948
12949 function parseStatement() {
12950 var type = lookahead.type,
12951 expr,
12952 labeledBody,
12953 key,
12954 node;
12955
12956 if (type === Token.EOF) {
12957 throwUnexpectedToken(lookahead);
12958 }
12959
12960 if (type === Token.Punctuator && lookahead.value === '{') {
12961 return parseBlock();
12962 }
12963 isAssignmentTarget = isBindingElement = true;
12964 node = new Node();
12965
12966 if (type === Token.Punctuator) {
12967 switch (lookahead.value) {
12968 case ';':
12969 return parseEmptyStatement(node);
12970 case '(':
12971 return parseExpressionStatement(node);
12972 default:
12973 break;
12974 }
12975 } else if (type === Token.Keyword) {
12976 switch (lookahead.value) {
12977 case 'break':
12978 return parseBreakStatement(node);
12979 case 'continue':
12980 return parseContinueStatement(node);
12981 case 'debugger':
12982 return parseDebuggerStatement(node);
12983 case 'do':
12984 return parseDoWhileStatement(node);
12985 case 'for':
12986 return parseForStatement(node);
12987 case 'function':
12988 return parseFunctionDeclaration(node);
12989 case 'if':
12990 return parseIfStatement(node);
12991 case 'return':
12992 return parseReturnStatement(node);
12993 case 'switch':
12994 return parseSwitchStatement(node);
12995 case 'throw':
12996 return parseThrowStatement(node);
12997 case 'try':
12998 return parseTryStatement(node);
12999 case 'var':
13000 return parseVariableStatement(node);
13001 case 'while':
13002 return parseWhileStatement(node);
13003 case 'with':
13004 return parseWithStatement(node);
13005 default:
13006 break;
13007 }
13008 }
13009
13010 expr = parseExpression();
13011
13012 // ECMA-262 12.12 Labelled Statements
13013 if ((expr.type === Syntax.Identifier) && match(':')) {
13014 lex();
13015
13016 key = '$' + expr.name;
13017 if (Object.prototype.hasOwnProperty.call(state.labelSet, key)) {
13018 throwError(Messages.Redeclaration, 'Label', expr.name);
13019 }
13020
13021 state.labelSet[key] = true;
13022 labeledBody = parseStatement();
13023 delete state.labelSet[key];
13024 return node.finishLabeledStatement(expr, labeledBody);
13025 }
13026
13027 consumeSemicolon();
13028
13029 return node.finishExpressionStatement(expr);
13030 }
13031
13032 // ECMA-262 14.1 Function Definition
13033
13034 function parseFunctionSourceElements() {
13035 var statement, body = [], token, directive, firstRestricted,
13036 oldLabelSet, oldInIteration, oldInSwitch, oldInFunctionBody,
13037 node = new Node();
13038
13039 expect('{');
13040
13041 while (startIndex < length) {
13042 if (lookahead.type !== Token.StringLiteral) {
13043 break;
13044 }
13045 token = lookahead;
13046
13047 statement = parseStatementListItem();
13048 body.push(statement);
13049 if (statement.expression.type !== Syntax.Literal) {
13050 // this is not directive
13051 break;
13052 }
13053 directive = source.slice(token.start + 1, token.end - 1);
13054 if (directive === 'use strict') {
13055 strict = true;
13056 if (firstRestricted) {
13057 tolerateUnexpectedToken(firstRestricted, Messages.StrictOctalLiteral);
13058 }
13059 } else {
13060 if (!firstRestricted && token.octal) {
13061 firstRestricted = token;
13062 }
13063 }
13064 }
13065
13066 oldLabelSet = state.labelSet;
13067 oldInIteration = state.inIteration;
13068 oldInSwitch = state.inSwitch;
13069 oldInFunctionBody = state.inFunctionBody;
13070
13071 state.labelSet = {};
13072 state.inIteration = false;
13073 state.inSwitch = false;
13074 state.inFunctionBody = true;
13075
13076 while (startIndex < length) {
13077 if (match('}')) {
13078 break;
13079 }
13080 body.push(parseStatementListItem());
13081 }
13082
13083 expect('}');
13084
13085 state.labelSet = oldLabelSet;
13086 state.inIteration = oldInIteration;
13087 state.inSwitch = oldInSwitch;
13088 state.inFunctionBody = oldInFunctionBody;
13089
13090 return node.finishBlockStatement(body);
13091 }
13092
13093 function validateParam(options, param, name) {
13094 var key = '$' + name;
13095 if (strict) {
13096 if (isRestrictedWord(name)) {
13097 options.stricted = param;
13098 options.message = Messages.StrictParamName;
13099 }
13100 if (Object.prototype.hasOwnProperty.call(options.paramSet, key)) {
13101 options.stricted = param;
13102 options.message = Messages.StrictParamDupe;
13103 }
13104 } else if (!options.firstRestricted) {
13105 if (isRestrictedWord(name)) {
13106 options.firstRestricted = param;
13107 options.message = Messages.StrictParamName;
13108 } else if (isStrictModeReservedWord(name)) {
13109 options.firstRestricted = param;
13110 options.message = Messages.StrictReservedWord;
13111 } else if (Object.prototype.hasOwnProperty.call(options.paramSet, key)) {
13112 options.stricted = param;
13113 options.message = Messages.StrictParamDupe;
13114 }
13115 }
13116 options.paramSet[key] = true;
13117 }
13118
13119 function parseParam(options) {
13120 var token, param, params = [], i, def;
13121
13122 token = lookahead;
13123 if (token.value === '...') {
13124 param = parseRestElement(params);
13125 validateParam(options, param.argument, param.argument.name);
13126 options.params.push(param);
13127 options.defaults.push(null);
13128 return false;
13129 }
13130
13131 param = parsePatternWithDefault(params);
13132 for (i = 0; i < params.length; i++) {
13133 validateParam(options, params[i], params[i].value);
13134 }
13135
13136 if (param.type === Syntax.AssignmentPattern) {
13137 def = param.right;
13138 param = param.left;
13139 ++options.defaultCount;
13140 }
13141
13142 options.params.push(param);
13143 options.defaults.push(def);
13144
13145 return !match(')');
13146 }
13147
13148 function parseParams(firstRestricted) {
13149 var options;
13150
13151 options = {
13152 params: [],
13153 defaultCount: 0,
13154 defaults: [],
13155 firstRestricted: firstRestricted
13156 };
13157
13158 expect('(');
13159
13160 if (!match(')')) {
13161 options.paramSet = {};
13162 while (startIndex < length) {
13163 if (!parseParam(options)) {
13164 break;
13165 }
13166 expect(',');
13167 }
13168 }
13169
13170 expect(')');
13171
13172 if (options.defaultCount === 0) {
13173 options.defaults = [];
13174 }
13175
13176 return {
13177 params: options.params,
13178 defaults: options.defaults,
13179 stricted: options.stricted,
13180 firstRestricted: options.firstRestricted,
13181 message: options.message
13182 };
13183 }
13184
13185 function parseFunctionDeclaration(node, identifierIsOptional) {
13186 var id = null, params = [], defaults = [], body, token, stricted, tmp, firstRestricted, message, previousStrict,
13187 isGenerator, previousAllowYield;
13188
13189 previousAllowYield = state.allowYield;
13190
13191 expectKeyword('function');
13192
13193 isGenerator = match('*');
13194 if (isGenerator) {
13195 lex();
13196 }
13197
13198 if (!identifierIsOptional || !match('(')) {
13199 token = lookahead;
13200 id = parseVariableIdentifier();
13201 if (strict) {
13202 if (isRestrictedWord(token.value)) {
13203 tolerateUnexpectedToken(token, Messages.StrictFunctionName);
13204 }
13205 } else {
13206 if (isRestrictedWord(token.value)) {
13207 firstRestricted = token;
13208 message = Messages.StrictFunctionName;
13209 } else if (isStrictModeReservedWord(token.value)) {
13210 firstRestricted = token;
13211 message = Messages.StrictReservedWord;
13212 }
13213 }
13214 }
13215
13216 state.allowYield = !isGenerator;
13217 tmp = parseParams(firstRestricted);
13218 params = tmp.params;
13219 defaults = tmp.defaults;
13220 stricted = tmp.stricted;
13221 firstRestricted = tmp.firstRestricted;
13222 if (tmp.message) {
13223 message = tmp.message;
13224 }
13225
13226
13227 previousStrict = strict;
13228 body = parseFunctionSourceElements();
13229 if (strict && firstRestricted) {
13230 throwUnexpectedToken(firstRestricted, message);
13231 }
13232 if (strict && stricted) {
13233 tolerateUnexpectedToken(stricted, message);
13234 }
13235
13236 strict = previousStrict;
13237 state.allowYield = previousAllowYield;
13238
13239 return node.finishFunctionDeclaration(id, params, defaults, body, isGenerator);
13240 }
13241
13242 function parseFunctionExpression() {
13243 var token, id = null, stricted, firstRestricted, message, tmp,
13244 params = [], defaults = [], body, previousStrict, node = new Node(),
13245 isGenerator, previousAllowYield;
13246
13247 previousAllowYield = state.allowYield;
13248
13249 expectKeyword('function');
13250
13251 isGenerator = match('*');
13252 if (isGenerator) {
13253 lex();
13254 }
13255
13256 state.allowYield = !isGenerator;
13257 if (!match('(')) {
13258 token = lookahead;
13259 id = (!strict && !isGenerator && matchKeyword('yield')) ? parseNonComputedProperty() : parseVariableIdentifier();
13260 if (strict) {
13261 if (isRestrictedWord(token.value)) {
13262 tolerateUnexpectedToken(token, Messages.StrictFunctionName);
13263 }
13264 } else {
13265 if (isRestrictedWord(token.value)) {
13266 firstRestricted = token;
13267 message = Messages.StrictFunctionName;
13268 } else if (isStrictModeReservedWord(token.value)) {
13269 firstRestricted = token;
13270 message = Messages.StrictReservedWord;
13271 }
13272 }
13273 }
13274
13275 tmp = parseParams(firstRestricted);
13276 params = tmp.params;
13277 defaults = tmp.defaults;
13278 stricted = tmp.stricted;
13279 firstRestricted = tmp.firstRestricted;
13280 if (tmp.message) {
13281 message = tmp.message;
13282 }
13283
13284 previousStrict = strict;
13285 body = parseFunctionSourceElements();
13286 if (strict && firstRestricted) {
13287 throwUnexpectedToken(firstRestricted, message);
13288 }
13289 if (strict && stricted) {
13290 tolerateUnexpectedToken(stricted, message);
13291 }
13292 strict = previousStrict;
13293 state.allowYield = previousAllowYield;
13294
13295 return node.finishFunctionExpression(id, params, defaults, body, isGenerator);
13296 }
13297
13298 // ECMA-262 14.5 Class Definitions
13299
13300 function parseClassBody() {
13301 var classBody, token, isStatic, hasConstructor = false, body, method, computed, key;
13302
13303 classBody = new Node();
13304
13305 expect('{');
13306 body = [];
13307 while (!match('}')) {
13308 if (match(';')) {
13309 lex();
13310 } else {
13311 method = new Node();
13312 token = lookahead;
13313 isStatic = false;
13314 computed = match('[');
13315 if (match('*')) {
13316 lex();
13317 } else {
13318 key = parseObjectPropertyKey();
13319 if (key.name === 'static' && (lookaheadPropertyName() || match('*'))) {
13320 token = lookahead;
13321 isStatic = true;
13322 computed = match('[');
13323 if (match('*')) {
13324 lex();
13325 } else {
13326 key = parseObjectPropertyKey();
13327 }
13328 }
13329 }
13330 method = tryParseMethodDefinition(token, key, computed, method);
13331 if (method) {
13332 method['static'] = isStatic; // jscs:ignore requireDotNotation
13333 if (method.kind === 'init') {
13334 method.kind = 'method';
13335 }
13336 if (!isStatic) {
13337 if (!method.computed && (method.key.name || method.key.value.toString()) === 'constructor') {
13338 if (method.kind !== 'method' || !method.method || method.value.generator) {
13339 throwUnexpectedToken(token, Messages.ConstructorSpecialMethod);
13340 }
13341 if (hasConstructor) {
13342 throwUnexpectedToken(token, Messages.DuplicateConstructor);
13343 } else {
13344 hasConstructor = true;
13345 }
13346 method.kind = 'constructor';
13347 }
13348 } else {
13349 if (!method.computed && (method.key.name || method.key.value.toString()) === 'prototype') {
13350 throwUnexpectedToken(token, Messages.StaticPrototype);
13351 }
13352 }
13353 method.type = Syntax.MethodDefinition;
13354 delete method.method;
13355 delete method.shorthand;
13356 body.push(method);
13357 } else {
13358 throwUnexpectedToken(lookahead);
13359 }
13360 }
13361 }
13362 lex();
13363 return classBody.finishClassBody(body);
13364 }
13365
13366 function parseClassDeclaration(identifierIsOptional) {
13367 var id = null, superClass = null, classNode = new Node(), classBody, previousStrict = strict;
13368 strict = true;
13369
13370 expectKeyword('class');
13371
13372 if (!identifierIsOptional || lookahead.type === Token.Identifier) {
13373 id = parseVariableIdentifier();
13374 }
13375
13376 if (matchKeyword('extends')) {
13377 lex();
13378 superClass = isolateCoverGrammar(parseLeftHandSideExpressionAllowCall);
13379 }
13380 classBody = parseClassBody();
13381 strict = previousStrict;
13382
13383 return classNode.finishClassDeclaration(id, superClass, classBody);
13384 }
13385
13386 function parseClassExpression() {
13387 var id = null, superClass = null, classNode = new Node(), classBody, previousStrict = strict;
13388 strict = true;
13389
13390 expectKeyword('class');
13391
13392 if (lookahead.type === Token.Identifier) {
13393 id = parseVariableIdentifier();
13394 }
13395
13396 if (matchKeyword('extends')) {
13397 lex();
13398 superClass = isolateCoverGrammar(parseLeftHandSideExpressionAllowCall);
13399 }
13400 classBody = parseClassBody();
13401 strict = previousStrict;
13402
13403 return classNode.finishClassExpression(id, superClass, classBody);
13404 }
13405
13406 // ECMA-262 15.2 Modules
13407
13408 function parseModuleSpecifier() {
13409 var node = new Node();
13410
13411 if (lookahead.type !== Token.StringLiteral) {
13412 throwError(Messages.InvalidModuleSpecifier);
13413 }
13414 return node.finishLiteral(lex());
13415 }
13416
13417 // ECMA-262 15.2.3 Exports
13418
13419 function parseExportSpecifier() {
13420 var exported, local, node = new Node(), def;
13421 if (matchKeyword('default')) {
13422 // export {default} from 'something';
13423 def = new Node();
13424 lex();
13425 local = def.finishIdentifier('default');
13426 } else {
13427 local = parseVariableIdentifier();
13428 }
13429 if (matchContextualKeyword('as')) {
13430 lex();
13431 exported = parseNonComputedProperty();
13432 }
13433 return node.finishExportSpecifier(local, exported);
13434 }
13435
13436 function parseExportNamedDeclaration(node) {
13437 var declaration = null,
13438 isExportFromIdentifier,
13439 src = null, specifiers = [];
13440
13441 // non-default export
13442 if (lookahead.type === Token.Keyword) {
13443 // covers:
13444 // export var f = 1;
13445 switch (lookahead.value) {
13446 case 'let':
13447 case 'const':
13448 declaration = parseLexicalDeclaration({inFor: false});
13449 return node.finishExportNamedDeclaration(declaration, specifiers, null);
13450 case 'var':
13451 case 'class':
13452 case 'function':
13453 declaration = parseStatementListItem();
13454 return node.finishExportNamedDeclaration(declaration, specifiers, null);
13455 }
13456 }
13457
13458 expect('{');
13459 while (!match('}')) {
13460 isExportFromIdentifier = isExportFromIdentifier || matchKeyword('default');
13461 specifiers.push(parseExportSpecifier());
13462 if (!match('}')) {
13463 expect(',');
13464 if (match('}')) {
13465 break;
13466 }
13467 }
13468 }
13469 expect('}');
13470
13471 if (matchContextualKeyword('from')) {
13472 // covering:
13473 // export {default} from 'foo';
13474 // export {foo} from 'foo';
13475 lex();
13476 src = parseModuleSpecifier();
13477 consumeSemicolon();
13478 } else if (isExportFromIdentifier) {
13479 // covering:
13480 // export {default}; // missing fromClause
13481 throwError(lookahead.value ?
13482 Messages.UnexpectedToken : Messages.MissingFromClause, lookahead.value);
13483 } else {
13484 // cover
13485 // export {foo};
13486 consumeSemicolon();
13487 }
13488 return node.finishExportNamedDeclaration(declaration, specifiers, src);
13489 }
13490
13491 function parseExportDefaultDeclaration(node) {
13492 var declaration = null,
13493 expression = null;
13494
13495 // covers:
13496 // export default ...
13497 expectKeyword('default');
13498
13499 if (matchKeyword('function')) {
13500 // covers:
13501 // export default function foo () {}
13502 // export default function () {}
13503 declaration = parseFunctionDeclaration(new Node(), true);
13504 return node.finishExportDefaultDeclaration(declaration);
13505 }
13506 if (matchKeyword('class')) {
13507 declaration = parseClassDeclaration(true);
13508 return node.finishExportDefaultDeclaration(declaration);
13509 }
13510
13511 if (matchContextualKeyword('from')) {
13512 throwError(Messages.UnexpectedToken, lookahead.value);
13513 }
13514
13515 // covers:
13516 // export default {};
13517 // export default [];
13518 // export default (1 + 2);
13519 if (match('{')) {
13520 expression = parseObjectInitializer();
13521 } else if (match('[')) {
13522 expression = parseArrayInitializer();
13523 } else {
13524 expression = parseAssignmentExpression();
13525 }
13526 consumeSemicolon();
13527 return node.finishExportDefaultDeclaration(expression);
13528 }
13529
13530 function parseExportAllDeclaration(node) {
13531 var src;
13532
13533 // covers:
13534 // export * from 'foo';
13535 expect('*');
13536 if (!matchContextualKeyword('from')) {
13537 throwError(lookahead.value ?
13538 Messages.UnexpectedToken : Messages.MissingFromClause, lookahead.value);
13539 }
13540 lex();
13541 src = parseModuleSpecifier();
13542 consumeSemicolon();
13543
13544 return node.finishExportAllDeclaration(src);
13545 }
13546
13547 function parseExportDeclaration() {
13548 var node = new Node();
13549 if (state.inFunctionBody) {
13550 throwError(Messages.IllegalExportDeclaration);
13551 }
13552
13553 expectKeyword('export');
13554
13555 if (matchKeyword('default')) {
13556 return parseExportDefaultDeclaration(node);
13557 }
13558 if (match('*')) {
13559 return parseExportAllDeclaration(node);
13560 }
13561 return parseExportNamedDeclaration(node);
13562 }
13563
13564 // ECMA-262 15.2.2 Imports
13565
13566 function parseImportSpecifier() {
13567 // import {<foo as bar>} ...;
13568 var local, imported, node = new Node();
13569
13570 imported = parseNonComputedProperty();
13571 if (matchContextualKeyword('as')) {
13572 lex();
13573 local = parseVariableIdentifier();
13574 }
13575
13576 return node.finishImportSpecifier(local, imported);
13577 }
13578
13579 function parseNamedImports() {
13580 var specifiers = [];
13581 // {foo, bar as bas}
13582 expect('{');
13583 while (!match('}')) {
13584 specifiers.push(parseImportSpecifier());
13585 if (!match('}')) {
13586 expect(',');
13587 if (match('}')) {
13588 break;
13589 }
13590 }
13591 }
13592 expect('}');
13593 return specifiers;
13594 }
13595
13596 function parseImportDefaultSpecifier() {
13597 // import <foo> ...;
13598 var local, node = new Node();
13599
13600 local = parseNonComputedProperty();
13601
13602 return node.finishImportDefaultSpecifier(local);
13603 }
13604
13605 function parseImportNamespaceSpecifier() {
13606 // import <* as foo> ...;
13607 var local, node = new Node();
13608
13609 expect('*');
13610 if (!matchContextualKeyword('as')) {
13611 throwError(Messages.NoAsAfterImportNamespace);
13612 }
13613 lex();
13614 local = parseNonComputedProperty();
13615
13616 return node.finishImportNamespaceSpecifier(local);
13617 }
13618
13619 function parseImportDeclaration() {
13620 var specifiers = [], src, node = new Node();
13621
13622 if (state.inFunctionBody) {
13623 throwError(Messages.IllegalImportDeclaration);
13624 }
13625
13626 expectKeyword('import');
13627
13628 if (lookahead.type === Token.StringLiteral) {
13629 // import 'foo';
13630 src = parseModuleSpecifier();
13631 } else {
13632
13633 if (match('{')) {
13634 // import {bar}
13635 specifiers = specifiers.concat(parseNamedImports());
13636 } else if (match('*')) {
13637 // import * as foo
13638 specifiers.push(parseImportNamespaceSpecifier());
13639 } else if (isIdentifierName(lookahead) && !matchKeyword('default')) {
13640 // import foo
13641 specifiers.push(parseImportDefaultSpecifier());
13642 if (match(',')) {
13643 lex();
13644 if (match('*')) {
13645 // import foo, * as foo
13646 specifiers.push(parseImportNamespaceSpecifier());
13647 } else if (match('{')) {
13648 // import foo, {bar}
13649 specifiers = specifiers.concat(parseNamedImports());
13650 } else {
13651 throwUnexpectedToken(lookahead);
13652 }
13653 }
13654 } else {
13655 throwUnexpectedToken(lex());
13656 }
13657
13658 if (!matchContextualKeyword('from')) {
13659 throwError(lookahead.value ?
13660 Messages.UnexpectedToken : Messages.MissingFromClause, lookahead.value);
13661 }
13662 lex();
13663 src = parseModuleSpecifier();
13664 }
13665
13666 consumeSemicolon();
13667 return node.finishImportDeclaration(specifiers, src);
13668 }
13669
13670 // ECMA-262 15.1 Scripts
13671
13672 function parseScriptBody() {
13673 var statement, body = [], token, directive, firstRestricted;
13674
13675 while (startIndex < length) {
13676 token = lookahead;
13677 if (token.type !== Token.StringLiteral) {
13678 break;
13679 }
13680
13681 statement = parseStatementListItem();
13682 body.push(statement);
13683 if (statement.expression.type !== Syntax.Literal) {
13684 // this is not directive
13685 break;
13686 }
13687 directive = source.slice(token.start + 1, token.end - 1);
13688 if (directive === 'use strict') {
13689 strict = true;
13690 if (firstRestricted) {
13691 tolerateUnexpectedToken(firstRestricted, Messages.StrictOctalLiteral);
13692 }
13693 } else {
13694 if (!firstRestricted && token.octal) {
13695 firstRestricted = token;
13696 }
13697 }
13698 }
13699
13700 while (startIndex < length) {
13701 statement = parseStatementListItem();
13702 /* istanbul ignore if */
13703 if (typeof statement === 'undefined') {
13704 break;
13705 }
13706 body.push(statement);
13707 }
13708 return body;
13709 }
13710
13711 function parseProgram() {
13712 var body, node;
13713
13714 peek();
13715 node = new Node();
13716
13717 body = parseScriptBody();
13718 return node.finishProgram(body, state.sourceType);
13719 }
13720
13721 function filterTokenLocation() {
13722 var i, entry, token, tokens = [];
13723
13724 for (i = 0; i < extra.tokens.length; ++i) {
13725 entry = extra.tokens[i];
13726 token = {
13727 type: entry.type,
13728 value: entry.value
13729 };
13730 if (entry.regex) {
13731 token.regex = {
13732 pattern: entry.regex.pattern,
13733 flags: entry.regex.flags
13734 };
13735 }
13736 if (extra.range) {
13737 token.range = entry.range;
13738 }
13739 if (extra.loc) {
13740 token.loc = entry.loc;
13741 }
13742 tokens.push(token);
13743 }
13744
13745 extra.tokens = tokens;
13746 }
13747
13748 function tokenize(code, options, delegate) {
13749 var toString,
13750 tokens;
13751
13752 toString = String;
13753 if (typeof code !== 'string' && !(code instanceof String)) {
13754 code = toString(code);
13755 }
13756
13757 source = code;
13758 index = 0;
13759 lineNumber = (source.length > 0) ? 1 : 0;
13760 lineStart = 0;
13761 startIndex = index;
13762 startLineNumber = lineNumber;
13763 startLineStart = lineStart;
13764 length = source.length;
13765 lookahead = null;
13766 state = {
13767 allowIn: true,
13768 allowYield: true,
13769 labelSet: {},
13770 inFunctionBody: false,
13771 inIteration: false,
13772 inSwitch: false,
13773 lastCommentStart: -1,
13774 curlyStack: []
13775 };
13776
13777 extra = {};
13778
13779 // Options matching.
13780 options = options || {};
13781
13782 // Of course we collect tokens here.
13783 options.tokens = true;
13784 extra.tokens = [];
13785 extra.tokenValues = [];
13786 extra.tokenize = true;
13787 extra.delegate = delegate;
13788
13789 // The following two fields are necessary to compute the Regex tokens.
13790 extra.openParenToken = -1;
13791 extra.openCurlyToken = -1;
13792
13793 extra.range = (typeof options.range === 'boolean') && options.range;
13794 extra.loc = (typeof options.loc === 'boolean') && options.loc;
13795
13796 if (typeof options.comment === 'boolean' && options.comment) {
13797 extra.comments = [];
13798 }
13799 if (typeof options.tolerant === 'boolean' && options.tolerant) {
13800 extra.errors = [];
13801 }
13802
13803 try {
13804 peek();
13805 if (lookahead.type === Token.EOF) {
13806 return extra.tokens;
13807 }
13808
13809 lex();
13810 while (lookahead.type !== Token.EOF) {
13811 try {
13812 lex();
13813 } catch (lexError) {
13814 if (extra.errors) {
13815 recordError(lexError);
13816 // We have to break on the first error
13817 // to avoid infinite loops.
13818 break;
13819 } else {
13820 throw lexError;
13821 }
13822 }
13823 }
13824
13825 tokens = extra.tokens;
13826 if (typeof extra.errors !== 'undefined') {
13827 tokens.errors = extra.errors;
13828 }
13829 } catch (e) {
13830 throw e;
13831 } finally {
13832 extra = {};
13833 }
13834 return tokens;
13835 }
13836
13837 function parse(code, options) {
13838 var program, toString;
13839
13840 toString = String;
13841 if (typeof code !== 'string' && !(code instanceof String)) {
13842 code = toString(code);
13843 }
13844
13845 source = code;
13846 index = 0;
13847 lineNumber = (source.length > 0) ? 1 : 0;
13848 lineStart = 0;
13849 startIndex = index;
13850 startLineNumber = lineNumber;
13851 startLineStart = lineStart;
13852 length = source.length;
13853 lookahead = null;
13854 state = {
13855 allowIn: true,
13856 allowYield: true,
13857 labelSet: {},
13858 inFunctionBody: false,
13859 inIteration: false,
13860 inSwitch: false,
13861 lastCommentStart: -1,
13862 curlyStack: [],
13863 sourceType: 'script'
13864 };
13865 strict = false;
13866
13867 extra = {};
13868 if (typeof options !== 'undefined') {
13869 extra.range = (typeof options.range === 'boolean') && options.range;
13870 extra.loc = (typeof options.loc === 'boolean') && options.loc;
13871 extra.attachComment = (typeof options.attachComment === 'boolean') && options.attachComment;
13872
13873 if (extra.loc && options.source !== null && options.source !== undefined) {
13874 extra.source = toString(options.source);
13875 }
13876
13877 if (typeof options.tokens === 'boolean' && options.tokens) {
13878 extra.tokens = [];
13879 }
13880 if (typeof options.comment === 'boolean' && options.comment) {
13881 extra.comments = [];
13882 }
13883 if (typeof options.tolerant === 'boolean' && options.tolerant) {
13884 extra.errors = [];
13885 }
13886 if (extra.attachComment) {
13887 extra.range = true;
13888 extra.comments = [];
13889 extra.bottomRightStack = [];
13890 extra.trailingComments = [];
13891 extra.leadingComments = [];
13892 }
13893 if (options.sourceType === 'module') {
13894 // very restrictive condition for now
13895 state.sourceType = options.sourceType;
13896 strict = true;
13897 }
13898 }
13899
13900 try {
13901 program = parseProgram();
13902 if (typeof extra.comments !== 'undefined') {
13903 program.comments = extra.comments;
13904 }
13905 if (typeof extra.tokens !== 'undefined') {
13906 filterTokenLocation();
13907 program.tokens = extra.tokens;
13908 }
13909 if (typeof extra.errors !== 'undefined') {
13910 program.errors = extra.errors;
13911 }
13912 } catch (e) {
13913 throw e;
13914 } finally {
13915 extra = {};
13916 }
13917
13918 return program;
13919 }
13920
13921 // Sync with *.json manifests.
13922 exports.version = '2.7.2';
13923
13924 exports.tokenize = tokenize;
13925
13926 exports.parse = parse;
13927
13928 // Deep copy.
13929 /* istanbul ignore next */
13930 exports.Syntax = (function () {
13931 var name, types = {};
13932
13933 if (typeof Object.create === 'function') {
13934 types = Object.create(null);
13935 }
13936
13937 for (name in Syntax) {
13938 if (Syntax.hasOwnProperty(name)) {
13939 types[name] = Syntax[name];
13940 }
13941 }
13942
13943 if (typeof Object.freeze === 'function') {
13944 Object.freeze(types);
13945 }
13946
13947 return types;
13948 }());
13949
13950}));
13951/* vim: set sw=4 ts=4 et tw=80 : */
13952
13953},{}],87:[function(_dereq_,module,exports){
13954/**
13955 * espurify - Clone new AST without extra properties
13956 *
13957 * https://github.com/estools/espurify
13958 *
13959 * Copyright (c) 2014-2016 Takuto Wada
13960 * Licensed under the MIT license.
13961 * https://github.com/estools/espurify/blob/master/MIT-LICENSE.txt
13962 */
13963'use strict';
13964
13965var createWhitelist = _dereq_('./lib/create-whitelist');
13966var cloneWithWhitelist = _dereq_('./lib/clone-ast');
13967
13968function createCloneFunction (options) {
13969 return cloneWithWhitelist(createWhitelist(options));
13970}
13971
13972var espurify = createCloneFunction();
13973espurify.customize = createCloneFunction;
13974espurify.cloneWithWhitelist = cloneWithWhitelist;
13975module.exports = espurify;
13976
13977},{"./lib/clone-ast":89,"./lib/create-whitelist":90}],88:[function(_dereq_,module,exports){
13978module.exports = {
13979 ArrayExpression: ['type', 'elements'],
13980 ArrayPattern: ['type', 'elements'],
13981 ArrowFunctionExpression: ['type', 'id', 'params', 'body', 'generator', 'expression'],
13982 AssignmentExpression: ['type', 'operator', 'left', 'right'],
13983 AssignmentPattern: ['type', 'left', 'right'],
13984 BinaryExpression: ['type', 'operator', 'left', 'right'],
13985 BlockStatement: ['type', 'body'],
13986 BreakStatement: ['type', 'label'],
13987 CallExpression: ['type', 'callee', 'arguments'],
13988 CatchClause: ['type', 'param', 'guard', 'body'],
13989 ClassBody: ['type', 'body'],
13990 ClassDeclaration: ['type', 'id', 'superClass', 'body'],
13991 ClassExpression: ['type', 'id', 'superClass', 'body'],
13992 ConditionalExpression: ['type', 'test', 'alternate', 'consequent'],
13993 ContinueStatement: ['type', 'label'],
13994 DebuggerStatement: ['type'],
13995 DoWhileStatement: ['type', 'body', 'test'],
13996 EmptyStatement: ['type'],
13997 ExportAllDeclaration: ['type', 'source'],
13998 ExportDefaultDeclaration: ['type', 'declaration'],
13999 ExportNamedDeclaration: ['type', 'declaration', 'specifiers', 'source'],
14000 ExportSpecifier: ['type', 'exported', 'local'],
14001 ExpressionStatement: ['type', 'expression'],
14002 ForInStatement: ['type', 'left', 'right', 'body'],
14003 ForOfStatement: ['type', 'left', 'right', 'body'],
14004 ForStatement: ['type', 'init', 'test', 'update', 'body'],
14005 FunctionDeclaration: ['type', 'id', 'params', 'body', 'generator'],
14006 FunctionExpression: ['type', 'id', 'params', 'body', 'generator'],
14007 Identifier: ['type', 'name'],
14008 IfStatement: ['type', 'test', 'consequent', 'alternate'],
14009 ImportDeclaration: ['type', 'specifiers', 'source'],
14010 ImportDefaultSpecifier: ['type', 'local'],
14011 ImportNamespaceSpecifier: ['type', 'local'],
14012 ImportSpecifier: ['type', 'imported', 'local'],
14013 LabeledStatement: ['type', 'label', 'body'],
14014 Literal: ['type', 'value', 'regex'],
14015 LogicalExpression: ['type', 'operator', 'left', 'right'],
14016 MemberExpression: ['type', 'object', 'property', 'computed'],
14017 MetaProperty: ['type', 'meta', 'property'],
14018 MethodDefinition: ['type', 'key', 'value', 'kind', 'computed', 'static'],
14019 NewExpression: ['type', 'callee', 'arguments'],
14020 ObjectExpression: ['type', 'properties'],
14021 ObjectPattern: ['type', 'properties'],
14022 Program: ['type', 'body', 'sourceType'],
14023 Property: ['type', 'key', 'value', 'kind', 'method', 'shorthand', 'computed'],
14024 RestElement: ['type', 'argument'],
14025 ReturnStatement: ['type', 'argument'],
14026 SequenceExpression: ['type', 'expressions'],
14027 SpreadElement: ['type', 'argument'],
14028 Super: ['type'],
14029 SwitchCase: ['type', 'test', 'consequent'],
14030 SwitchStatement: ['type', 'discriminant', 'cases', 'lexical'],
14031 TaggedTemplateExpression: ['type', 'tag', 'quasi'],
14032 TemplateElement: ['type', 'tail', 'value'],
14033 TemplateLiteral: ['type', 'quasis', 'expressions'],
14034 ThisExpression: ['type'],
14035 ThrowStatement: ['type', 'argument'],
14036 TryStatement: ['type', 'block', 'handler', 'finalizer'],
14037 UnaryExpression: ['type', 'operator', 'prefix', 'argument'],
14038 UpdateExpression: ['type', 'operator', 'argument', 'prefix'],
14039 VariableDeclaration: ['type', 'declarations', 'kind'],
14040 VariableDeclarator: ['type', 'id', 'init'],
14041 WhileStatement: ['type', 'test', 'body'],
14042 WithStatement: ['type', 'object', 'body'],
14043 YieldExpression: ['type', 'argument', 'delegate']
14044};
14045
14046},{}],89:[function(_dereq_,module,exports){
14047'use strict';
14048
14049var isArray = _dereq_('core-js/library/fn/array/is-array');
14050var objectKeys = _dereq_('core-js/library/fn/object/keys');
14051var indexOf = _dereq_('core-js/library/fn/array/index-of');
14052var reduce = _dereq_('core-js/library/fn/array/reduce');
14053
14054module.exports = function cloneWithWhitelist (astWhiteList) {
14055 var whitelist = reduce(objectKeys(astWhiteList), function (props, key) {
14056 var propNames = astWhiteList[key];
14057 var prepend = (indexOf(propNames, 'type') === -1) ? ['type'] : [];
14058 props[key] = prepend.concat(propNames);
14059 return props;
14060 }, {});
14061
14062 function cloneNodeOrObject (obj) {
14063 var props = obj.type ? whitelist[obj.type] : null;
14064 if (props) {
14065 return cloneNode(obj, props);
14066 } else {
14067 return cloneObject(obj);
14068 }
14069 }
14070
14071 function cloneArray (ary) {
14072 var i = ary.length, clone = [];
14073 while (i--) {
14074 clone[i] = cloneOf(ary[i]);
14075 }
14076 return clone;
14077 }
14078
14079 function cloneNode (node, props) {
14080 var i, len, key, clone = {};
14081 for (i = 0, len = props.length; i < len; i += 1) {
14082 key = props[i];
14083 if (node.hasOwnProperty(key)) {
14084 clone[key] = cloneOf(node[key]);
14085 }
14086 }
14087 return clone;
14088 }
14089
14090 function cloneObject (obj) {
14091 var props = objectKeys(obj);
14092 var i, len, key, clone = {};
14093 for (i = 0, len = props.length; i < len; i += 1) {
14094 key = props[i];
14095 clone[key] = cloneOf(obj[key]);
14096 }
14097 return clone;
14098 }
14099
14100 function cloneOf (val) {
14101 if (typeof val === 'object' && val !== null) {
14102 if (val instanceof RegExp) {
14103 return new RegExp(val);
14104 } else if (isArray(val)) {
14105 return cloneArray(val);
14106 } else {
14107 return cloneNodeOrObject(val);
14108 }
14109 } else {
14110 return val;
14111 }
14112 }
14113
14114 return cloneNodeOrObject;
14115};
14116
14117},{"core-js/library/fn/array/index-of":16,"core-js/library/fn/array/is-array":17,"core-js/library/fn/array/reduce":18,"core-js/library/fn/object/keys":20}],90:[function(_dereq_,module,exports){
14118'use strict';
14119
14120var defaultProps = _dereq_('./ast-properties');
14121var objectKeys = _dereq_('core-js/library/fn/object/keys');
14122var assign = _dereq_('core-js/library/fn/object/assign');
14123
14124module.exports = function createWhitelist (options) {
14125 var opts = assign({}, options);
14126 var typeName, i, len;
14127 var keys = objectKeys(defaultProps);
14128 var result = {};
14129 for (i = 0, len = keys.length; i < len; i += 1) {
14130 typeName = keys[i];
14131 result[typeName] = defaultProps[typeName].concat(opts.extra);
14132 }
14133 return result;
14134};
14135
14136},{"./ast-properties":88,"core-js/library/fn/object/assign":19,"core-js/library/fn/object/keys":20}],91:[function(_dereq_,module,exports){
14137/*
14138 Copyright (C) 2012-2013 Yusuke Suzuki <utatane.tea@gmail.com>
14139 Copyright (C) 2012 Ariya Hidayat <ariya.hidayat@gmail.com>
14140
14141 Redistribution and use in source and binary forms, with or without
14142 modification, are permitted provided that the following conditions are met:
14143
14144 * Redistributions of source code must retain the above copyright
14145 notice, this list of conditions and the following disclaimer.
14146 * Redistributions in binary form must reproduce the above copyright
14147 notice, this list of conditions and the following disclaimer in the
14148 documentation and/or other materials provided with the distribution.
14149
14150 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
14151 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
14152 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
14153 ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
14154 DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
14155 (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
14156 LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
14157 ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
14158 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
14159 THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
14160*/
14161/*jslint vars:false, bitwise:true*/
14162/*jshint indent:4*/
14163/*global exports:true*/
14164(function clone(exports) {
14165 'use strict';
14166
14167 var Syntax,
14168 isArray,
14169 VisitorOption,
14170 VisitorKeys,
14171 objectCreate,
14172 objectKeys,
14173 BREAK,
14174 SKIP,
14175 REMOVE;
14176
14177 function ignoreJSHintError() { }
14178
14179 isArray = Array.isArray;
14180 if (!isArray) {
14181 isArray = function isArray(array) {
14182 return Object.prototype.toString.call(array) === '[object Array]';
14183 };
14184 }
14185
14186 function deepCopy(obj) {
14187 var ret = {}, key, val;
14188 for (key in obj) {
14189 if (obj.hasOwnProperty(key)) {
14190 val = obj[key];
14191 if (typeof val === 'object' && val !== null) {
14192 ret[key] = deepCopy(val);
14193 } else {
14194 ret[key] = val;
14195 }
14196 }
14197 }
14198 return ret;
14199 }
14200
14201 function shallowCopy(obj) {
14202 var ret = {}, key;
14203 for (key in obj) {
14204 if (obj.hasOwnProperty(key)) {
14205 ret[key] = obj[key];
14206 }
14207 }
14208 return ret;
14209 }
14210 ignoreJSHintError(shallowCopy);
14211
14212 // based on LLVM libc++ upper_bound / lower_bound
14213 // MIT License
14214
14215 function upperBound(array, func) {
14216 var diff, len, i, current;
14217
14218 len = array.length;
14219 i = 0;
14220
14221 while (len) {
14222 diff = len >>> 1;
14223 current = i + diff;
14224 if (func(array[current])) {
14225 len = diff;
14226 } else {
14227 i = current + 1;
14228 len -= diff + 1;
14229 }
14230 }
14231 return i;
14232 }
14233
14234 function lowerBound(array, func) {
14235 var diff, len, i, current;
14236
14237 len = array.length;
14238 i = 0;
14239
14240 while (len) {
14241 diff = len >>> 1;
14242 current = i + diff;
14243 if (func(array[current])) {
14244 i = current + 1;
14245 len -= diff + 1;
14246 } else {
14247 len = diff;
14248 }
14249 }
14250 return i;
14251 }
14252 ignoreJSHintError(lowerBound);
14253
14254 objectCreate = Object.create || (function () {
14255 function F() { }
14256
14257 return function (o) {
14258 F.prototype = o;
14259 return new F();
14260 };
14261 })();
14262
14263 objectKeys = Object.keys || function (o) {
14264 var keys = [], key;
14265 for (key in o) {
14266 keys.push(key);
14267 }
14268 return keys;
14269 };
14270
14271 function extend(to, from) {
14272 var keys = objectKeys(from), key, i, len;
14273 for (i = 0, len = keys.length; i < len; i += 1) {
14274 key = keys[i];
14275 to[key] = from[key];
14276 }
14277 return to;
14278 }
14279
14280 Syntax = {
14281 AssignmentExpression: 'AssignmentExpression',
14282 AssignmentPattern: 'AssignmentPattern',
14283 ArrayExpression: 'ArrayExpression',
14284 ArrayPattern: 'ArrayPattern',
14285 ArrowFunctionExpression: 'ArrowFunctionExpression',
14286 AwaitExpression: 'AwaitExpression', // CAUTION: It's deferred to ES7.
14287 BlockStatement: 'BlockStatement',
14288 BinaryExpression: 'BinaryExpression',
14289 BreakStatement: 'BreakStatement',
14290 CallExpression: 'CallExpression',
14291 CatchClause: 'CatchClause',
14292 ClassBody: 'ClassBody',
14293 ClassDeclaration: 'ClassDeclaration',
14294 ClassExpression: 'ClassExpression',
14295 ComprehensionBlock: 'ComprehensionBlock', // CAUTION: It's deferred to ES7.
14296 ComprehensionExpression: 'ComprehensionExpression', // CAUTION: It's deferred to ES7.
14297 ConditionalExpression: 'ConditionalExpression',
14298 ContinueStatement: 'ContinueStatement',
14299 DebuggerStatement: 'DebuggerStatement',
14300 DirectiveStatement: 'DirectiveStatement',
14301 DoWhileStatement: 'DoWhileStatement',
14302 EmptyStatement: 'EmptyStatement',
14303 ExportAllDeclaration: 'ExportAllDeclaration',
14304 ExportDefaultDeclaration: 'ExportDefaultDeclaration',
14305 ExportNamedDeclaration: 'ExportNamedDeclaration',
14306 ExportSpecifier: 'ExportSpecifier',
14307 ExpressionStatement: 'ExpressionStatement',
14308 ForStatement: 'ForStatement',
14309 ForInStatement: 'ForInStatement',
14310 ForOfStatement: 'ForOfStatement',
14311 FunctionDeclaration: 'FunctionDeclaration',
14312 FunctionExpression: 'FunctionExpression',
14313 GeneratorExpression: 'GeneratorExpression', // CAUTION: It's deferred to ES7.
14314 Identifier: 'Identifier',
14315 IfStatement: 'IfStatement',
14316 ImportDeclaration: 'ImportDeclaration',
14317 ImportDefaultSpecifier: 'ImportDefaultSpecifier',
14318 ImportNamespaceSpecifier: 'ImportNamespaceSpecifier',
14319 ImportSpecifier: 'ImportSpecifier',
14320 Literal: 'Literal',
14321 LabeledStatement: 'LabeledStatement',
14322 LogicalExpression: 'LogicalExpression',
14323 MemberExpression: 'MemberExpression',
14324 MetaProperty: 'MetaProperty',
14325 MethodDefinition: 'MethodDefinition',
14326 ModuleSpecifier: 'ModuleSpecifier',
14327 NewExpression: 'NewExpression',
14328 ObjectExpression: 'ObjectExpression',
14329 ObjectPattern: 'ObjectPattern',
14330 Program: 'Program',
14331 Property: 'Property',
14332 RestElement: 'RestElement',
14333 ReturnStatement: 'ReturnStatement',
14334 SequenceExpression: 'SequenceExpression',
14335 SpreadElement: 'SpreadElement',
14336 Super: 'Super',
14337 SwitchStatement: 'SwitchStatement',
14338 SwitchCase: 'SwitchCase',
14339 TaggedTemplateExpression: 'TaggedTemplateExpression',
14340 TemplateElement: 'TemplateElement',
14341 TemplateLiteral: 'TemplateLiteral',
14342 ThisExpression: 'ThisExpression',
14343 ThrowStatement: 'ThrowStatement',
14344 TryStatement: 'TryStatement',
14345 UnaryExpression: 'UnaryExpression',
14346 UpdateExpression: 'UpdateExpression',
14347 VariableDeclaration: 'VariableDeclaration',
14348 VariableDeclarator: 'VariableDeclarator',
14349 WhileStatement: 'WhileStatement',
14350 WithStatement: 'WithStatement',
14351 YieldExpression: 'YieldExpression'
14352 };
14353
14354 VisitorKeys = {
14355 AssignmentExpression: ['left', 'right'],
14356 AssignmentPattern: ['left', 'right'],
14357 ArrayExpression: ['elements'],
14358 ArrayPattern: ['elements'],
14359 ArrowFunctionExpression: ['params', 'body'],
14360 AwaitExpression: ['argument'], // CAUTION: It's deferred to ES7.
14361 BlockStatement: ['body'],
14362 BinaryExpression: ['left', 'right'],
14363 BreakStatement: ['label'],
14364 CallExpression: ['callee', 'arguments'],
14365 CatchClause: ['param', 'body'],
14366 ClassBody: ['body'],
14367 ClassDeclaration: ['id', 'superClass', 'body'],
14368 ClassExpression: ['id', 'superClass', 'body'],
14369 ComprehensionBlock: ['left', 'right'], // CAUTION: It's deferred to ES7.
14370 ComprehensionExpression: ['blocks', 'filter', 'body'], // CAUTION: It's deferred to ES7.
14371 ConditionalExpression: ['test', 'consequent', 'alternate'],
14372 ContinueStatement: ['label'],
14373 DebuggerStatement: [],
14374 DirectiveStatement: [],
14375 DoWhileStatement: ['body', 'test'],
14376 EmptyStatement: [],
14377 ExportAllDeclaration: ['source'],
14378 ExportDefaultDeclaration: ['declaration'],
14379 ExportNamedDeclaration: ['declaration', 'specifiers', 'source'],
14380 ExportSpecifier: ['exported', 'local'],
14381 ExpressionStatement: ['expression'],
14382 ForStatement: ['init', 'test', 'update', 'body'],
14383 ForInStatement: ['left', 'right', 'body'],
14384 ForOfStatement: ['left', 'right', 'body'],
14385 FunctionDeclaration: ['id', 'params', 'body'],
14386 FunctionExpression: ['id', 'params', 'body'],
14387 GeneratorExpression: ['blocks', 'filter', 'body'], // CAUTION: It's deferred to ES7.
14388 Identifier: [],
14389 IfStatement: ['test', 'consequent', 'alternate'],
14390 ImportDeclaration: ['specifiers', 'source'],
14391 ImportDefaultSpecifier: ['local'],
14392 ImportNamespaceSpecifier: ['local'],
14393 ImportSpecifier: ['imported', 'local'],
14394 Literal: [],
14395 LabeledStatement: ['label', 'body'],
14396 LogicalExpression: ['left', 'right'],
14397 MemberExpression: ['object', 'property'],
14398 MetaProperty: ['meta', 'property'],
14399 MethodDefinition: ['key', 'value'],
14400 ModuleSpecifier: [],
14401 NewExpression: ['callee', 'arguments'],
14402 ObjectExpression: ['properties'],
14403 ObjectPattern: ['properties'],
14404 Program: ['body'],
14405 Property: ['key', 'value'],
14406 RestElement: [ 'argument' ],
14407 ReturnStatement: ['argument'],
14408 SequenceExpression: ['expressions'],
14409 SpreadElement: ['argument'],
14410 Super: [],
14411 SwitchStatement: ['discriminant', 'cases'],
14412 SwitchCase: ['test', 'consequent'],
14413 TaggedTemplateExpression: ['tag', 'quasi'],
14414 TemplateElement: [],
14415 TemplateLiteral: ['quasis', 'expressions'],
14416 ThisExpression: [],
14417 ThrowStatement: ['argument'],
14418 TryStatement: ['block', 'handler', 'finalizer'],
14419 UnaryExpression: ['argument'],
14420 UpdateExpression: ['argument'],
14421 VariableDeclaration: ['declarations'],
14422 VariableDeclarator: ['id', 'init'],
14423 WhileStatement: ['test', 'body'],
14424 WithStatement: ['object', 'body'],
14425 YieldExpression: ['argument']
14426 };
14427
14428 // unique id
14429 BREAK = {};
14430 SKIP = {};
14431 REMOVE = {};
14432
14433 VisitorOption = {
14434 Break: BREAK,
14435 Skip: SKIP,
14436 Remove: REMOVE
14437 };
14438
14439 function Reference(parent, key) {
14440 this.parent = parent;
14441 this.key = key;
14442 }
14443
14444 Reference.prototype.replace = function replace(node) {
14445 this.parent[this.key] = node;
14446 };
14447
14448 Reference.prototype.remove = function remove() {
14449 if (isArray(this.parent)) {
14450 this.parent.splice(this.key, 1);
14451 return true;
14452 } else {
14453 this.replace(null);
14454 return false;
14455 }
14456 };
14457
14458 function Element(node, path, wrap, ref) {
14459 this.node = node;
14460 this.path = path;
14461 this.wrap = wrap;
14462 this.ref = ref;
14463 }
14464
14465 function Controller() { }
14466
14467 // API:
14468 // return property path array from root to current node
14469 Controller.prototype.path = function path() {
14470 var i, iz, j, jz, result, element;
14471
14472 function addToPath(result, path) {
14473 if (isArray(path)) {
14474 for (j = 0, jz = path.length; j < jz; ++j) {
14475 result.push(path[j]);
14476 }
14477 } else {
14478 result.push(path);
14479 }
14480 }
14481
14482 // root node
14483 if (!this.__current.path) {
14484 return null;
14485 }
14486
14487 // first node is sentinel, second node is root element
14488 result = [];
14489 for (i = 2, iz = this.__leavelist.length; i < iz; ++i) {
14490 element = this.__leavelist[i];
14491 addToPath(result, element.path);
14492 }
14493 addToPath(result, this.__current.path);
14494 return result;
14495 };
14496
14497 // API:
14498 // return type of current node
14499 Controller.prototype.type = function () {
14500 var node = this.current();
14501 return node.type || this.__current.wrap;
14502 };
14503
14504 // API:
14505 // return array of parent elements
14506 Controller.prototype.parents = function parents() {
14507 var i, iz, result;
14508
14509 // first node is sentinel
14510 result = [];
14511 for (i = 1, iz = this.__leavelist.length; i < iz; ++i) {
14512 result.push(this.__leavelist[i].node);
14513 }
14514
14515 return result;
14516 };
14517
14518 // API:
14519 // return current node
14520 Controller.prototype.current = function current() {
14521 return this.__current.node;
14522 };
14523
14524 Controller.prototype.__execute = function __execute(callback, element) {
14525 var previous, result;
14526
14527 result = undefined;
14528
14529 previous = this.__current;
14530 this.__current = element;
14531 this.__state = null;
14532 if (callback) {
14533 result = callback.call(this, element.node, this.__leavelist[this.__leavelist.length - 1].node);
14534 }
14535 this.__current = previous;
14536
14537 return result;
14538 };
14539
14540 // API:
14541 // notify control skip / break
14542 Controller.prototype.notify = function notify(flag) {
14543 this.__state = flag;
14544 };
14545
14546 // API:
14547 // skip child nodes of current node
14548 Controller.prototype.skip = function () {
14549 this.notify(SKIP);
14550 };
14551
14552 // API:
14553 // break traversals
14554 Controller.prototype['break'] = function () {
14555 this.notify(BREAK);
14556 };
14557
14558 // API:
14559 // remove node
14560 Controller.prototype.remove = function () {
14561 this.notify(REMOVE);
14562 };
14563
14564 Controller.prototype.__initialize = function(root, visitor) {
14565 this.visitor = visitor;
14566 this.root = root;
14567 this.__worklist = [];
14568 this.__leavelist = [];
14569 this.__current = null;
14570 this.__state = null;
14571 this.__fallback = null;
14572 if (visitor.fallback === 'iteration') {
14573 this.__fallback = objectKeys;
14574 } else if (typeof visitor.fallback === 'function') {
14575 this.__fallback = visitor.fallback;
14576 }
14577
14578 this.__keys = VisitorKeys;
14579 if (visitor.keys) {
14580 this.__keys = extend(objectCreate(this.__keys), visitor.keys);
14581 }
14582 };
14583
14584 function isNode(node) {
14585 if (node == null) {
14586 return false;
14587 }
14588 return typeof node === 'object' && typeof node.type === 'string';
14589 }
14590
14591 function isProperty(nodeType, key) {
14592 return (nodeType === Syntax.ObjectExpression || nodeType === Syntax.ObjectPattern) && 'properties' === key;
14593 }
14594
14595 Controller.prototype.traverse = function traverse(root, visitor) {
14596 var worklist,
14597 leavelist,
14598 element,
14599 node,
14600 nodeType,
14601 ret,
14602 key,
14603 current,
14604 current2,
14605 candidates,
14606 candidate,
14607 sentinel;
14608
14609 this.__initialize(root, visitor);
14610
14611 sentinel = {};
14612
14613 // reference
14614 worklist = this.__worklist;
14615 leavelist = this.__leavelist;
14616
14617 // initialize
14618 worklist.push(new Element(root, null, null, null));
14619 leavelist.push(new Element(null, null, null, null));
14620
14621 while (worklist.length) {
14622 element = worklist.pop();
14623
14624 if (element === sentinel) {
14625 element = leavelist.pop();
14626
14627 ret = this.__execute(visitor.leave, element);
14628
14629 if (this.__state === BREAK || ret === BREAK) {
14630 return;
14631 }
14632 continue;
14633 }
14634
14635 if (element.node) {
14636
14637 ret = this.__execute(visitor.enter, element);
14638
14639 if (this.__state === BREAK || ret === BREAK) {
14640 return;
14641 }
14642
14643 worklist.push(sentinel);
14644 leavelist.push(element);
14645
14646 if (this.__state === SKIP || ret === SKIP) {
14647 continue;
14648 }
14649
14650 node = element.node;
14651 nodeType = node.type || element.wrap;
14652 candidates = this.__keys[nodeType];
14653 if (!candidates) {
14654 if (this.__fallback) {
14655 candidates = this.__fallback(node);
14656 } else {
14657 throw new Error('Unknown node type ' + nodeType + '.');
14658 }
14659 }
14660
14661 current = candidates.length;
14662 while ((current -= 1) >= 0) {
14663 key = candidates[current];
14664 candidate = node[key];
14665 if (!candidate) {
14666 continue;
14667 }
14668
14669 if (isArray(candidate)) {
14670 current2 = candidate.length;
14671 while ((current2 -= 1) >= 0) {
14672 if (!candidate[current2]) {
14673 continue;
14674 }
14675 if (isProperty(nodeType, candidates[current])) {
14676 element = new Element(candidate[current2], [key, current2], 'Property', null);
14677 } else if (isNode(candidate[current2])) {
14678 element = new Element(candidate[current2], [key, current2], null, null);
14679 } else {
14680 continue;
14681 }
14682 worklist.push(element);
14683 }
14684 } else if (isNode(candidate)) {
14685 worklist.push(new Element(candidate, key, null, null));
14686 }
14687 }
14688 }
14689 }
14690 };
14691
14692 Controller.prototype.replace = function replace(root, visitor) {
14693 var worklist,
14694 leavelist,
14695 node,
14696 nodeType,
14697 target,
14698 element,
14699 current,
14700 current2,
14701 candidates,
14702 candidate,
14703 sentinel,
14704 outer,
14705 key;
14706
14707 function removeElem(element) {
14708 var i,
14709 key,
14710 nextElem,
14711 parent;
14712
14713 if (element.ref.remove()) {
14714 // When the reference is an element of an array.
14715 key = element.ref.key;
14716 parent = element.ref.parent;
14717
14718 // If removed from array, then decrease following items' keys.
14719 i = worklist.length;
14720 while (i--) {
14721 nextElem = worklist[i];
14722 if (nextElem.ref && nextElem.ref.parent === parent) {
14723 if (nextElem.ref.key < key) {
14724 break;
14725 }
14726 --nextElem.ref.key;
14727 }
14728 }
14729 }
14730 }
14731
14732 this.__initialize(root, visitor);
14733
14734 sentinel = {};
14735
14736 // reference
14737 worklist = this.__worklist;
14738 leavelist = this.__leavelist;
14739
14740 // initialize
14741 outer = {
14742 root: root
14743 };
14744 element = new Element(root, null, null, new Reference(outer, 'root'));
14745 worklist.push(element);
14746 leavelist.push(element);
14747
14748 while (worklist.length) {
14749 element = worklist.pop();
14750
14751 if (element === sentinel) {
14752 element = leavelist.pop();
14753
14754 target = this.__execute(visitor.leave, element);
14755
14756 // node may be replaced with null,
14757 // so distinguish between undefined and null in this place
14758 if (target !== undefined && target !== BREAK && target !== SKIP && target !== REMOVE) {
14759 // replace
14760 element.ref.replace(target);
14761 }
14762
14763 if (this.__state === REMOVE || target === REMOVE) {
14764 removeElem(element);
14765 }
14766
14767 if (this.__state === BREAK || target === BREAK) {
14768 return outer.root;
14769 }
14770 continue;
14771 }
14772
14773 target = this.__execute(visitor.enter, element);
14774
14775 // node may be replaced with null,
14776 // so distinguish between undefined and null in this place
14777 if (target !== undefined && target !== BREAK && target !== SKIP && target !== REMOVE) {
14778 // replace
14779 element.ref.replace(target);
14780 element.node = target;
14781 }
14782
14783 if (this.__state === REMOVE || target === REMOVE) {
14784 removeElem(element);
14785 element.node = null;
14786 }
14787
14788 if (this.__state === BREAK || target === BREAK) {
14789 return outer.root;
14790 }
14791
14792 // node may be null
14793 node = element.node;
14794 if (!node) {
14795 continue;
14796 }
14797
14798 worklist.push(sentinel);
14799 leavelist.push(element);
14800
14801 if (this.__state === SKIP || target === SKIP) {
14802 continue;
14803 }
14804
14805 nodeType = node.type || element.wrap;
14806 candidates = this.__keys[nodeType];
14807 if (!candidates) {
14808 if (this.__fallback) {
14809 candidates = this.__fallback(node);
14810 } else {
14811 throw new Error('Unknown node type ' + nodeType + '.');
14812 }
14813 }
14814
14815 current = candidates.length;
14816 while ((current -= 1) >= 0) {
14817 key = candidates[current];
14818 candidate = node[key];
14819 if (!candidate) {
14820 continue;
14821 }
14822
14823 if (isArray(candidate)) {
14824 current2 = candidate.length;
14825 while ((current2 -= 1) >= 0) {
14826 if (!candidate[current2]) {
14827 continue;
14828 }
14829 if (isProperty(nodeType, candidates[current])) {
14830 element = new Element(candidate[current2], [key, current2], 'Property', new Reference(candidate, current2));
14831 } else if (isNode(candidate[current2])) {
14832 element = new Element(candidate[current2], [key, current2], null, new Reference(candidate, current2));
14833 } else {
14834 continue;
14835 }
14836 worklist.push(element);
14837 }
14838 } else if (isNode(candidate)) {
14839 worklist.push(new Element(candidate, key, null, new Reference(node, key)));
14840 }
14841 }
14842 }
14843
14844 return outer.root;
14845 };
14846
14847 function traverse(root, visitor) {
14848 var controller = new Controller();
14849 return controller.traverse(root, visitor);
14850 }
14851
14852 function replace(root, visitor) {
14853 var controller = new Controller();
14854 return controller.replace(root, visitor);
14855 }
14856
14857 function extendCommentRange(comment, tokens) {
14858 var target;
14859
14860 target = upperBound(tokens, function search(token) {
14861 return token.range[0] > comment.range[0];
14862 });
14863
14864 comment.extendedRange = [comment.range[0], comment.range[1]];
14865
14866 if (target !== tokens.length) {
14867 comment.extendedRange[1] = tokens[target].range[0];
14868 }
14869
14870 target -= 1;
14871 if (target >= 0) {
14872 comment.extendedRange[0] = tokens[target].range[1];
14873 }
14874
14875 return comment;
14876 }
14877
14878 function attachComments(tree, providedComments, tokens) {
14879 // At first, we should calculate extended comment ranges.
14880 var comments = [], comment, len, i, cursor;
14881
14882 if (!tree.range) {
14883 throw new Error('attachComments needs range information');
14884 }
14885
14886 // tokens array is empty, we attach comments to tree as 'leadingComments'
14887 if (!tokens.length) {
14888 if (providedComments.length) {
14889 for (i = 0, len = providedComments.length; i < len; i += 1) {
14890 comment = deepCopy(providedComments[i]);
14891 comment.extendedRange = [0, tree.range[0]];
14892 comments.push(comment);
14893 }
14894 tree.leadingComments = comments;
14895 }
14896 return tree;
14897 }
14898
14899 for (i = 0, len = providedComments.length; i < len; i += 1) {
14900 comments.push(extendCommentRange(deepCopy(providedComments[i]), tokens));
14901 }
14902
14903 // This is based on John Freeman's implementation.
14904 cursor = 0;
14905 traverse(tree, {
14906 enter: function (node) {
14907 var comment;
14908
14909 while (cursor < comments.length) {
14910 comment = comments[cursor];
14911 if (comment.extendedRange[1] > node.range[0]) {
14912 break;
14913 }
14914
14915 if (comment.extendedRange[1] === node.range[0]) {
14916 if (!node.leadingComments) {
14917 node.leadingComments = [];
14918 }
14919 node.leadingComments.push(comment);
14920 comments.splice(cursor, 1);
14921 } else {
14922 cursor += 1;
14923 }
14924 }
14925
14926 // already out of owned node
14927 if (cursor === comments.length) {
14928 return VisitorOption.Break;
14929 }
14930
14931 if (comments[cursor].extendedRange[0] > node.range[1]) {
14932 return VisitorOption.Skip;
14933 }
14934 }
14935 });
14936
14937 cursor = 0;
14938 traverse(tree, {
14939 leave: function (node) {
14940 var comment;
14941
14942 while (cursor < comments.length) {
14943 comment = comments[cursor];
14944 if (node.range[1] < comment.extendedRange[0]) {
14945 break;
14946 }
14947
14948 if (node.range[1] === comment.extendedRange[0]) {
14949 if (!node.trailingComments) {
14950 node.trailingComments = [];
14951 }
14952 node.trailingComments.push(comment);
14953 comments.splice(cursor, 1);
14954 } else {
14955 cursor += 1;
14956 }
14957 }
14958
14959 // already out of owned node
14960 if (cursor === comments.length) {
14961 return VisitorOption.Break;
14962 }
14963
14964 if (comments[cursor].extendedRange[0] > node.range[1]) {
14965 return VisitorOption.Skip;
14966 }
14967 }
14968 });
14969
14970 return tree;
14971 }
14972
14973 exports.version = _dereq_('./package.json').version;
14974 exports.Syntax = Syntax;
14975 exports.traverse = traverse;
14976 exports.replace = replace;
14977 exports.attachComments = attachComments;
14978 exports.VisitorKeys = VisitorKeys;
14979 exports.VisitorOption = VisitorOption;
14980 exports.Controller = Controller;
14981 exports.cloneEnvironment = function () { return clone({}); };
14982
14983 return exports;
14984}(exports));
14985/* vim: set sw=4 ts=4 et tw=80 : */
14986
14987},{"./package.json":92}],92:[function(_dereq_,module,exports){
14988module.exports={"version":"4.2.0"}
14989},{}],93:[function(_dereq_,module,exports){
14990/*
14991 Copyright (C) 2013 Yusuke Suzuki <utatane.tea@gmail.com>
14992
14993 Redistribution and use in source and binary forms, with or without
14994 modification, are permitted provided that the following conditions are met:
14995
14996 * Redistributions of source code must retain the above copyright
14997 notice, this list of conditions and the following disclaimer.
14998 * Redistributions in binary form must reproduce the above copyright
14999 notice, this list of conditions and the following disclaimer in the
15000 documentation and/or other materials provided with the distribution.
15001
15002 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 'AS IS'
15003 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
15004 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
15005 ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
15006 DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
15007 (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
15008 LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
15009 ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
15010 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
15011 THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
15012*/
15013
15014(function () {
15015 'use strict';
15016
15017 function isExpression(node) {
15018 if (node == null) { return false; }
15019 switch (node.type) {
15020 case 'ArrayExpression':
15021 case 'AssignmentExpression':
15022 case 'BinaryExpression':
15023 case 'CallExpression':
15024 case 'ConditionalExpression':
15025 case 'FunctionExpression':
15026 case 'Identifier':
15027 case 'Literal':
15028 case 'LogicalExpression':
15029 case 'MemberExpression':
15030 case 'NewExpression':
15031 case 'ObjectExpression':
15032 case 'SequenceExpression':
15033 case 'ThisExpression':
15034 case 'UnaryExpression':
15035 case 'UpdateExpression':
15036 return true;
15037 }
15038 return false;
15039 }
15040
15041 function isIterationStatement(node) {
15042 if (node == null) { return false; }
15043 switch (node.type) {
15044 case 'DoWhileStatement':
15045 case 'ForInStatement':
15046 case 'ForStatement':
15047 case 'WhileStatement':
15048 return true;
15049 }
15050 return false;
15051 }
15052
15053 function isStatement(node) {
15054 if (node == null) { return false; }
15055 switch (node.type) {
15056 case 'BlockStatement':
15057 case 'BreakStatement':
15058 case 'ContinueStatement':
15059 case 'DebuggerStatement':
15060 case 'DoWhileStatement':
15061 case 'EmptyStatement':
15062 case 'ExpressionStatement':
15063 case 'ForInStatement':
15064 case 'ForStatement':
15065 case 'IfStatement':
15066 case 'LabeledStatement':
15067 case 'ReturnStatement':
15068 case 'SwitchStatement':
15069 case 'ThrowStatement':
15070 case 'TryStatement':
15071 case 'VariableDeclaration':
15072 case 'WhileStatement':
15073 case 'WithStatement':
15074 return true;
15075 }
15076 return false;
15077 }
15078
15079 function isSourceElement(node) {
15080 return isStatement(node) || node != null && node.type === 'FunctionDeclaration';
15081 }
15082
15083 function trailingStatement(node) {
15084 switch (node.type) {
15085 case 'IfStatement':
15086 if (node.alternate != null) {
15087 return node.alternate;
15088 }
15089 return node.consequent;
15090
15091 case 'LabeledStatement':
15092 case 'ForStatement':
15093 case 'ForInStatement':
15094 case 'WhileStatement':
15095 case 'WithStatement':
15096 return node.body;
15097 }
15098 return null;
15099 }
15100
15101 function isProblematicIfStatement(node) {
15102 var current;
15103
15104 if (node.type !== 'IfStatement') {
15105 return false;
15106 }
15107 if (node.alternate == null) {
15108 return false;
15109 }
15110 current = node.consequent;
15111 do {
15112 if (current.type === 'IfStatement') {
15113 if (current.alternate == null) {
15114 return true;
15115 }
15116 }
15117 current = trailingStatement(current);
15118 } while (current);
15119
15120 return false;
15121 }
15122
15123 module.exports = {
15124 isExpression: isExpression,
15125 isStatement: isStatement,
15126 isIterationStatement: isIterationStatement,
15127 isSourceElement: isSourceElement,
15128 isProblematicIfStatement: isProblematicIfStatement,
15129
15130 trailingStatement: trailingStatement
15131 };
15132}());
15133/* vim: set sw=4 ts=4 et tw=80 : */
15134
15135},{}],94:[function(_dereq_,module,exports){
15136/*
15137 Copyright (C) 2013-2014 Yusuke Suzuki <utatane.tea@gmail.com>
15138 Copyright (C) 2014 Ivan Nikulin <ifaaan@gmail.com>
15139
15140 Redistribution and use in source and binary forms, with or without
15141 modification, are permitted provided that the following conditions are met:
15142
15143 * Redistributions of source code must retain the above copyright
15144 notice, this list of conditions and the following disclaimer.
15145 * Redistributions in binary form must reproduce the above copyright
15146 notice, this list of conditions and the following disclaimer in the
15147 documentation and/or other materials provided with the distribution.
15148
15149 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
15150 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
15151 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
15152 ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
15153 DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
15154 (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
15155 LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
15156 ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
15157 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
15158 THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
15159*/
15160
15161(function () {
15162 'use strict';
15163
15164 var ES6Regex, ES5Regex, NON_ASCII_WHITESPACES, IDENTIFIER_START, IDENTIFIER_PART, ch;
15165
15166 // See `tools/generate-identifier-regex.js`.
15167 ES5Regex = {
15168 // ECMAScript 5.1/Unicode v7.0.0 NonAsciiIdentifierStart:
15169 NonAsciiIdentifierStart: /[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\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-\u08B2\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\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-\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-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\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-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA78E\uA790-\uA7AD\uA7B0\uA7B1\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB5F\uAB64\uAB65\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]/,
15170 // ECMAScript 5.1/Unicode v7.0.0 NonAsciiIdentifierPart:
15171 NonAsciiIdentifierPart: /[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\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-\u08B2\u08E4-\u0963\u0966-\u096F\u0971-\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\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58\u0C59\u0C60-\u0C63\u0C66-\u0C6F\u0C81-\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\u0D01-\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\u0DE6-\u0DEF\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-\u16F8\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-\u191E\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\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1CD0-\u1CD2\u1CD4-\u1CF6\u1CF8\u1CF9\u1D00-\u1DF5\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-\uA69D\uA69F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA78E\uA790-\uA7AD\uA7B0\uA7B1\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C4\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB5F\uAB64\uAB65\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-\uFE2D\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]/
15172 };
15173
15174 ES6Regex = {
15175 // ECMAScript 6/Unicode v7.0.0 NonAsciiIdentifierStart:
15176 NonAsciiIdentifierStart: /[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\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-\u08B2\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\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-\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-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\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\u2118-\u211D\u2124\u2126\u2128\u212A-\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\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309B-\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-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA78E\uA790-\uA7AD\uA7B0\uA7B1\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB5F\uAB64\uAB65\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]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDE80-\uDE9C\uDEA0-\uDED0\uDF00-\uDF1F\uDF30-\uDF4A\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00\uDE10-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE4\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48]|\uD804[\uDC03-\uDC37\uDC83-\uDCAF\uDCD0-\uDCE8\uDD03-\uDD26\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDDA\uDE00-\uDE11\uDE13-\uDE2B\uDEB0-\uDEDE\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF5D-\uDF61]|\uD805[\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDE00-\uDE2F\uDE44\uDE80-\uDEAA]|\uD806[\uDCA0-\uDCDF\uDCFF\uDEC0-\uDEF8]|\uD808[\uDC00-\uDF98]|\uD809[\uDC00-\uDC6E]|[\uD80C\uD840-\uD868\uD86A-\uD86C][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50\uDF93-\uDF9F]|\uD82C[\uDC00\uDC01]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB]|\uD83A[\uDC00-\uDCC4]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D]|\uD87E[\uDC00-\uDE1D]/,
15177 // ECMAScript 6/Unicode v7.0.0 NonAsciiIdentifierPart:
15178 NonAsciiIdentifierPart: /[\xAA\xB5\xB7\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\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-\u08B2\u08E4-\u0963\u0966-\u096F\u0971-\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\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58\u0C59\u0C60-\u0C63\u0C66-\u0C6F\u0C81-\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\u0D01-\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\u0DE6-\u0DEF\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\u1369-\u1371\u1380-\u138F\u13A0-\u13F4\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\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-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19DA\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1CD0-\u1CD2\u1CD4-\u1CF6\u1CF8\u1CF9\u1D00-\u1DF5\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\u2118-\u211D\u2124\u2126\u2128\u212A-\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\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099-\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-\uA69D\uA69F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA78E\uA790-\uA7AD\uA7B0\uA7B1\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C4\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB5F\uAB64\uAB65\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-\uFE2D\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]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDDFD\uDE80-\uDE9C\uDEA0-\uDED0\uDEE0\uDF00-\uDF1F\uDF30-\uDF4A\uDF50-\uDF7A\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCA0-\uDCA9\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00-\uDE03\uDE05\uDE06\uDE0C-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE38-\uDE3A\uDE3F\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE6\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48]|\uD804[\uDC00-\uDC46\uDC66-\uDC6F\uDC7F-\uDCBA\uDCD0-\uDCE8\uDCF0-\uDCF9\uDD00-\uDD34\uDD36-\uDD3F\uDD50-\uDD73\uDD76\uDD80-\uDDC4\uDDD0-\uDDDA\uDE00-\uDE11\uDE13-\uDE37\uDEB0-\uDEEA\uDEF0-\uDEF9\uDF01-\uDF03\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3C-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF57\uDF5D-\uDF63\uDF66-\uDF6C\uDF70-\uDF74]|\uD805[\uDC80-\uDCC5\uDCC7\uDCD0-\uDCD9\uDD80-\uDDB5\uDDB8-\uDDC0\uDE00-\uDE40\uDE44\uDE50-\uDE59\uDE80-\uDEB7\uDEC0-\uDEC9]|\uD806[\uDCA0-\uDCE9\uDCFF\uDEC0-\uDEF8]|\uD808[\uDC00-\uDF98]|\uD809[\uDC00-\uDC6E]|[\uD80C\uD840-\uD868\uD86A-\uD86C][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDE60-\uDE69\uDED0-\uDEED\uDEF0-\uDEF4\uDF00-\uDF36\uDF40-\uDF43\uDF50-\uDF59\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50-\uDF7E\uDF8F-\uDF9F]|\uD82C[\uDC00\uDC01]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99\uDC9D\uDC9E]|\uD834[\uDD65-\uDD69\uDD6D-\uDD72\uDD7B-\uDD82\uDD85-\uDD8B\uDDAA-\uDDAD\uDE42-\uDE44]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB\uDFCE-\uDFFF]|\uD83A[\uDC00-\uDCC4\uDCD0-\uDCD6]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D]|\uD87E[\uDC00-\uDE1D]|\uDB40[\uDD00-\uDDEF]/
15179 };
15180
15181 function isDecimalDigit(ch) {
15182 return 0x30 <= ch && ch <= 0x39; // 0..9
15183 }
15184
15185 function isHexDigit(ch) {
15186 return 0x30 <= ch && ch <= 0x39 || // 0..9
15187 0x61 <= ch && ch <= 0x66 || // a..f
15188 0x41 <= ch && ch <= 0x46; // A..F
15189 }
15190
15191 function isOctalDigit(ch) {
15192 return ch >= 0x30 && ch <= 0x37; // 0..7
15193 }
15194
15195 // 7.2 White Space
15196
15197 NON_ASCII_WHITESPACES = [
15198 0x1680, 0x180E,
15199 0x2000, 0x2001, 0x2002, 0x2003, 0x2004, 0x2005, 0x2006, 0x2007, 0x2008, 0x2009, 0x200A,
15200 0x202F, 0x205F,
15201 0x3000,
15202 0xFEFF
15203 ];
15204
15205 function isWhiteSpace(ch) {
15206 return ch === 0x20 || ch === 0x09 || ch === 0x0B || ch === 0x0C || ch === 0xA0 ||
15207 ch >= 0x1680 && NON_ASCII_WHITESPACES.indexOf(ch) >= 0;
15208 }
15209
15210 // 7.3 Line Terminators
15211
15212 function isLineTerminator(ch) {
15213 return ch === 0x0A || ch === 0x0D || ch === 0x2028 || ch === 0x2029;
15214 }
15215
15216 // 7.6 Identifier Names and Identifiers
15217
15218 function fromCodePoint(cp) {
15219 if (cp <= 0xFFFF) { return String.fromCharCode(cp); }
15220 var cu1 = String.fromCharCode(Math.floor((cp - 0x10000) / 0x400) + 0xD800);
15221 var cu2 = String.fromCharCode(((cp - 0x10000) % 0x400) + 0xDC00);
15222 return cu1 + cu2;
15223 }
15224
15225 IDENTIFIER_START = new Array(0x80);
15226 for(ch = 0; ch < 0x80; ++ch) {
15227 IDENTIFIER_START[ch] =
15228 ch >= 0x61 && ch <= 0x7A || // a..z
15229 ch >= 0x41 && ch <= 0x5A || // A..Z
15230 ch === 0x24 || ch === 0x5F; // $ (dollar) and _ (underscore)
15231 }
15232
15233 IDENTIFIER_PART = new Array(0x80);
15234 for(ch = 0; ch < 0x80; ++ch) {
15235 IDENTIFIER_PART[ch] =
15236 ch >= 0x61 && ch <= 0x7A || // a..z
15237 ch >= 0x41 && ch <= 0x5A || // A..Z
15238 ch >= 0x30 && ch <= 0x39 || // 0..9
15239 ch === 0x24 || ch === 0x5F; // $ (dollar) and _ (underscore)
15240 }
15241
15242 function isIdentifierStartES5(ch) {
15243 return ch < 0x80 ? IDENTIFIER_START[ch] : ES5Regex.NonAsciiIdentifierStart.test(fromCodePoint(ch));
15244 }
15245
15246 function isIdentifierPartES5(ch) {
15247 return ch < 0x80 ? IDENTIFIER_PART[ch] : ES5Regex.NonAsciiIdentifierPart.test(fromCodePoint(ch));
15248 }
15249
15250 function isIdentifierStartES6(ch) {
15251 return ch < 0x80 ? IDENTIFIER_START[ch] : ES6Regex.NonAsciiIdentifierStart.test(fromCodePoint(ch));
15252 }
15253
15254 function isIdentifierPartES6(ch) {
15255 return ch < 0x80 ? IDENTIFIER_PART[ch] : ES6Regex.NonAsciiIdentifierPart.test(fromCodePoint(ch));
15256 }
15257
15258 module.exports = {
15259 isDecimalDigit: isDecimalDigit,
15260 isHexDigit: isHexDigit,
15261 isOctalDigit: isOctalDigit,
15262 isWhiteSpace: isWhiteSpace,
15263 isLineTerminator: isLineTerminator,
15264 isIdentifierStartES5: isIdentifierStartES5,
15265 isIdentifierPartES5: isIdentifierPartES5,
15266 isIdentifierStartES6: isIdentifierStartES6,
15267 isIdentifierPartES6: isIdentifierPartES6
15268 };
15269}());
15270/* vim: set sw=4 ts=4 et tw=80 : */
15271
15272},{}],95:[function(_dereq_,module,exports){
15273/*
15274 Copyright (C) 2013 Yusuke Suzuki <utatane.tea@gmail.com>
15275
15276 Redistribution and use in source and binary forms, with or without
15277 modification, are permitted provided that the following conditions are met:
15278
15279 * Redistributions of source code must retain the above copyright
15280 notice, this list of conditions and the following disclaimer.
15281 * Redistributions in binary form must reproduce the above copyright
15282 notice, this list of conditions and the following disclaimer in the
15283 documentation and/or other materials provided with the distribution.
15284
15285 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
15286 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
15287 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
15288 ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
15289 DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
15290 (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
15291 LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
15292 ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
15293 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
15294 THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
15295*/
15296
15297(function () {
15298 'use strict';
15299
15300 var code = _dereq_('./code');
15301
15302 function isStrictModeReservedWordES6(id) {
15303 switch (id) {
15304 case 'implements':
15305 case 'interface':
15306 case 'package':
15307 case 'private':
15308 case 'protected':
15309 case 'public':
15310 case 'static':
15311 case 'let':
15312 return true;
15313 default:
15314 return false;
15315 }
15316 }
15317
15318 function isKeywordES5(id, strict) {
15319 // yield should not be treated as keyword under non-strict mode.
15320 if (!strict && id === 'yield') {
15321 return false;
15322 }
15323 return isKeywordES6(id, strict);
15324 }
15325
15326 function isKeywordES6(id, strict) {
15327 if (strict && isStrictModeReservedWordES6(id)) {
15328 return true;
15329 }
15330
15331 switch (id.length) {
15332 case 2:
15333 return (id === 'if') || (id === 'in') || (id === 'do');
15334 case 3:
15335 return (id === 'var') || (id === 'for') || (id === 'new') || (id === 'try');
15336 case 4:
15337 return (id === 'this') || (id === 'else') || (id === 'case') ||
15338 (id === 'void') || (id === 'with') || (id === 'enum');
15339 case 5:
15340 return (id === 'while') || (id === 'break') || (id === 'catch') ||
15341 (id === 'throw') || (id === 'const') || (id === 'yield') ||
15342 (id === 'class') || (id === 'super');
15343 case 6:
15344 return (id === 'return') || (id === 'typeof') || (id === 'delete') ||
15345 (id === 'switch') || (id === 'export') || (id === 'import');
15346 case 7:
15347 return (id === 'default') || (id === 'finally') || (id === 'extends');
15348 case 8:
15349 return (id === 'function') || (id === 'continue') || (id === 'debugger');
15350 case 10:
15351 return (id === 'instanceof');
15352 default:
15353 return false;
15354 }
15355 }
15356
15357 function isReservedWordES5(id, strict) {
15358 return id === 'null' || id === 'true' || id === 'false' || isKeywordES5(id, strict);
15359 }
15360
15361 function isReservedWordES6(id, strict) {
15362 return id === 'null' || id === 'true' || id === 'false' || isKeywordES6(id, strict);
15363 }
15364
15365 function isRestrictedWord(id) {
15366 return id === 'eval' || id === 'arguments';
15367 }
15368
15369 function isIdentifierNameES5(id) {
15370 var i, iz, ch;
15371
15372 if (id.length === 0) { return false; }
15373
15374 ch = id.charCodeAt(0);
15375 if (!code.isIdentifierStartES5(ch)) {
15376 return false;
15377 }
15378
15379 for (i = 1, iz = id.length; i < iz; ++i) {
15380 ch = id.charCodeAt(i);
15381 if (!code.isIdentifierPartES5(ch)) {
15382 return false;
15383 }
15384 }
15385 return true;
15386 }
15387
15388 function decodeUtf16(lead, trail) {
15389 return (lead - 0xD800) * 0x400 + (trail - 0xDC00) + 0x10000;
15390 }
15391
15392 function isIdentifierNameES6(id) {
15393 var i, iz, ch, lowCh, check;
15394
15395 if (id.length === 0) { return false; }
15396
15397 check = code.isIdentifierStartES6;
15398 for (i = 0, iz = id.length; i < iz; ++i) {
15399 ch = id.charCodeAt(i);
15400 if (0xD800 <= ch && ch <= 0xDBFF) {
15401 ++i;
15402 if (i >= iz) { return false; }
15403 lowCh = id.charCodeAt(i);
15404 if (!(0xDC00 <= lowCh && lowCh <= 0xDFFF)) {
15405 return false;
15406 }
15407 ch = decodeUtf16(ch, lowCh);
15408 }
15409 if (!check(ch)) {
15410 return false;
15411 }
15412 check = code.isIdentifierPartES6;
15413 }
15414 return true;
15415 }
15416
15417 function isIdentifierES5(id, strict) {
15418 return isIdentifierNameES5(id) && !isReservedWordES5(id, strict);
15419 }
15420
15421 function isIdentifierES6(id, strict) {
15422 return isIdentifierNameES6(id) && !isReservedWordES6(id, strict);
15423 }
15424
15425 module.exports = {
15426 isKeywordES5: isKeywordES5,
15427 isKeywordES6: isKeywordES6,
15428 isReservedWordES5: isReservedWordES5,
15429 isReservedWordES6: isReservedWordES6,
15430 isRestrictedWord: isRestrictedWord,
15431 isIdentifierNameES5: isIdentifierNameES5,
15432 isIdentifierNameES6: isIdentifierNameES6,
15433 isIdentifierES5: isIdentifierES5,
15434 isIdentifierES6: isIdentifierES6
15435 };
15436}());
15437/* vim: set sw=4 ts=4 et tw=80 : */
15438
15439},{"./code":94}],96:[function(_dereq_,module,exports){
15440/*
15441 Copyright (C) 2013 Yusuke Suzuki <utatane.tea@gmail.com>
15442
15443 Redistribution and use in source and binary forms, with or without
15444 modification, are permitted provided that the following conditions are met:
15445
15446 * Redistributions of source code must retain the above copyright
15447 notice, this list of conditions and the following disclaimer.
15448 * Redistributions in binary form must reproduce the above copyright
15449 notice, this list of conditions and the following disclaimer in the
15450 documentation and/or other materials provided with the distribution.
15451
15452 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
15453 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
15454 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
15455 ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
15456 DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
15457 (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
15458 LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
15459 ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
15460 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
15461 THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
15462*/
15463
15464
15465(function () {
15466 'use strict';
15467
15468 exports.ast = _dereq_('./ast');
15469 exports.code = _dereq_('./code');
15470 exports.keyword = _dereq_('./keyword');
15471}());
15472/* vim: set sw=4 ts=4 et tw=80 : */
15473
15474},{"./ast":93,"./code":94,"./keyword":95}],97:[function(_dereq_,module,exports){
15475
15476var indexOf = [].indexOf;
15477
15478module.exports = function(arr, obj){
15479 if (indexOf) return arr.indexOf(obj);
15480 for (var i = 0; i < arr.length; ++i) {
15481 if (arr[i] === obj) return i;
15482 }
15483 return -1;
15484};
15485},{}],98:[function(_dereq_,module,exports){
15486
15487/**
15488 * Expose `isUrl`.
15489 */
15490
15491module.exports = isUrl;
15492
15493/**
15494 * Matcher.
15495 */
15496
15497var matcher = /^(?:\w+:)?\/\/([^\s\.]+\.\S{2}|localhost[\:?\d]*)\S*$/;
15498
15499/**
15500 * Loosely validate a URL `string`.
15501 *
15502 * @param {String} string
15503 * @return {Boolean}
15504 */
15505
15506function isUrl(string){
15507 return matcher.test(string);
15508}
15509
15510},{}],99:[function(_dereq_,module,exports){
15511var toString = {}.toString;
15512
15513module.exports = Array.isArray || function (arr) {
15514 return toString.call(arr) == '[object Array]';
15515};
15516
15517},{}],100:[function(_dereq_,module,exports){
15518(function (process){
15519// Copyright Joyent, Inc. and other Node contributors.
15520//
15521// Permission is hereby granted, free of charge, to any person obtaining a
15522// copy of this software and associated documentation files (the
15523// "Software"), to deal in the Software without restriction, including
15524// without limitation the rights to use, copy, modify, merge, publish,
15525// distribute, sublicense, and/or sell copies of the Software, and to permit
15526// persons to whom the Software is furnished to do so, subject to the
15527// following conditions:
15528//
15529// The above copyright notice and this permission notice shall be included
15530// in all copies or substantial portions of the Software.
15531//
15532// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
15533// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
15534// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
15535// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
15536// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
15537// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
15538// USE OR OTHER DEALINGS IN THE SOFTWARE.
15539
15540// resolves . and .. elements in a path array with directory names there
15541// must be no slashes, empty elements, or device names (c:\) in the array
15542// (so also no leading and trailing slashes - it does not distinguish
15543// relative and absolute paths)
15544function normalizeArray(parts, allowAboveRoot) {
15545 // if the path tries to go above the root, `up` ends up > 0
15546 var up = 0;
15547 for (var i = parts.length - 1; i >= 0; i--) {
15548 var last = parts[i];
15549 if (last === '.') {
15550 parts.splice(i, 1);
15551 } else if (last === '..') {
15552 parts.splice(i, 1);
15553 up++;
15554 } else if (up) {
15555 parts.splice(i, 1);
15556 up--;
15557 }
15558 }
15559
15560 // if the path is allowed to go above the root, restore leading ..s
15561 if (allowAboveRoot) {
15562 for (; up--; up) {
15563 parts.unshift('..');
15564 }
15565 }
15566
15567 return parts;
15568}
15569
15570// Split a filename into [root, dir, basename, ext], unix version
15571// 'root' is just a slash, or nothing.
15572var splitPathRe =
15573 /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;
15574var splitPath = function(filename) {
15575 return splitPathRe.exec(filename).slice(1);
15576};
15577
15578// path.resolve([from ...], to)
15579// posix version
15580exports.resolve = function() {
15581 var resolvedPath = '',
15582 resolvedAbsolute = false;
15583
15584 for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) {
15585 var path = (i >= 0) ? arguments[i] : process.cwd();
15586
15587 // Skip empty and invalid entries
15588 if (typeof path !== 'string') {
15589 throw new TypeError('Arguments to path.resolve must be strings');
15590 } else if (!path) {
15591 continue;
15592 }
15593
15594 resolvedPath = path + '/' + resolvedPath;
15595 resolvedAbsolute = path.charAt(0) === '/';
15596 }
15597
15598 // At this point the path should be resolved to a full absolute path, but
15599 // handle relative paths to be safe (might happen when process.cwd() fails)
15600
15601 // Normalize the path
15602 resolvedPath = normalizeArray(filter(resolvedPath.split('/'), function(p) {
15603 return !!p;
15604 }), !resolvedAbsolute).join('/');
15605
15606 return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.';
15607};
15608
15609// path.normalize(path)
15610// posix version
15611exports.normalize = function(path) {
15612 var isAbsolute = exports.isAbsolute(path),
15613 trailingSlash = substr(path, -1) === '/';
15614
15615 // Normalize the path
15616 path = normalizeArray(filter(path.split('/'), function(p) {
15617 return !!p;
15618 }), !isAbsolute).join('/');
15619
15620 if (!path && !isAbsolute) {
15621 path = '.';
15622 }
15623 if (path && trailingSlash) {
15624 path += '/';
15625 }
15626
15627 return (isAbsolute ? '/' : '') + path;
15628};
15629
15630// posix version
15631exports.isAbsolute = function(path) {
15632 return path.charAt(0) === '/';
15633};
15634
15635// posix version
15636exports.join = function() {
15637 var paths = Array.prototype.slice.call(arguments, 0);
15638 return exports.normalize(filter(paths, function(p, index) {
15639 if (typeof p !== 'string') {
15640 throw new TypeError('Arguments to path.join must be strings');
15641 }
15642 return p;
15643 }).join('/'));
15644};
15645
15646
15647// path.relative(from, to)
15648// posix version
15649exports.relative = function(from, to) {
15650 from = exports.resolve(from).substr(1);
15651 to = exports.resolve(to).substr(1);
15652
15653 function trim(arr) {
15654 var start = 0;
15655 for (; start < arr.length; start++) {
15656 if (arr[start] !== '') break;
15657 }
15658
15659 var end = arr.length - 1;
15660 for (; end >= 0; end--) {
15661 if (arr[end] !== '') break;
15662 }
15663
15664 if (start > end) return [];
15665 return arr.slice(start, end - start + 1);
15666 }
15667
15668 var fromParts = trim(from.split('/'));
15669 var toParts = trim(to.split('/'));
15670
15671 var length = Math.min(fromParts.length, toParts.length);
15672 var samePartsLength = length;
15673 for (var i = 0; i < length; i++) {
15674 if (fromParts[i] !== toParts[i]) {
15675 samePartsLength = i;
15676 break;
15677 }
15678 }
15679
15680 var outputParts = [];
15681 for (var i = samePartsLength; i < fromParts.length; i++) {
15682 outputParts.push('..');
15683 }
15684
15685 outputParts = outputParts.concat(toParts.slice(samePartsLength));
15686
15687 return outputParts.join('/');
15688};
15689
15690exports.sep = '/';
15691exports.delimiter = ':';
15692
15693exports.dirname = function(path) {
15694 var result = splitPath(path),
15695 root = result[0],
15696 dir = result[1];
15697
15698 if (!root && !dir) {
15699 // No dirname whatsoever
15700 return '.';
15701 }
15702
15703 if (dir) {
15704 // It has a dirname, strip trailing slash
15705 dir = dir.substr(0, dir.length - 1);
15706 }
15707
15708 return root + dir;
15709};
15710
15711
15712exports.basename = function(path, ext) {
15713 var f = splitPath(path)[2];
15714 // TODO: make this comparison case-insensitive on windows?
15715 if (ext && f.substr(-1 * ext.length) === ext) {
15716 f = f.substr(0, f.length - ext.length);
15717 }
15718 return f;
15719};
15720
15721
15722exports.extname = function(path) {
15723 return splitPath(path)[3];
15724};
15725
15726function filter (xs, f) {
15727 if (xs.filter) return xs.filter(f);
15728 var res = [];
15729 for (var i = 0; i < xs.length; i++) {
15730 if (f(xs[i], i, xs)) res.push(xs[i]);
15731 }
15732 return res;
15733}
15734
15735// String.prototype.substr - negative index don't work in IE8
15736var substr = 'ab'.substr(-1) === 'b'
15737 ? function (str, start, len) { return str.substr(start, len) }
15738 : function (str, start, len) {
15739 if (start < 0) start = str.length + start;
15740 return str.substr(start, len);
15741 }
15742;
15743
15744}).call(this,_dereq_('_process'))
15745},{"_process":102}],101:[function(_dereq_,module,exports){
15746(function (process){
15747'use strict';
15748
15749function posix(path) {
15750 return path.charAt(0) === '/';
15751};
15752
15753function win32(path) {
15754 // https://github.com/joyent/node/blob/b3fcc245fb25539909ef1d5eaa01dbf92e168633/lib/path.js#L56
15755 var splitDeviceRe = /^([a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/]+[^\\\/]+)?([\\\/])?([\s\S]*?)$/;
15756 var result = splitDeviceRe.exec(path);
15757 var device = result[1] || '';
15758 var isUnc = !!device && device.charAt(1) !== ':';
15759
15760 // UNC paths are always absolute
15761 return !!result[2] || isUnc;
15762};
15763
15764module.exports = process.platform === 'win32' ? win32 : posix;
15765module.exports.posix = posix;
15766module.exports.win32 = win32;
15767
15768}).call(this,_dereq_('_process'))
15769},{"_process":102}],102:[function(_dereq_,module,exports){
15770// shim for using process in browser
15771
15772var process = module.exports = {};
15773
15774// cached from whatever global is present so that test runners that stub it
15775// don't break things. But we need to wrap it in a try catch in case it is
15776// wrapped in strict mode code which doesn't define any globals. It's inside a
15777// function because try/catches deoptimize in certain engines.
15778
15779var cachedSetTimeout;
15780var cachedClearTimeout;
15781
15782(function () {
15783 try {
15784 cachedSetTimeout = setTimeout;
15785 } catch (e) {
15786 cachedSetTimeout = function () {
15787 throw new Error('setTimeout is not defined');
15788 }
15789 }
15790 try {
15791 cachedClearTimeout = clearTimeout;
15792 } catch (e) {
15793 cachedClearTimeout = function () {
15794 throw new Error('clearTimeout is not defined');
15795 }
15796 }
15797} ())
15798var queue = [];
15799var draining = false;
15800var currentQueue;
15801var queueIndex = -1;
15802
15803function cleanUpNextTick() {
15804 if (!draining || !currentQueue) {
15805 return;
15806 }
15807 draining = false;
15808 if (currentQueue.length) {
15809 queue = currentQueue.concat(queue);
15810 } else {
15811 queueIndex = -1;
15812 }
15813 if (queue.length) {
15814 drainQueue();
15815 }
15816}
15817
15818function drainQueue() {
15819 if (draining) {
15820 return;
15821 }
15822 var timeout = cachedSetTimeout(cleanUpNextTick);
15823 draining = true;
15824
15825 var len = queue.length;
15826 while(len) {
15827 currentQueue = queue;
15828 queue = [];
15829 while (++queueIndex < len) {
15830 if (currentQueue) {
15831 currentQueue[queueIndex].run();
15832 }
15833 }
15834 queueIndex = -1;
15835 len = queue.length;
15836 }
15837 currentQueue = null;
15838 draining = false;
15839 cachedClearTimeout(timeout);
15840}
15841
15842process.nextTick = function (fun) {
15843 var args = new Array(arguments.length - 1);
15844 if (arguments.length > 1) {
15845 for (var i = 1; i < arguments.length; i++) {
15846 args[i - 1] = arguments[i];
15847 }
15848 }
15849 queue.push(new Item(fun, args));
15850 if (queue.length === 1 && !draining) {
15851 cachedSetTimeout(drainQueue, 0);
15852 }
15853};
15854
15855// v8 likes predictible objects
15856function Item(fun, array) {
15857 this.fun = fun;
15858 this.array = array;
15859}
15860Item.prototype.run = function () {
15861 this.fun.apply(null, this.array);
15862};
15863process.title = 'browser';
15864process.browser = true;
15865process.env = {};
15866process.argv = [];
15867process.version = ''; // empty string to avoid regexp issues
15868process.versions = {};
15869
15870function noop() {}
15871
15872process.on = noop;
15873process.addListener = noop;
15874process.once = noop;
15875process.off = noop;
15876process.removeListener = noop;
15877process.removeAllListeners = noop;
15878process.emit = noop;
15879
15880process.binding = function (name) {
15881 throw new Error('process.binding is not supported');
15882};
15883
15884process.cwd = function () { return '/' };
15885process.chdir = function (dir) {
15886 throw new Error('process.chdir is not supported');
15887};
15888process.umask = function() { return 0; };
15889
15890},{}],103:[function(_dereq_,module,exports){
15891/* -*- Mode: js; js-indent-level: 2; -*- */
15892/*
15893 * Copyright 2011 Mozilla Foundation and contributors
15894 * Licensed under the New BSD license. See LICENSE or:
15895 * http://opensource.org/licenses/BSD-3-Clause
15896 */
15897
15898var util = _dereq_('./util');
15899var has = Object.prototype.hasOwnProperty;
15900
15901/**
15902 * A data structure which is a combination of an array and a set. Adding a new
15903 * member is O(1), testing for membership is O(1), and finding the index of an
15904 * element is O(1). Removing elements from the set is not supported. Only
15905 * strings are supported for membership.
15906 */
15907function ArraySet() {
15908 this._array = [];
15909 this._set = Object.create(null);
15910}
15911
15912/**
15913 * Static method for creating ArraySet instances from an existing array.
15914 */
15915ArraySet.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) {
15916 var set = new ArraySet();
15917 for (var i = 0, len = aArray.length; i < len; i++) {
15918 set.add(aArray[i], aAllowDuplicates);
15919 }
15920 return set;
15921};
15922
15923/**
15924 * Return how many unique items are in this ArraySet. If duplicates have been
15925 * added, than those do not count towards the size.
15926 *
15927 * @returns Number
15928 */
15929ArraySet.prototype.size = function ArraySet_size() {
15930 return Object.getOwnPropertyNames(this._set).length;
15931};
15932
15933/**
15934 * Add the given string to this set.
15935 *
15936 * @param String aStr
15937 */
15938ArraySet.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) {
15939 var sStr = util.toSetString(aStr);
15940 var isDuplicate = has.call(this._set, sStr);
15941 var idx = this._array.length;
15942 if (!isDuplicate || aAllowDuplicates) {
15943 this._array.push(aStr);
15944 }
15945 if (!isDuplicate) {
15946 this._set[sStr] = idx;
15947 }
15948};
15949
15950/**
15951 * Is the given string a member of this set?
15952 *
15953 * @param String aStr
15954 */
15955ArraySet.prototype.has = function ArraySet_has(aStr) {
15956 var sStr = util.toSetString(aStr);
15957 return has.call(this._set, sStr);
15958};
15959
15960/**
15961 * What is the index of the given string in the array?
15962 *
15963 * @param String aStr
15964 */
15965ArraySet.prototype.indexOf = function ArraySet_indexOf(aStr) {
15966 var sStr = util.toSetString(aStr);
15967 if (has.call(this._set, sStr)) {
15968 return this._set[sStr];
15969 }
15970 throw new Error('"' + aStr + '" is not in the set.');
15971};
15972
15973/**
15974 * What is the element at the given index?
15975 *
15976 * @param Number aIdx
15977 */
15978ArraySet.prototype.at = function ArraySet_at(aIdx) {
15979 if (aIdx >= 0 && aIdx < this._array.length) {
15980 return this._array[aIdx];
15981 }
15982 throw new Error('No element indexed by ' + aIdx);
15983};
15984
15985/**
15986 * Returns the array representation of this set (which has the proper indices
15987 * indicated by indexOf). Note that this is a copy of the internal array used
15988 * for storing the members so that no one can mess with internal state.
15989 */
15990ArraySet.prototype.toArray = function ArraySet_toArray() {
15991 return this._array.slice();
15992};
15993
15994exports.ArraySet = ArraySet;
15995
15996},{"./util":112}],104:[function(_dereq_,module,exports){
15997/* -*- Mode: js; js-indent-level: 2; -*- */
15998/*
15999 * Copyright 2011 Mozilla Foundation and contributors
16000 * Licensed under the New BSD license. See LICENSE or:
16001 * http://opensource.org/licenses/BSD-3-Clause
16002 *
16003 * Based on the Base 64 VLQ implementation in Closure Compiler:
16004 * https://code.google.com/p/closure-compiler/source/browse/trunk/src/com/google/debugging/sourcemap/Base64VLQ.java
16005 *
16006 * Copyright 2011 The Closure Compiler Authors. All rights reserved.
16007 * Redistribution and use in source and binary forms, with or without
16008 * modification, are permitted provided that the following conditions are
16009 * met:
16010 *
16011 * * Redistributions of source code must retain the above copyright
16012 * notice, this list of conditions and the following disclaimer.
16013 * * Redistributions in binary form must reproduce the above
16014 * copyright notice, this list of conditions and the following
16015 * disclaimer in the documentation and/or other materials provided
16016 * with the distribution.
16017 * * Neither the name of Google Inc. nor the names of its
16018 * contributors may be used to endorse or promote products derived
16019 * from this software without specific prior written permission.
16020 *
16021 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
16022 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
16023 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
16024 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
16025 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
16026 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
16027 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
16028 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
16029 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
16030 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
16031 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
16032 */
16033
16034var base64 = _dereq_('./base64');
16035
16036// A single base 64 digit can contain 6 bits of data. For the base 64 variable
16037// length quantities we use in the source map spec, the first bit is the sign,
16038// the next four bits are the actual value, and the 6th bit is the
16039// continuation bit. The continuation bit tells us whether there are more
16040// digits in this value following this digit.
16041//
16042// Continuation
16043// | Sign
16044// | |
16045// V V
16046// 101011
16047
16048var VLQ_BASE_SHIFT = 5;
16049
16050// binary: 100000
16051var VLQ_BASE = 1 << VLQ_BASE_SHIFT;
16052
16053// binary: 011111
16054var VLQ_BASE_MASK = VLQ_BASE - 1;
16055
16056// binary: 100000
16057var VLQ_CONTINUATION_BIT = VLQ_BASE;
16058
16059/**
16060 * Converts from a two-complement value to a value where the sign bit is
16061 * placed in the least significant bit. For example, as decimals:
16062 * 1 becomes 2 (10 binary), -1 becomes 3 (11 binary)
16063 * 2 becomes 4 (100 binary), -2 becomes 5 (101 binary)
16064 */
16065function toVLQSigned(aValue) {
16066 return aValue < 0
16067 ? ((-aValue) << 1) + 1
16068 : (aValue << 1) + 0;
16069}
16070
16071/**
16072 * Converts to a two-complement value from a value where the sign bit is
16073 * placed in the least significant bit. For example, as decimals:
16074 * 2 (10 binary) becomes 1, 3 (11 binary) becomes -1
16075 * 4 (100 binary) becomes 2, 5 (101 binary) becomes -2
16076 */
16077function fromVLQSigned(aValue) {
16078 var isNegative = (aValue & 1) === 1;
16079 var shifted = aValue >> 1;
16080 return isNegative
16081 ? -shifted
16082 : shifted;
16083}
16084
16085/**
16086 * Returns the base 64 VLQ encoded value.
16087 */
16088exports.encode = function base64VLQ_encode(aValue) {
16089 var encoded = "";
16090 var digit;
16091
16092 var vlq = toVLQSigned(aValue);
16093
16094 do {
16095 digit = vlq & VLQ_BASE_MASK;
16096 vlq >>>= VLQ_BASE_SHIFT;
16097 if (vlq > 0) {
16098 // There are still more digits in this value, so we must make sure the
16099 // continuation bit is marked.
16100 digit |= VLQ_CONTINUATION_BIT;
16101 }
16102 encoded += base64.encode(digit);
16103 } while (vlq > 0);
16104
16105 return encoded;
16106};
16107
16108/**
16109 * Decodes the next base 64 VLQ value from the given string and returns the
16110 * value and the rest of the string via the out parameter.
16111 */
16112exports.decode = function base64VLQ_decode(aStr, aIndex, aOutParam) {
16113 var strLen = aStr.length;
16114 var result = 0;
16115 var shift = 0;
16116 var continuation, digit;
16117
16118 do {
16119 if (aIndex >= strLen) {
16120 throw new Error("Expected more digits in base 64 VLQ value.");
16121 }
16122
16123 digit = base64.decode(aStr.charCodeAt(aIndex++));
16124 if (digit === -1) {
16125 throw new Error("Invalid base64 digit: " + aStr.charAt(aIndex - 1));
16126 }
16127
16128 continuation = !!(digit & VLQ_CONTINUATION_BIT);
16129 digit &= VLQ_BASE_MASK;
16130 result = result + (digit << shift);
16131 shift += VLQ_BASE_SHIFT;
16132 } while (continuation);
16133
16134 aOutParam.value = fromVLQSigned(result);
16135 aOutParam.rest = aIndex;
16136};
16137
16138},{"./base64":105}],105:[function(_dereq_,module,exports){
16139/* -*- Mode: js; js-indent-level: 2; -*- */
16140/*
16141 * Copyright 2011 Mozilla Foundation and contributors
16142 * Licensed under the New BSD license. See LICENSE or:
16143 * http://opensource.org/licenses/BSD-3-Clause
16144 */
16145
16146var intToCharMap = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split('');
16147
16148/**
16149 * Encode an integer in the range of 0 to 63 to a single base 64 digit.
16150 */
16151exports.encode = function (number) {
16152 if (0 <= number && number < intToCharMap.length) {
16153 return intToCharMap[number];
16154 }
16155 throw new TypeError("Must be between 0 and 63: " + number);
16156};
16157
16158/**
16159 * Decode a single base 64 character code digit to an integer. Returns -1 on
16160 * failure.
16161 */
16162exports.decode = function (charCode) {
16163 var bigA = 65; // 'A'
16164 var bigZ = 90; // 'Z'
16165
16166 var littleA = 97; // 'a'
16167 var littleZ = 122; // 'z'
16168
16169 var zero = 48; // '0'
16170 var nine = 57; // '9'
16171
16172 var plus = 43; // '+'
16173 var slash = 47; // '/'
16174
16175 var littleOffset = 26;
16176 var numberOffset = 52;
16177
16178 // 0 - 25: ABCDEFGHIJKLMNOPQRSTUVWXYZ
16179 if (bigA <= charCode && charCode <= bigZ) {
16180 return (charCode - bigA);
16181 }
16182
16183 // 26 - 51: abcdefghijklmnopqrstuvwxyz
16184 if (littleA <= charCode && charCode <= littleZ) {
16185 return (charCode - littleA + littleOffset);
16186 }
16187
16188 // 52 - 61: 0123456789
16189 if (zero <= charCode && charCode <= nine) {
16190 return (charCode - zero + numberOffset);
16191 }
16192
16193 // 62: +
16194 if (charCode == plus) {
16195 return 62;
16196 }
16197
16198 // 63: /
16199 if (charCode == slash) {
16200 return 63;
16201 }
16202
16203 // Invalid base64 digit.
16204 return -1;
16205};
16206
16207},{}],106:[function(_dereq_,module,exports){
16208/* -*- Mode: js; js-indent-level: 2; -*- */
16209/*
16210 * Copyright 2011 Mozilla Foundation and contributors
16211 * Licensed under the New BSD license. See LICENSE or:
16212 * http://opensource.org/licenses/BSD-3-Clause
16213 */
16214
16215exports.GREATEST_LOWER_BOUND = 1;
16216exports.LEAST_UPPER_BOUND = 2;
16217
16218/**
16219 * Recursive implementation of binary search.
16220 *
16221 * @param aLow Indices here and lower do not contain the needle.
16222 * @param aHigh Indices here and higher do not contain the needle.
16223 * @param aNeedle The element being searched for.
16224 * @param aHaystack The non-empty array being searched.
16225 * @param aCompare Function which takes two elements and returns -1, 0, or 1.
16226 * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or
16227 * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the
16228 * closest element that is smaller than or greater than the one we are
16229 * searching for, respectively, if the exact element cannot be found.
16230 */
16231function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare, aBias) {
16232 // This function terminates when one of the following is true:
16233 //
16234 // 1. We find the exact element we are looking for.
16235 //
16236 // 2. We did not find the exact element, but we can return the index of
16237 // the next-closest element.
16238 //
16239 // 3. We did not find the exact element, and there is no next-closest
16240 // element than the one we are searching for, so we return -1.
16241 var mid = Math.floor((aHigh - aLow) / 2) + aLow;
16242 var cmp = aCompare(aNeedle, aHaystack[mid], true);
16243 if (cmp === 0) {
16244 // Found the element we are looking for.
16245 return mid;
16246 }
16247 else if (cmp > 0) {
16248 // Our needle is greater than aHaystack[mid].
16249 if (aHigh - mid > 1) {
16250 // The element is in the upper half.
16251 return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare, aBias);
16252 }
16253
16254 // The exact needle element was not found in this haystack. Determine if
16255 // we are in termination case (3) or (2) and return the appropriate thing.
16256 if (aBias == exports.LEAST_UPPER_BOUND) {
16257 return aHigh < aHaystack.length ? aHigh : -1;
16258 } else {
16259 return mid;
16260 }
16261 }
16262 else {
16263 // Our needle is less than aHaystack[mid].
16264 if (mid - aLow > 1) {
16265 // The element is in the lower half.
16266 return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare, aBias);
16267 }
16268
16269 // we are in termination case (3) or (2) and return the appropriate thing.
16270 if (aBias == exports.LEAST_UPPER_BOUND) {
16271 return mid;
16272 } else {
16273 return aLow < 0 ? -1 : aLow;
16274 }
16275 }
16276}
16277
16278/**
16279 * This is an implementation of binary search which will always try and return
16280 * the index of the closest element if there is no exact hit. This is because
16281 * mappings between original and generated line/col pairs are single points,
16282 * and there is an implicit region between each of them, so a miss just means
16283 * that you aren't on the very start of a region.
16284 *
16285 * @param aNeedle The element you are looking for.
16286 * @param aHaystack The array that is being searched.
16287 * @param aCompare A function which takes the needle and an element in the
16288 * array and returns -1, 0, or 1 depending on whether the needle is less
16289 * than, equal to, or greater than the element, respectively.
16290 * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or
16291 * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the
16292 * closest element that is smaller than or greater than the one we are
16293 * searching for, respectively, if the exact element cannot be found.
16294 * Defaults to 'binarySearch.GREATEST_LOWER_BOUND'.
16295 */
16296exports.search = function search(aNeedle, aHaystack, aCompare, aBias) {
16297 if (aHaystack.length === 0) {
16298 return -1;
16299 }
16300
16301 var index = recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack,
16302 aCompare, aBias || exports.GREATEST_LOWER_BOUND);
16303 if (index < 0) {
16304 return -1;
16305 }
16306
16307 // We have found either the exact element, or the next-closest element than
16308 // the one we are searching for. However, there may be more than one such
16309 // element. Make sure we always return the smallest of these.
16310 while (index - 1 >= 0) {
16311 if (aCompare(aHaystack[index], aHaystack[index - 1], true) !== 0) {
16312 break;
16313 }
16314 --index;
16315 }
16316
16317 return index;
16318};
16319
16320},{}],107:[function(_dereq_,module,exports){
16321/* -*- Mode: js; js-indent-level: 2; -*- */
16322/*
16323 * Copyright 2014 Mozilla Foundation and contributors
16324 * Licensed under the New BSD license. See LICENSE or:
16325 * http://opensource.org/licenses/BSD-3-Clause
16326 */
16327
16328var util = _dereq_('./util');
16329
16330/**
16331 * Determine whether mappingB is after mappingA with respect to generated
16332 * position.
16333 */
16334function generatedPositionAfter(mappingA, mappingB) {
16335 // Optimized for most common case
16336 var lineA = mappingA.generatedLine;
16337 var lineB = mappingB.generatedLine;
16338 var columnA = mappingA.generatedColumn;
16339 var columnB = mappingB.generatedColumn;
16340 return lineB > lineA || lineB == lineA && columnB >= columnA ||
16341 util.compareByGeneratedPositionsInflated(mappingA, mappingB) <= 0;
16342}
16343
16344/**
16345 * A data structure to provide a sorted view of accumulated mappings in a
16346 * performance conscious manner. It trades a neglibable overhead in general
16347 * case for a large speedup in case of mappings being added in order.
16348 */
16349function MappingList() {
16350 this._array = [];
16351 this._sorted = true;
16352 // Serves as infimum
16353 this._last = {generatedLine: -1, generatedColumn: 0};
16354}
16355
16356/**
16357 * Iterate through internal items. This method takes the same arguments that
16358 * `Array.prototype.forEach` takes.
16359 *
16360 * NOTE: The order of the mappings is NOT guaranteed.
16361 */
16362MappingList.prototype.unsortedForEach =
16363 function MappingList_forEach(aCallback, aThisArg) {
16364 this._array.forEach(aCallback, aThisArg);
16365 };
16366
16367/**
16368 * Add the given source mapping.
16369 *
16370 * @param Object aMapping
16371 */
16372MappingList.prototype.add = function MappingList_add(aMapping) {
16373 if (generatedPositionAfter(this._last, aMapping)) {
16374 this._last = aMapping;
16375 this._array.push(aMapping);
16376 } else {
16377 this._sorted = false;
16378 this._array.push(aMapping);
16379 }
16380};
16381
16382/**
16383 * Returns the flat, sorted array of mappings. The mappings are sorted by
16384 * generated position.
16385 *
16386 * WARNING: This method returns internal data without copying, for
16387 * performance. The return value must NOT be mutated, and should be treated as
16388 * an immutable borrow. If you want to take ownership, you must make your own
16389 * copy.
16390 */
16391MappingList.prototype.toArray = function MappingList_toArray() {
16392 if (!this._sorted) {
16393 this._array.sort(util.compareByGeneratedPositionsInflated);
16394 this._sorted = true;
16395 }
16396 return this._array;
16397};
16398
16399exports.MappingList = MappingList;
16400
16401},{"./util":112}],108:[function(_dereq_,module,exports){
16402/* -*- Mode: js; js-indent-level: 2; -*- */
16403/*
16404 * Copyright 2011 Mozilla Foundation and contributors
16405 * Licensed under the New BSD license. See LICENSE or:
16406 * http://opensource.org/licenses/BSD-3-Clause
16407 */
16408
16409// It turns out that some (most?) JavaScript engines don't self-host
16410// `Array.prototype.sort`. This makes sense because C++ will likely remain
16411// faster than JS when doing raw CPU-intensive sorting. However, when using a
16412// custom comparator function, calling back and forth between the VM's C++ and
16413// JIT'd JS is rather slow *and* loses JIT type information, resulting in
16414// worse generated code for the comparator function than would be optimal. In
16415// fact, when sorting with a comparator, these costs outweigh the benefits of
16416// sorting in C++. By using our own JS-implemented Quick Sort (below), we get
16417// a ~3500ms mean speed-up in `bench/bench.html`.
16418
16419/**
16420 * Swap the elements indexed by `x` and `y` in the array `ary`.
16421 *
16422 * @param {Array} ary
16423 * The array.
16424 * @param {Number} x
16425 * The index of the first item.
16426 * @param {Number} y
16427 * The index of the second item.
16428 */
16429function swap(ary, x, y) {
16430 var temp = ary[x];
16431 ary[x] = ary[y];
16432 ary[y] = temp;
16433}
16434
16435/**
16436 * Returns a random integer within the range `low .. high` inclusive.
16437 *
16438 * @param {Number} low
16439 * The lower bound on the range.
16440 * @param {Number} high
16441 * The upper bound on the range.
16442 */
16443function randomIntInRange(low, high) {
16444 return Math.round(low + (Math.random() * (high - low)));
16445}
16446
16447/**
16448 * The Quick Sort algorithm.
16449 *
16450 * @param {Array} ary
16451 * An array to sort.
16452 * @param {function} comparator
16453 * Function to use to compare two items.
16454 * @param {Number} p
16455 * Start index of the array
16456 * @param {Number} r
16457 * End index of the array
16458 */
16459function doQuickSort(ary, comparator, p, r) {
16460 // If our lower bound is less than our upper bound, we (1) partition the
16461 // array into two pieces and (2) recurse on each half. If it is not, this is
16462 // the empty array and our base case.
16463
16464 if (p < r) {
16465 // (1) Partitioning.
16466 //
16467 // The partitioning chooses a pivot between `p` and `r` and moves all
16468 // elements that are less than or equal to the pivot to the before it, and
16469 // all the elements that are greater than it after it. The effect is that
16470 // once partition is done, the pivot is in the exact place it will be when
16471 // the array is put in sorted order, and it will not need to be moved
16472 // again. This runs in O(n) time.
16473
16474 // Always choose a random pivot so that an input array which is reverse
16475 // sorted does not cause O(n^2) running time.
16476 var pivotIndex = randomIntInRange(p, r);
16477 var i = p - 1;
16478
16479 swap(ary, pivotIndex, r);
16480 var pivot = ary[r];
16481
16482 // Immediately after `j` is incremented in this loop, the following hold
16483 // true:
16484 //
16485 // * Every element in `ary[p .. i]` is less than or equal to the pivot.
16486 //
16487 // * Every element in `ary[i+1 .. j-1]` is greater than the pivot.
16488 for (var j = p; j < r; j++) {
16489 if (comparator(ary[j], pivot) <= 0) {
16490 i += 1;
16491 swap(ary, i, j);
16492 }
16493 }
16494
16495 swap(ary, i + 1, j);
16496 var q = i + 1;
16497
16498 // (2) Recurse on each half.
16499
16500 doQuickSort(ary, comparator, p, q - 1);
16501 doQuickSort(ary, comparator, q + 1, r);
16502 }
16503}
16504
16505/**
16506 * Sort the given array in-place with the given comparator function.
16507 *
16508 * @param {Array} ary
16509 * An array to sort.
16510 * @param {function} comparator
16511 * Function to use to compare two items.
16512 */
16513exports.quickSort = function (ary, comparator) {
16514 doQuickSort(ary, comparator, 0, ary.length - 1);
16515};
16516
16517},{}],109:[function(_dereq_,module,exports){
16518/* -*- Mode: js; js-indent-level: 2; -*- */
16519/*
16520 * Copyright 2011 Mozilla Foundation and contributors
16521 * Licensed under the New BSD license. See LICENSE or:
16522 * http://opensource.org/licenses/BSD-3-Clause
16523 */
16524
16525var util = _dereq_('./util');
16526var binarySearch = _dereq_('./binary-search');
16527var ArraySet = _dereq_('./array-set').ArraySet;
16528var base64VLQ = _dereq_('./base64-vlq');
16529var quickSort = _dereq_('./quick-sort').quickSort;
16530
16531function SourceMapConsumer(aSourceMap) {
16532 var sourceMap = aSourceMap;
16533 if (typeof aSourceMap === 'string') {
16534 sourceMap = JSON.parse(aSourceMap.replace(/^\)\]\}'/, ''));
16535 }
16536
16537 return sourceMap.sections != null
16538 ? new IndexedSourceMapConsumer(sourceMap)
16539 : new BasicSourceMapConsumer(sourceMap);
16540}
16541
16542SourceMapConsumer.fromSourceMap = function(aSourceMap) {
16543 return BasicSourceMapConsumer.fromSourceMap(aSourceMap);
16544}
16545
16546/**
16547 * The version of the source mapping spec that we are consuming.
16548 */
16549SourceMapConsumer.prototype._version = 3;
16550
16551// `__generatedMappings` and `__originalMappings` are arrays that hold the
16552// parsed mapping coordinates from the source map's "mappings" attribute. They
16553// are lazily instantiated, accessed via the `_generatedMappings` and
16554// `_originalMappings` getters respectively, and we only parse the mappings
16555// and create these arrays once queried for a source location. We jump through
16556// these hoops because there can be many thousands of mappings, and parsing
16557// them is expensive, so we only want to do it if we must.
16558//
16559// Each object in the arrays is of the form:
16560//
16561// {
16562// generatedLine: The line number in the generated code,
16563// generatedColumn: The column number in the generated code,
16564// source: The path to the original source file that generated this
16565// chunk of code,
16566// originalLine: The line number in the original source that
16567// corresponds to this chunk of generated code,
16568// originalColumn: The column number in the original source that
16569// corresponds to this chunk of generated code,
16570// name: The name of the original symbol which generated this chunk of
16571// code.
16572// }
16573//
16574// All properties except for `generatedLine` and `generatedColumn` can be
16575// `null`.
16576//
16577// `_generatedMappings` is ordered by the generated positions.
16578//
16579// `_originalMappings` is ordered by the original positions.
16580
16581SourceMapConsumer.prototype.__generatedMappings = null;
16582Object.defineProperty(SourceMapConsumer.prototype, '_generatedMappings', {
16583 get: function () {
16584 if (!this.__generatedMappings) {
16585 this._parseMappings(this._mappings, this.sourceRoot);
16586 }
16587
16588 return this.__generatedMappings;
16589 }
16590});
16591
16592SourceMapConsumer.prototype.__originalMappings = null;
16593Object.defineProperty(SourceMapConsumer.prototype, '_originalMappings', {
16594 get: function () {
16595 if (!this.__originalMappings) {
16596 this._parseMappings(this._mappings, this.sourceRoot);
16597 }
16598
16599 return this.__originalMappings;
16600 }
16601});
16602
16603SourceMapConsumer.prototype._charIsMappingSeparator =
16604 function SourceMapConsumer_charIsMappingSeparator(aStr, index) {
16605 var c = aStr.charAt(index);
16606 return c === ";" || c === ",";
16607 };
16608
16609/**
16610 * Parse the mappings in a string in to a data structure which we can easily
16611 * query (the ordered arrays in the `this.__generatedMappings` and
16612 * `this.__originalMappings` properties).
16613 */
16614SourceMapConsumer.prototype._parseMappings =
16615 function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {
16616 throw new Error("Subclasses must implement _parseMappings");
16617 };
16618
16619SourceMapConsumer.GENERATED_ORDER = 1;
16620SourceMapConsumer.ORIGINAL_ORDER = 2;
16621
16622SourceMapConsumer.GREATEST_LOWER_BOUND = 1;
16623SourceMapConsumer.LEAST_UPPER_BOUND = 2;
16624
16625/**
16626 * Iterate over each mapping between an original source/line/column and a
16627 * generated line/column in this source map.
16628 *
16629 * @param Function aCallback
16630 * The function that is called with each mapping.
16631 * @param Object aContext
16632 * Optional. If specified, this object will be the value of `this` every
16633 * time that `aCallback` is called.
16634 * @param aOrder
16635 * Either `SourceMapConsumer.GENERATED_ORDER` or
16636 * `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to
16637 * iterate over the mappings sorted by the generated file's line/column
16638 * order or the original's source/line/column order, respectively. Defaults to
16639 * `SourceMapConsumer.GENERATED_ORDER`.
16640 */
16641SourceMapConsumer.prototype.eachMapping =
16642 function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) {
16643 var context = aContext || null;
16644 var order = aOrder || SourceMapConsumer.GENERATED_ORDER;
16645
16646 var mappings;
16647 switch (order) {
16648 case SourceMapConsumer.GENERATED_ORDER:
16649 mappings = this._generatedMappings;
16650 break;
16651 case SourceMapConsumer.ORIGINAL_ORDER:
16652 mappings = this._originalMappings;
16653 break;
16654 default:
16655 throw new Error("Unknown order of iteration.");
16656 }
16657
16658 var sourceRoot = this.sourceRoot;
16659 mappings.map(function (mapping) {
16660 var source = mapping.source === null ? null : this._sources.at(mapping.source);
16661 if (source != null && sourceRoot != null) {
16662 source = util.join(sourceRoot, source);
16663 }
16664 return {
16665 source: source,
16666 generatedLine: mapping.generatedLine,
16667 generatedColumn: mapping.generatedColumn,
16668 originalLine: mapping.originalLine,
16669 originalColumn: mapping.originalColumn,
16670 name: mapping.name === null ? null : this._names.at(mapping.name)
16671 };
16672 }, this).forEach(aCallback, context);
16673 };
16674
16675/**
16676 * Returns all generated line and column information for the original source,
16677 * line, and column provided. If no column is provided, returns all mappings
16678 * corresponding to a either the line we are searching for or the next
16679 * closest line that has any mappings. Otherwise, returns all mappings
16680 * corresponding to the given line and either the column we are searching for
16681 * or the next closest column that has any offsets.
16682 *
16683 * The only argument is an object with the following properties:
16684 *
16685 * - source: The filename of the original source.
16686 * - line: The line number in the original source.
16687 * - column: Optional. the column number in the original source.
16688 *
16689 * and an array of objects is returned, each with the following properties:
16690 *
16691 * - line: The line number in the generated source, or null.
16692 * - column: The column number in the generated source, or null.
16693 */
16694SourceMapConsumer.prototype.allGeneratedPositionsFor =
16695 function SourceMapConsumer_allGeneratedPositionsFor(aArgs) {
16696 var line = util.getArg(aArgs, 'line');
16697
16698 // When there is no exact match, BasicSourceMapConsumer.prototype._findMapping
16699 // returns the index of the closest mapping less than the needle. By
16700 // setting needle.originalColumn to 0, we thus find the last mapping for
16701 // the given line, provided such a mapping exists.
16702 var needle = {
16703 source: util.getArg(aArgs, 'source'),
16704 originalLine: line,
16705 originalColumn: util.getArg(aArgs, 'column', 0)
16706 };
16707
16708 if (this.sourceRoot != null) {
16709 needle.source = util.relative(this.sourceRoot, needle.source);
16710 }
16711 if (!this._sources.has(needle.source)) {
16712 return [];
16713 }
16714 needle.source = this._sources.indexOf(needle.source);
16715
16716 var mappings = [];
16717
16718 var index = this._findMapping(needle,
16719 this._originalMappings,
16720 "originalLine",
16721 "originalColumn",
16722 util.compareByOriginalPositions,
16723 binarySearch.LEAST_UPPER_BOUND);
16724 if (index >= 0) {
16725 var mapping = this._originalMappings[index];
16726
16727 if (aArgs.column === undefined) {
16728 var originalLine = mapping.originalLine;
16729
16730 // Iterate until either we run out of mappings, or we run into
16731 // a mapping for a different line than the one we found. Since
16732 // mappings are sorted, this is guaranteed to find all mappings for
16733 // the line we found.
16734 while (mapping && mapping.originalLine === originalLine) {
16735 mappings.push({
16736 line: util.getArg(mapping, 'generatedLine', null),
16737 column: util.getArg(mapping, 'generatedColumn', null),
16738 lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)
16739 });
16740
16741 mapping = this._originalMappings[++index];
16742 }
16743 } else {
16744 var originalColumn = mapping.originalColumn;
16745
16746 // Iterate until either we run out of mappings, or we run into
16747 // a mapping for a different line than the one we were searching for.
16748 // Since mappings are sorted, this is guaranteed to find all mappings for
16749 // the line we are searching for.
16750 while (mapping &&
16751 mapping.originalLine === line &&
16752 mapping.originalColumn == originalColumn) {
16753 mappings.push({
16754 line: util.getArg(mapping, 'generatedLine', null),
16755 column: util.getArg(mapping, 'generatedColumn', null),
16756 lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)
16757 });
16758
16759 mapping = this._originalMappings[++index];
16760 }
16761 }
16762 }
16763
16764 return mappings;
16765 };
16766
16767exports.SourceMapConsumer = SourceMapConsumer;
16768
16769/**
16770 * A BasicSourceMapConsumer instance represents a parsed source map which we can
16771 * query for information about the original file positions by giving it a file
16772 * position in the generated source.
16773 *
16774 * The only parameter is the raw source map (either as a JSON string, or
16775 * already parsed to an object). According to the spec, source maps have the
16776 * following attributes:
16777 *
16778 * - version: Which version of the source map spec this map is following.
16779 * - sources: An array of URLs to the original source files.
16780 * - names: An array of identifiers which can be referrenced by individual mappings.
16781 * - sourceRoot: Optional. The URL root from which all sources are relative.
16782 * - sourcesContent: Optional. An array of contents of the original source files.
16783 * - mappings: A string of base64 VLQs which contain the actual mappings.
16784 * - file: Optional. The generated file this source map is associated with.
16785 *
16786 * Here is an example source map, taken from the source map spec[0]:
16787 *
16788 * {
16789 * version : 3,
16790 * file: "out.js",
16791 * sourceRoot : "",
16792 * sources: ["foo.js", "bar.js"],
16793 * names: ["src", "maps", "are", "fun"],
16794 * mappings: "AA,AB;;ABCDE;"
16795 * }
16796 *
16797 * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?pli=1#
16798 */
16799function BasicSourceMapConsumer(aSourceMap) {
16800 var sourceMap = aSourceMap;
16801 if (typeof aSourceMap === 'string') {
16802 sourceMap = JSON.parse(aSourceMap.replace(/^\)\]\}'/, ''));
16803 }
16804
16805 var version = util.getArg(sourceMap, 'version');
16806 var sources = util.getArg(sourceMap, 'sources');
16807 // Sass 3.3 leaves out the 'names' array, so we deviate from the spec (which
16808 // requires the array) to play nice here.
16809 var names = util.getArg(sourceMap, 'names', []);
16810 var sourceRoot = util.getArg(sourceMap, 'sourceRoot', null);
16811 var sourcesContent = util.getArg(sourceMap, 'sourcesContent', null);
16812 var mappings = util.getArg(sourceMap, 'mappings');
16813 var file = util.getArg(sourceMap, 'file', null);
16814
16815 // Once again, Sass deviates from the spec and supplies the version as a
16816 // string rather than a number, so we use loose equality checking here.
16817 if (version != this._version) {
16818 throw new Error('Unsupported version: ' + version);
16819 }
16820
16821 sources = sources
16822 .map(String)
16823 // Some source maps produce relative source paths like "./foo.js" instead of
16824 // "foo.js". Normalize these first so that future comparisons will succeed.
16825 // See bugzil.la/1090768.
16826 .map(util.normalize)
16827 // Always ensure that absolute sources are internally stored relative to
16828 // the source root, if the source root is absolute. Not doing this would
16829 // be particularly problematic when the source root is a prefix of the
16830 // source (valid, but why??). See github issue #199 and bugzil.la/1188982.
16831 .map(function (source) {
16832 return sourceRoot && util.isAbsolute(sourceRoot) && util.isAbsolute(source)
16833 ? util.relative(sourceRoot, source)
16834 : source;
16835 });
16836
16837 // Pass `true` below to allow duplicate names and sources. While source maps
16838 // are intended to be compressed and deduplicated, the TypeScript compiler
16839 // sometimes generates source maps with duplicates in them. See Github issue
16840 // #72 and bugzil.la/889492.
16841 this._names = ArraySet.fromArray(names.map(String), true);
16842 this._sources = ArraySet.fromArray(sources, true);
16843
16844 this.sourceRoot = sourceRoot;
16845 this.sourcesContent = sourcesContent;
16846 this._mappings = mappings;
16847 this.file = file;
16848}
16849
16850BasicSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype);
16851BasicSourceMapConsumer.prototype.consumer = SourceMapConsumer;
16852
16853/**
16854 * Create a BasicSourceMapConsumer from a SourceMapGenerator.
16855 *
16856 * @param SourceMapGenerator aSourceMap
16857 * The source map that will be consumed.
16858 * @returns BasicSourceMapConsumer
16859 */
16860BasicSourceMapConsumer.fromSourceMap =
16861 function SourceMapConsumer_fromSourceMap(aSourceMap) {
16862 var smc = Object.create(BasicSourceMapConsumer.prototype);
16863
16864 var names = smc._names = ArraySet.fromArray(aSourceMap._names.toArray(), true);
16865 var sources = smc._sources = ArraySet.fromArray(aSourceMap._sources.toArray(), true);
16866 smc.sourceRoot = aSourceMap._sourceRoot;
16867 smc.sourcesContent = aSourceMap._generateSourcesContent(smc._sources.toArray(),
16868 smc.sourceRoot);
16869 smc.file = aSourceMap._file;
16870
16871 // Because we are modifying the entries (by converting string sources and
16872 // names to indices into the sources and names ArraySets), we have to make
16873 // a copy of the entry or else bad things happen. Shared mutable state
16874 // strikes again! See github issue #191.
16875
16876 var generatedMappings = aSourceMap._mappings.toArray().slice();
16877 var destGeneratedMappings = smc.__generatedMappings = [];
16878 var destOriginalMappings = smc.__originalMappings = [];
16879
16880 for (var i = 0, length = generatedMappings.length; i < length; i++) {
16881 var srcMapping = generatedMappings[i];
16882 var destMapping = new Mapping;
16883 destMapping.generatedLine = srcMapping.generatedLine;
16884 destMapping.generatedColumn = srcMapping.generatedColumn;
16885
16886 if (srcMapping.source) {
16887 destMapping.source = sources.indexOf(srcMapping.source);
16888 destMapping.originalLine = srcMapping.originalLine;
16889 destMapping.originalColumn = srcMapping.originalColumn;
16890
16891 if (srcMapping.name) {
16892 destMapping.name = names.indexOf(srcMapping.name);
16893 }
16894
16895 destOriginalMappings.push(destMapping);
16896 }
16897
16898 destGeneratedMappings.push(destMapping);
16899 }
16900
16901 quickSort(smc.__originalMappings, util.compareByOriginalPositions);
16902
16903 return smc;
16904 };
16905
16906/**
16907 * The version of the source mapping spec that we are consuming.
16908 */
16909BasicSourceMapConsumer.prototype._version = 3;
16910
16911/**
16912 * The list of original sources.
16913 */
16914Object.defineProperty(BasicSourceMapConsumer.prototype, 'sources', {
16915 get: function () {
16916 return this._sources.toArray().map(function (s) {
16917 return this.sourceRoot != null ? util.join(this.sourceRoot, s) : s;
16918 }, this);
16919 }
16920});
16921
16922/**
16923 * Provide the JIT with a nice shape / hidden class.
16924 */
16925function Mapping() {
16926 this.generatedLine = 0;
16927 this.generatedColumn = 0;
16928 this.source = null;
16929 this.originalLine = null;
16930 this.originalColumn = null;
16931 this.name = null;
16932}
16933
16934/**
16935 * Parse the mappings in a string in to a data structure which we can easily
16936 * query (the ordered arrays in the `this.__generatedMappings` and
16937 * `this.__originalMappings` properties).
16938 */
16939BasicSourceMapConsumer.prototype._parseMappings =
16940 function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {
16941 var generatedLine = 1;
16942 var previousGeneratedColumn = 0;
16943 var previousOriginalLine = 0;
16944 var previousOriginalColumn = 0;
16945 var previousSource = 0;
16946 var previousName = 0;
16947 var length = aStr.length;
16948 var index = 0;
16949 var cachedSegments = {};
16950 var temp = {};
16951 var originalMappings = [];
16952 var generatedMappings = [];
16953 var mapping, str, segment, end, value;
16954
16955 while (index < length) {
16956 if (aStr.charAt(index) === ';') {
16957 generatedLine++;
16958 index++;
16959 previousGeneratedColumn = 0;
16960 }
16961 else if (aStr.charAt(index) === ',') {
16962 index++;
16963 }
16964 else {
16965 mapping = new Mapping();
16966 mapping.generatedLine = generatedLine;
16967
16968 // Because each offset is encoded relative to the previous one,
16969 // many segments often have the same encoding. We can exploit this
16970 // fact by caching the parsed variable length fields of each segment,
16971 // allowing us to avoid a second parse if we encounter the same
16972 // segment again.
16973 for (end = index; end < length; end++) {
16974 if (this._charIsMappingSeparator(aStr, end)) {
16975 break;
16976 }
16977 }
16978 str = aStr.slice(index, end);
16979
16980 segment = cachedSegments[str];
16981 if (segment) {
16982 index += str.length;
16983 } else {
16984 segment = [];
16985 while (index < end) {
16986 base64VLQ.decode(aStr, index, temp);
16987 value = temp.value;
16988 index = temp.rest;
16989 segment.push(value);
16990 }
16991
16992 if (segment.length === 2) {
16993 throw new Error('Found a source, but no line and column');
16994 }
16995
16996 if (segment.length === 3) {
16997 throw new Error('Found a source and line, but no column');
16998 }
16999
17000 cachedSegments[str] = segment;
17001 }
17002
17003 // Generated column.
17004 mapping.generatedColumn = previousGeneratedColumn + segment[0];
17005 previousGeneratedColumn = mapping.generatedColumn;
17006
17007 if (segment.length > 1) {
17008 // Original source.
17009 mapping.source = previousSource + segment[1];
17010 previousSource += segment[1];
17011
17012 // Original line.
17013 mapping.originalLine = previousOriginalLine + segment[2];
17014 previousOriginalLine = mapping.originalLine;
17015 // Lines are stored 0-based
17016 mapping.originalLine += 1;
17017
17018 // Original column.
17019 mapping.originalColumn = previousOriginalColumn + segment[3];
17020 previousOriginalColumn = mapping.originalColumn;
17021
17022 if (segment.length > 4) {
17023 // Original name.
17024 mapping.name = previousName + segment[4];
17025 previousName += segment[4];
17026 }
17027 }
17028
17029 generatedMappings.push(mapping);
17030 if (typeof mapping.originalLine === 'number') {
17031 originalMappings.push(mapping);
17032 }
17033 }
17034 }
17035
17036 quickSort(generatedMappings, util.compareByGeneratedPositionsDeflated);
17037 this.__generatedMappings = generatedMappings;
17038
17039 quickSort(originalMappings, util.compareByOriginalPositions);
17040 this.__originalMappings = originalMappings;
17041 };
17042
17043/**
17044 * Find the mapping that best matches the hypothetical "needle" mapping that
17045 * we are searching for in the given "haystack" of mappings.
17046 */
17047BasicSourceMapConsumer.prototype._findMapping =
17048 function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName,
17049 aColumnName, aComparator, aBias) {
17050 // To return the position we are searching for, we must first find the
17051 // mapping for the given position and then return the opposite position it
17052 // points to. Because the mappings are sorted, we can use binary search to
17053 // find the best mapping.
17054
17055 if (aNeedle[aLineName] <= 0) {
17056 throw new TypeError('Line must be greater than or equal to 1, got '
17057 + aNeedle[aLineName]);
17058 }
17059 if (aNeedle[aColumnName] < 0) {
17060 throw new TypeError('Column must be greater than or equal to 0, got '
17061 + aNeedle[aColumnName]);
17062 }
17063
17064 return binarySearch.search(aNeedle, aMappings, aComparator, aBias);
17065 };
17066
17067/**
17068 * Compute the last column for each generated mapping. The last column is
17069 * inclusive.
17070 */
17071BasicSourceMapConsumer.prototype.computeColumnSpans =
17072 function SourceMapConsumer_computeColumnSpans() {
17073 for (var index = 0; index < this._generatedMappings.length; ++index) {
17074 var mapping = this._generatedMappings[index];
17075
17076 // Mappings do not contain a field for the last generated columnt. We
17077 // can come up with an optimistic estimate, however, by assuming that
17078 // mappings are contiguous (i.e. given two consecutive mappings, the
17079 // first mapping ends where the second one starts).
17080 if (index + 1 < this._generatedMappings.length) {
17081 var nextMapping = this._generatedMappings[index + 1];
17082
17083 if (mapping.generatedLine === nextMapping.generatedLine) {
17084 mapping.lastGeneratedColumn = nextMapping.generatedColumn - 1;
17085 continue;
17086 }
17087 }
17088
17089 // The last mapping for each line spans the entire line.
17090 mapping.lastGeneratedColumn = Infinity;
17091 }
17092 };
17093
17094/**
17095 * Returns the original source, line, and column information for the generated
17096 * source's line and column positions provided. The only argument is an object
17097 * with the following properties:
17098 *
17099 * - line: The line number in the generated source.
17100 * - column: The column number in the generated source.
17101 * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or
17102 * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the
17103 * closest element that is smaller than or greater than the one we are
17104 * searching for, respectively, if the exact element cannot be found.
17105 * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'.
17106 *
17107 * and an object is returned with the following properties:
17108 *
17109 * - source: The original source file, or null.
17110 * - line: The line number in the original source, or null.
17111 * - column: The column number in the original source, or null.
17112 * - name: The original identifier, or null.
17113 */
17114BasicSourceMapConsumer.prototype.originalPositionFor =
17115 function SourceMapConsumer_originalPositionFor(aArgs) {
17116 var needle = {
17117 generatedLine: util.getArg(aArgs, 'line'),
17118 generatedColumn: util.getArg(aArgs, 'column')
17119 };
17120
17121 var index = this._findMapping(
17122 needle,
17123 this._generatedMappings,
17124 "generatedLine",
17125 "generatedColumn",
17126 util.compareByGeneratedPositionsDeflated,
17127 util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND)
17128 );
17129
17130 if (index >= 0) {
17131 var mapping = this._generatedMappings[index];
17132
17133 if (mapping.generatedLine === needle.generatedLine) {
17134 var source = util.getArg(mapping, 'source', null);
17135 if (source !== null) {
17136 source = this._sources.at(source);
17137 if (this.sourceRoot != null) {
17138 source = util.join(this.sourceRoot, source);
17139 }
17140 }
17141 var name = util.getArg(mapping, 'name', null);
17142 if (name !== null) {
17143 name = this._names.at(name);
17144 }
17145 return {
17146 source: source,
17147 line: util.getArg(mapping, 'originalLine', null),
17148 column: util.getArg(mapping, 'originalColumn', null),
17149 name: name
17150 };
17151 }
17152 }
17153
17154 return {
17155 source: null,
17156 line: null,
17157 column: null,
17158 name: null
17159 };
17160 };
17161
17162/**
17163 * Return true if we have the source content for every source in the source
17164 * map, false otherwise.
17165 */
17166BasicSourceMapConsumer.prototype.hasContentsOfAllSources =
17167 function BasicSourceMapConsumer_hasContentsOfAllSources() {
17168 if (!this.sourcesContent) {
17169 return false;
17170 }
17171 return this.sourcesContent.length >= this._sources.size() &&
17172 !this.sourcesContent.some(function (sc) { return sc == null; });
17173 };
17174
17175/**
17176 * Returns the original source content. The only argument is the url of the
17177 * original source file. Returns null if no original source content is
17178 * available.
17179 */
17180BasicSourceMapConsumer.prototype.sourceContentFor =
17181 function SourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {
17182 if (!this.sourcesContent) {
17183 return null;
17184 }
17185
17186 if (this.sourceRoot != null) {
17187 aSource = util.relative(this.sourceRoot, aSource);
17188 }
17189
17190 if (this._sources.has(aSource)) {
17191 return this.sourcesContent[this._sources.indexOf(aSource)];
17192 }
17193
17194 var url;
17195 if (this.sourceRoot != null
17196 && (url = util.urlParse(this.sourceRoot))) {
17197 // XXX: file:// URIs and absolute paths lead to unexpected behavior for
17198 // many users. We can help them out when they expect file:// URIs to
17199 // behave like it would if they were running a local HTTP server. See
17200 // https://bugzilla.mozilla.org/show_bug.cgi?id=885597.
17201 var fileUriAbsPath = aSource.replace(/^file:\/\//, "");
17202 if (url.scheme == "file"
17203 && this._sources.has(fileUriAbsPath)) {
17204 return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)]
17205 }
17206
17207 if ((!url.path || url.path == "/")
17208 && this._sources.has("/" + aSource)) {
17209 return this.sourcesContent[this._sources.indexOf("/" + aSource)];
17210 }
17211 }
17212
17213 // This function is used recursively from
17214 // IndexedSourceMapConsumer.prototype.sourceContentFor. In that case, we
17215 // don't want to throw if we can't find the source - we just want to
17216 // return null, so we provide a flag to exit gracefully.
17217 if (nullOnMissing) {
17218 return null;
17219 }
17220 else {
17221 throw new Error('"' + aSource + '" is not in the SourceMap.');
17222 }
17223 };
17224
17225/**
17226 * Returns the generated line and column information for the original source,
17227 * line, and column positions provided. The only argument is an object with
17228 * the following properties:
17229 *
17230 * - source: The filename of the original source.
17231 * - line: The line number in the original source.
17232 * - column: The column number in the original source.
17233 * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or
17234 * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the
17235 * closest element that is smaller than or greater than the one we are
17236 * searching for, respectively, if the exact element cannot be found.
17237 * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'.
17238 *
17239 * and an object is returned with the following properties:
17240 *
17241 * - line: The line number in the generated source, or null.
17242 * - column: The column number in the generated source, or null.
17243 */
17244BasicSourceMapConsumer.prototype.generatedPositionFor =
17245 function SourceMapConsumer_generatedPositionFor(aArgs) {
17246 var source = util.getArg(aArgs, 'source');
17247 if (this.sourceRoot != null) {
17248 source = util.relative(this.sourceRoot, source);
17249 }
17250 if (!this._sources.has(source)) {
17251 return {
17252 line: null,
17253 column: null,
17254 lastColumn: null
17255 };
17256 }
17257 source = this._sources.indexOf(source);
17258
17259 var needle = {
17260 source: source,
17261 originalLine: util.getArg(aArgs, 'line'),
17262 originalColumn: util.getArg(aArgs, 'column')
17263 };
17264
17265 var index = this._findMapping(
17266 needle,
17267 this._originalMappings,
17268 "originalLine",
17269 "originalColumn",
17270 util.compareByOriginalPositions,
17271 util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND)
17272 );
17273
17274 if (index >= 0) {
17275 var mapping = this._originalMappings[index];
17276
17277 if (mapping.source === needle.source) {
17278 return {
17279 line: util.getArg(mapping, 'generatedLine', null),
17280 column: util.getArg(mapping, 'generatedColumn', null),
17281 lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)
17282 };
17283 }
17284 }
17285
17286 return {
17287 line: null,
17288 column: null,
17289 lastColumn: null
17290 };
17291 };
17292
17293exports.BasicSourceMapConsumer = BasicSourceMapConsumer;
17294
17295/**
17296 * An IndexedSourceMapConsumer instance represents a parsed source map which
17297 * we can query for information. It differs from BasicSourceMapConsumer in
17298 * that it takes "indexed" source maps (i.e. ones with a "sections" field) as
17299 * input.
17300 *
17301 * The only parameter is a raw source map (either as a JSON string, or already
17302 * parsed to an object). According to the spec for indexed source maps, they
17303 * have the following attributes:
17304 *
17305 * - version: Which version of the source map spec this map is following.
17306 * - file: Optional. The generated file this source map is associated with.
17307 * - sections: A list of section definitions.
17308 *
17309 * Each value under the "sections" field has two fields:
17310 * - offset: The offset into the original specified at which this section
17311 * begins to apply, defined as an object with a "line" and "column"
17312 * field.
17313 * - map: A source map definition. This source map could also be indexed,
17314 * but doesn't have to be.
17315 *
17316 * Instead of the "map" field, it's also possible to have a "url" field
17317 * specifying a URL to retrieve a source map from, but that's currently
17318 * unsupported.
17319 *
17320 * Here's an example source map, taken from the source map spec[0], but
17321 * modified to omit a section which uses the "url" field.
17322 *
17323 * {
17324 * version : 3,
17325 * file: "app.js",
17326 * sections: [{
17327 * offset: {line:100, column:10},
17328 * map: {
17329 * version : 3,
17330 * file: "section.js",
17331 * sources: ["foo.js", "bar.js"],
17332 * names: ["src", "maps", "are", "fun"],
17333 * mappings: "AAAA,E;;ABCDE;"
17334 * }
17335 * }],
17336 * }
17337 *
17338 * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit#heading=h.535es3xeprgt
17339 */
17340function IndexedSourceMapConsumer(aSourceMap) {
17341 var sourceMap = aSourceMap;
17342 if (typeof aSourceMap === 'string') {
17343 sourceMap = JSON.parse(aSourceMap.replace(/^\)\]\}'/, ''));
17344 }
17345
17346 var version = util.getArg(sourceMap, 'version');
17347 var sections = util.getArg(sourceMap, 'sections');
17348
17349 if (version != this._version) {
17350 throw new Error('Unsupported version: ' + version);
17351 }
17352
17353 this._sources = new ArraySet();
17354 this._names = new ArraySet();
17355
17356 var lastOffset = {
17357 line: -1,
17358 column: 0
17359 };
17360 this._sections = sections.map(function (s) {
17361 if (s.url) {
17362 // The url field will require support for asynchronicity.
17363 // See https://github.com/mozilla/source-map/issues/16
17364 throw new Error('Support for url field in sections not implemented.');
17365 }
17366 var offset = util.getArg(s, 'offset');
17367 var offsetLine = util.getArg(offset, 'line');
17368 var offsetColumn = util.getArg(offset, 'column');
17369
17370 if (offsetLine < lastOffset.line ||
17371 (offsetLine === lastOffset.line && offsetColumn < lastOffset.column)) {
17372 throw new Error('Section offsets must be ordered and non-overlapping.');
17373 }
17374 lastOffset = offset;
17375
17376 return {
17377 generatedOffset: {
17378 // The offset fields are 0-based, but we use 1-based indices when
17379 // encoding/decoding from VLQ.
17380 generatedLine: offsetLine + 1,
17381 generatedColumn: offsetColumn + 1
17382 },
17383 consumer: new SourceMapConsumer(util.getArg(s, 'map'))
17384 }
17385 });
17386}
17387
17388IndexedSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype);
17389IndexedSourceMapConsumer.prototype.constructor = SourceMapConsumer;
17390
17391/**
17392 * The version of the source mapping spec that we are consuming.
17393 */
17394IndexedSourceMapConsumer.prototype._version = 3;
17395
17396/**
17397 * The list of original sources.
17398 */
17399Object.defineProperty(IndexedSourceMapConsumer.prototype, 'sources', {
17400 get: function () {
17401 var sources = [];
17402 for (var i = 0; i < this._sections.length; i++) {
17403 for (var j = 0; j < this._sections[i].consumer.sources.length; j++) {
17404 sources.push(this._sections[i].consumer.sources[j]);
17405 }
17406 }
17407 return sources;
17408 }
17409});
17410
17411/**
17412 * Returns the original source, line, and column information for the generated
17413 * source's line and column positions provided. The only argument is an object
17414 * with the following properties:
17415 *
17416 * - line: The line number in the generated source.
17417 * - column: The column number in the generated source.
17418 *
17419 * and an object is returned with the following properties:
17420 *
17421 * - source: The original source file, or null.
17422 * - line: The line number in the original source, or null.
17423 * - column: The column number in the original source, or null.
17424 * - name: The original identifier, or null.
17425 */
17426IndexedSourceMapConsumer.prototype.originalPositionFor =
17427 function IndexedSourceMapConsumer_originalPositionFor(aArgs) {
17428 var needle = {
17429 generatedLine: util.getArg(aArgs, 'line'),
17430 generatedColumn: util.getArg(aArgs, 'column')
17431 };
17432
17433 // Find the section containing the generated position we're trying to map
17434 // to an original position.
17435 var sectionIndex = binarySearch.search(needle, this._sections,
17436 function(needle, section) {
17437 var cmp = needle.generatedLine - section.generatedOffset.generatedLine;
17438 if (cmp) {
17439 return cmp;
17440 }
17441
17442 return (needle.generatedColumn -
17443 section.generatedOffset.generatedColumn);
17444 });
17445 var section = this._sections[sectionIndex];
17446
17447 if (!section) {
17448 return {
17449 source: null,
17450 line: null,
17451 column: null,
17452 name: null
17453 };
17454 }
17455
17456 return section.consumer.originalPositionFor({
17457 line: needle.generatedLine -
17458 (section.generatedOffset.generatedLine - 1),
17459 column: needle.generatedColumn -
17460 (section.generatedOffset.generatedLine === needle.generatedLine
17461 ? section.generatedOffset.generatedColumn - 1
17462 : 0),
17463 bias: aArgs.bias
17464 });
17465 };
17466
17467/**
17468 * Return true if we have the source content for every source in the source
17469 * map, false otherwise.
17470 */
17471IndexedSourceMapConsumer.prototype.hasContentsOfAllSources =
17472 function IndexedSourceMapConsumer_hasContentsOfAllSources() {
17473 return this._sections.every(function (s) {
17474 return s.consumer.hasContentsOfAllSources();
17475 });
17476 };
17477
17478/**
17479 * Returns the original source content. The only argument is the url of the
17480 * original source file. Returns null if no original source content is
17481 * available.
17482 */
17483IndexedSourceMapConsumer.prototype.sourceContentFor =
17484 function IndexedSourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {
17485 for (var i = 0; i < this._sections.length; i++) {
17486 var section = this._sections[i];
17487
17488 var content = section.consumer.sourceContentFor(aSource, true);
17489 if (content) {
17490 return content;
17491 }
17492 }
17493 if (nullOnMissing) {
17494 return null;
17495 }
17496 else {
17497 throw new Error('"' + aSource + '" is not in the SourceMap.');
17498 }
17499 };
17500
17501/**
17502 * Returns the generated line and column information for the original source,
17503 * line, and column positions provided. The only argument is an object with
17504 * the following properties:
17505 *
17506 * - source: The filename of the original source.
17507 * - line: The line number in the original source.
17508 * - column: The column number in the original source.
17509 *
17510 * and an object is returned with the following properties:
17511 *
17512 * - line: The line number in the generated source, or null.
17513 * - column: The column number in the generated source, or null.
17514 */
17515IndexedSourceMapConsumer.prototype.generatedPositionFor =
17516 function IndexedSourceMapConsumer_generatedPositionFor(aArgs) {
17517 for (var i = 0; i < this._sections.length; i++) {
17518 var section = this._sections[i];
17519
17520 // Only consider this section if the requested source is in the list of
17521 // sources of the consumer.
17522 if (section.consumer.sources.indexOf(util.getArg(aArgs, 'source')) === -1) {
17523 continue;
17524 }
17525 var generatedPosition = section.consumer.generatedPositionFor(aArgs);
17526 if (generatedPosition) {
17527 var ret = {
17528 line: generatedPosition.line +
17529 (section.generatedOffset.generatedLine - 1),
17530 column: generatedPosition.column +
17531 (section.generatedOffset.generatedLine === generatedPosition.line
17532 ? section.generatedOffset.generatedColumn - 1
17533 : 0)
17534 };
17535 return ret;
17536 }
17537 }
17538
17539 return {
17540 line: null,
17541 column: null
17542 };
17543 };
17544
17545/**
17546 * Parse the mappings in a string in to a data structure which we can easily
17547 * query (the ordered arrays in the `this.__generatedMappings` and
17548 * `this.__originalMappings` properties).
17549 */
17550IndexedSourceMapConsumer.prototype._parseMappings =
17551 function IndexedSourceMapConsumer_parseMappings(aStr, aSourceRoot) {
17552 this.__generatedMappings = [];
17553 this.__originalMappings = [];
17554 for (var i = 0; i < this._sections.length; i++) {
17555 var section = this._sections[i];
17556 var sectionMappings = section.consumer._generatedMappings;
17557 for (var j = 0; j < sectionMappings.length; j++) {
17558 var mapping = sectionMappings[j];
17559
17560 var source = section.consumer._sources.at(mapping.source);
17561 if (section.consumer.sourceRoot !== null) {
17562 source = util.join(section.consumer.sourceRoot, source);
17563 }
17564 this._sources.add(source);
17565 source = this._sources.indexOf(source);
17566
17567 var name = section.consumer._names.at(mapping.name);
17568 this._names.add(name);
17569 name = this._names.indexOf(name);
17570
17571 // The mappings coming from the consumer for the section have
17572 // generated positions relative to the start of the section, so we
17573 // need to offset them to be relative to the start of the concatenated
17574 // generated file.
17575 var adjustedMapping = {
17576 source: source,
17577 generatedLine: mapping.generatedLine +
17578 (section.generatedOffset.generatedLine - 1),
17579 generatedColumn: mapping.generatedColumn +
17580 (section.generatedOffset.generatedLine === mapping.generatedLine
17581 ? section.generatedOffset.generatedColumn - 1
17582 : 0),
17583 originalLine: mapping.originalLine,
17584 originalColumn: mapping.originalColumn,
17585 name: name
17586 };
17587
17588 this.__generatedMappings.push(adjustedMapping);
17589 if (typeof adjustedMapping.originalLine === 'number') {
17590 this.__originalMappings.push(adjustedMapping);
17591 }
17592 }
17593 }
17594
17595 quickSort(this.__generatedMappings, util.compareByGeneratedPositionsDeflated);
17596 quickSort(this.__originalMappings, util.compareByOriginalPositions);
17597 };
17598
17599exports.IndexedSourceMapConsumer = IndexedSourceMapConsumer;
17600
17601},{"./array-set":103,"./base64-vlq":104,"./binary-search":106,"./quick-sort":108,"./util":112}],110:[function(_dereq_,module,exports){
17602/* -*- Mode: js; js-indent-level: 2; -*- */
17603/*
17604 * Copyright 2011 Mozilla Foundation and contributors
17605 * Licensed under the New BSD license. See LICENSE or:
17606 * http://opensource.org/licenses/BSD-3-Clause
17607 */
17608
17609var base64VLQ = _dereq_('./base64-vlq');
17610var util = _dereq_('./util');
17611var ArraySet = _dereq_('./array-set').ArraySet;
17612var MappingList = _dereq_('./mapping-list').MappingList;
17613
17614/**
17615 * An instance of the SourceMapGenerator represents a source map which is
17616 * being built incrementally. You may pass an object with the following
17617 * properties:
17618 *
17619 * - file: The filename of the generated source.
17620 * - sourceRoot: A root for all relative URLs in this source map.
17621 */
17622function SourceMapGenerator(aArgs) {
17623 if (!aArgs) {
17624 aArgs = {};
17625 }
17626 this._file = util.getArg(aArgs, 'file', null);
17627 this._sourceRoot = util.getArg(aArgs, 'sourceRoot', null);
17628 this._skipValidation = util.getArg(aArgs, 'skipValidation', false);
17629 this._sources = new ArraySet();
17630 this._names = new ArraySet();
17631 this._mappings = new MappingList();
17632 this._sourcesContents = null;
17633}
17634
17635SourceMapGenerator.prototype._version = 3;
17636
17637/**
17638 * Creates a new SourceMapGenerator based on a SourceMapConsumer
17639 *
17640 * @param aSourceMapConsumer The SourceMap.
17641 */
17642SourceMapGenerator.fromSourceMap =
17643 function SourceMapGenerator_fromSourceMap(aSourceMapConsumer) {
17644 var sourceRoot = aSourceMapConsumer.sourceRoot;
17645 var generator = new SourceMapGenerator({
17646 file: aSourceMapConsumer.file,
17647 sourceRoot: sourceRoot
17648 });
17649 aSourceMapConsumer.eachMapping(function (mapping) {
17650 var newMapping = {
17651 generated: {
17652 line: mapping.generatedLine,
17653 column: mapping.generatedColumn
17654 }
17655 };
17656
17657 if (mapping.source != null) {
17658 newMapping.source = mapping.source;
17659 if (sourceRoot != null) {
17660 newMapping.source = util.relative(sourceRoot, newMapping.source);
17661 }
17662
17663 newMapping.original = {
17664 line: mapping.originalLine,
17665 column: mapping.originalColumn
17666 };
17667
17668 if (mapping.name != null) {
17669 newMapping.name = mapping.name;
17670 }
17671 }
17672
17673 generator.addMapping(newMapping);
17674 });
17675 aSourceMapConsumer.sources.forEach(function (sourceFile) {
17676 var content = aSourceMapConsumer.sourceContentFor(sourceFile);
17677 if (content != null) {
17678 generator.setSourceContent(sourceFile, content);
17679 }
17680 });
17681 return generator;
17682 };
17683
17684/**
17685 * Add a single mapping from original source line and column to the generated
17686 * source's line and column for this source map being created. The mapping
17687 * object should have the following properties:
17688 *
17689 * - generated: An object with the generated line and column positions.
17690 * - original: An object with the original line and column positions.
17691 * - source: The original source file (relative to the sourceRoot).
17692 * - name: An optional original token name for this mapping.
17693 */
17694SourceMapGenerator.prototype.addMapping =
17695 function SourceMapGenerator_addMapping(aArgs) {
17696 var generated = util.getArg(aArgs, 'generated');
17697 var original = util.getArg(aArgs, 'original', null);
17698 var source = util.getArg(aArgs, 'source', null);
17699 var name = util.getArg(aArgs, 'name', null);
17700
17701 if (!this._skipValidation) {
17702 this._validateMapping(generated, original, source, name);
17703 }
17704
17705 if (source != null) {
17706 source = String(source);
17707 if (!this._sources.has(source)) {
17708 this._sources.add(source);
17709 }
17710 }
17711
17712 if (name != null) {
17713 name = String(name);
17714 if (!this._names.has(name)) {
17715 this._names.add(name);
17716 }
17717 }
17718
17719 this._mappings.add({
17720 generatedLine: generated.line,
17721 generatedColumn: generated.column,
17722 originalLine: original != null && original.line,
17723 originalColumn: original != null && original.column,
17724 source: source,
17725 name: name
17726 });
17727 };
17728
17729/**
17730 * Set the source content for a source file.
17731 */
17732SourceMapGenerator.prototype.setSourceContent =
17733 function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) {
17734 var source = aSourceFile;
17735 if (this._sourceRoot != null) {
17736 source = util.relative(this._sourceRoot, source);
17737 }
17738
17739 if (aSourceContent != null) {
17740 // Add the source content to the _sourcesContents map.
17741 // Create a new _sourcesContents map if the property is null.
17742 if (!this._sourcesContents) {
17743 this._sourcesContents = Object.create(null);
17744 }
17745 this._sourcesContents[util.toSetString(source)] = aSourceContent;
17746 } else if (this._sourcesContents) {
17747 // Remove the source file from the _sourcesContents map.
17748 // If the _sourcesContents map is empty, set the property to null.
17749 delete this._sourcesContents[util.toSetString(source)];
17750 if (Object.keys(this._sourcesContents).length === 0) {
17751 this._sourcesContents = null;
17752 }
17753 }
17754 };
17755
17756/**
17757 * Applies the mappings of a sub-source-map for a specific source file to the
17758 * source map being generated. Each mapping to the supplied source file is
17759 * rewritten using the supplied source map. Note: The resolution for the
17760 * resulting mappings is the minimium of this map and the supplied map.
17761 *
17762 * @param aSourceMapConsumer The source map to be applied.
17763 * @param aSourceFile Optional. The filename of the source file.
17764 * If omitted, SourceMapConsumer's file property will be used.
17765 * @param aSourceMapPath Optional. The dirname of the path to the source map
17766 * to be applied. If relative, it is relative to the SourceMapConsumer.
17767 * This parameter is needed when the two source maps aren't in the same
17768 * directory, and the source map to be applied contains relative source
17769 * paths. If so, those relative source paths need to be rewritten
17770 * relative to the SourceMapGenerator.
17771 */
17772SourceMapGenerator.prototype.applySourceMap =
17773 function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile, aSourceMapPath) {
17774 var sourceFile = aSourceFile;
17775 // If aSourceFile is omitted, we will use the file property of the SourceMap
17776 if (aSourceFile == null) {
17777 if (aSourceMapConsumer.file == null) {
17778 throw new Error(
17779 'SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, ' +
17780 'or the source map\'s "file" property. Both were omitted.'
17781 );
17782 }
17783 sourceFile = aSourceMapConsumer.file;
17784 }
17785 var sourceRoot = this._sourceRoot;
17786 // Make "sourceFile" relative if an absolute Url is passed.
17787 if (sourceRoot != null) {
17788 sourceFile = util.relative(sourceRoot, sourceFile);
17789 }
17790 // Applying the SourceMap can add and remove items from the sources and
17791 // the names array.
17792 var newSources = new ArraySet();
17793 var newNames = new ArraySet();
17794
17795 // Find mappings for the "sourceFile"
17796 this._mappings.unsortedForEach(function (mapping) {
17797 if (mapping.source === sourceFile && mapping.originalLine != null) {
17798 // Check if it can be mapped by the source map, then update the mapping.
17799 var original = aSourceMapConsumer.originalPositionFor({
17800 line: mapping.originalLine,
17801 column: mapping.originalColumn
17802 });
17803 if (original.source != null) {
17804 // Copy mapping
17805 mapping.source = original.source;
17806 if (aSourceMapPath != null) {
17807 mapping.source = util.join(aSourceMapPath, mapping.source)
17808 }
17809 if (sourceRoot != null) {
17810 mapping.source = util.relative(sourceRoot, mapping.source);
17811 }
17812 mapping.originalLine = original.line;
17813 mapping.originalColumn = original.column;
17814 if (original.name != null) {
17815 mapping.name = original.name;
17816 }
17817 }
17818 }
17819
17820 var source = mapping.source;
17821 if (source != null && !newSources.has(source)) {
17822 newSources.add(source);
17823 }
17824
17825 var name = mapping.name;
17826 if (name != null && !newNames.has(name)) {
17827 newNames.add(name);
17828 }
17829
17830 }, this);
17831 this._sources = newSources;
17832 this._names = newNames;
17833
17834 // Copy sourcesContents of applied map.
17835 aSourceMapConsumer.sources.forEach(function (sourceFile) {
17836 var content = aSourceMapConsumer.sourceContentFor(sourceFile);
17837 if (content != null) {
17838 if (aSourceMapPath != null) {
17839 sourceFile = util.join(aSourceMapPath, sourceFile);
17840 }
17841 if (sourceRoot != null) {
17842 sourceFile = util.relative(sourceRoot, sourceFile);
17843 }
17844 this.setSourceContent(sourceFile, content);
17845 }
17846 }, this);
17847 };
17848
17849/**
17850 * A mapping can have one of the three levels of data:
17851 *
17852 * 1. Just the generated position.
17853 * 2. The Generated position, original position, and original source.
17854 * 3. Generated and original position, original source, as well as a name
17855 * token.
17856 *
17857 * To maintain consistency, we validate that any new mapping being added falls
17858 * in to one of these categories.
17859 */
17860SourceMapGenerator.prototype._validateMapping =
17861 function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource,
17862 aName) {
17863 if (aGenerated && 'line' in aGenerated && 'column' in aGenerated
17864 && aGenerated.line > 0 && aGenerated.column >= 0
17865 && !aOriginal && !aSource && !aName) {
17866 // Case 1.
17867 return;
17868 }
17869 else if (aGenerated && 'line' in aGenerated && 'column' in aGenerated
17870 && aOriginal && 'line' in aOriginal && 'column' in aOriginal
17871 && aGenerated.line > 0 && aGenerated.column >= 0
17872 && aOriginal.line > 0 && aOriginal.column >= 0
17873 && aSource) {
17874 // Cases 2 and 3.
17875 return;
17876 }
17877 else {
17878 throw new Error('Invalid mapping: ' + JSON.stringify({
17879 generated: aGenerated,
17880 source: aSource,
17881 original: aOriginal,
17882 name: aName
17883 }));
17884 }
17885 };
17886
17887/**
17888 * Serialize the accumulated mappings in to the stream of base 64 VLQs
17889 * specified by the source map format.
17890 */
17891SourceMapGenerator.prototype._serializeMappings =
17892 function SourceMapGenerator_serializeMappings() {
17893 var previousGeneratedColumn = 0;
17894 var previousGeneratedLine = 1;
17895 var previousOriginalColumn = 0;
17896 var previousOriginalLine = 0;
17897 var previousName = 0;
17898 var previousSource = 0;
17899 var result = '';
17900 var next;
17901 var mapping;
17902 var nameIdx;
17903 var sourceIdx;
17904
17905 var mappings = this._mappings.toArray();
17906 for (var i = 0, len = mappings.length; i < len; i++) {
17907 mapping = mappings[i];
17908 next = ''
17909
17910 if (mapping.generatedLine !== previousGeneratedLine) {
17911 previousGeneratedColumn = 0;
17912 while (mapping.generatedLine !== previousGeneratedLine) {
17913 next += ';';
17914 previousGeneratedLine++;
17915 }
17916 }
17917 else {
17918 if (i > 0) {
17919 if (!util.compareByGeneratedPositionsInflated(mapping, mappings[i - 1])) {
17920 continue;
17921 }
17922 next += ',';
17923 }
17924 }
17925
17926 next += base64VLQ.encode(mapping.generatedColumn
17927 - previousGeneratedColumn);
17928 previousGeneratedColumn = mapping.generatedColumn;
17929
17930 if (mapping.source != null) {
17931 sourceIdx = this._sources.indexOf(mapping.source);
17932 next += base64VLQ.encode(sourceIdx - previousSource);
17933 previousSource = sourceIdx;
17934
17935 // lines are stored 0-based in SourceMap spec version 3
17936 next += base64VLQ.encode(mapping.originalLine - 1
17937 - previousOriginalLine);
17938 previousOriginalLine = mapping.originalLine - 1;
17939
17940 next += base64VLQ.encode(mapping.originalColumn
17941 - previousOriginalColumn);
17942 previousOriginalColumn = mapping.originalColumn;
17943
17944 if (mapping.name != null) {
17945 nameIdx = this._names.indexOf(mapping.name);
17946 next += base64VLQ.encode(nameIdx - previousName);
17947 previousName = nameIdx;
17948 }
17949 }
17950
17951 result += next;
17952 }
17953
17954 return result;
17955 };
17956
17957SourceMapGenerator.prototype._generateSourcesContent =
17958 function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) {
17959 return aSources.map(function (source) {
17960 if (!this._sourcesContents) {
17961 return null;
17962 }
17963 if (aSourceRoot != null) {
17964 source = util.relative(aSourceRoot, source);
17965 }
17966 var key = util.toSetString(source);
17967 return Object.prototype.hasOwnProperty.call(this._sourcesContents, key)
17968 ? this._sourcesContents[key]
17969 : null;
17970 }, this);
17971 };
17972
17973/**
17974 * Externalize the source map.
17975 */
17976SourceMapGenerator.prototype.toJSON =
17977 function SourceMapGenerator_toJSON() {
17978 var map = {
17979 version: this._version,
17980 sources: this._sources.toArray(),
17981 names: this._names.toArray(),
17982 mappings: this._serializeMappings()
17983 };
17984 if (this._file != null) {
17985 map.file = this._file;
17986 }
17987 if (this._sourceRoot != null) {
17988 map.sourceRoot = this._sourceRoot;
17989 }
17990 if (this._sourcesContents) {
17991 map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot);
17992 }
17993
17994 return map;
17995 };
17996
17997/**
17998 * Render the source map being generated to a string.
17999 */
18000SourceMapGenerator.prototype.toString =
18001 function SourceMapGenerator_toString() {
18002 return JSON.stringify(this.toJSON());
18003 };
18004
18005exports.SourceMapGenerator = SourceMapGenerator;
18006
18007},{"./array-set":103,"./base64-vlq":104,"./mapping-list":107,"./util":112}],111:[function(_dereq_,module,exports){
18008/* -*- Mode: js; js-indent-level: 2; -*- */
18009/*
18010 * Copyright 2011 Mozilla Foundation and contributors
18011 * Licensed under the New BSD license. See LICENSE or:
18012 * http://opensource.org/licenses/BSD-3-Clause
18013 */
18014
18015var SourceMapGenerator = _dereq_('./source-map-generator').SourceMapGenerator;
18016var util = _dereq_('./util');
18017
18018// Matches a Windows-style `\r\n` newline or a `\n` newline used by all other
18019// operating systems these days (capturing the result).
18020var REGEX_NEWLINE = /(\r?\n)/;
18021
18022// Newline character code for charCodeAt() comparisons
18023var NEWLINE_CODE = 10;
18024
18025// Private symbol for identifying `SourceNode`s when multiple versions of
18026// the source-map library are loaded. This MUST NOT CHANGE across
18027// versions!
18028var isSourceNode = "$$$isSourceNode$$$";
18029
18030/**
18031 * SourceNodes provide a way to abstract over interpolating/concatenating
18032 * snippets of generated JavaScript source code while maintaining the line and
18033 * column information associated with the original source code.
18034 *
18035 * @param aLine The original line number.
18036 * @param aColumn The original column number.
18037 * @param aSource The original source's filename.
18038 * @param aChunks Optional. An array of strings which are snippets of
18039 * generated JS, or other SourceNodes.
18040 * @param aName The original identifier.
18041 */
18042function SourceNode(aLine, aColumn, aSource, aChunks, aName) {
18043 this.children = [];
18044 this.sourceContents = {};
18045 this.line = aLine == null ? null : aLine;
18046 this.column = aColumn == null ? null : aColumn;
18047 this.source = aSource == null ? null : aSource;
18048 this.name = aName == null ? null : aName;
18049 this[isSourceNode] = true;
18050 if (aChunks != null) this.add(aChunks);
18051}
18052
18053/**
18054 * Creates a SourceNode from generated code and a SourceMapConsumer.
18055 *
18056 * @param aGeneratedCode The generated code
18057 * @param aSourceMapConsumer The SourceMap for the generated code
18058 * @param aRelativePath Optional. The path that relative sources in the
18059 * SourceMapConsumer should be relative to.
18060 */
18061SourceNode.fromStringWithSourceMap =
18062 function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer, aRelativePath) {
18063 // The SourceNode we want to fill with the generated code
18064 // and the SourceMap
18065 var node = new SourceNode();
18066
18067 // All even indices of this array are one line of the generated code,
18068 // while all odd indices are the newlines between two adjacent lines
18069 // (since `REGEX_NEWLINE` captures its match).
18070 // Processed fragments are removed from this array, by calling `shiftNextLine`.
18071 var remainingLines = aGeneratedCode.split(REGEX_NEWLINE);
18072 var shiftNextLine = function() {
18073 var lineContents = remainingLines.shift();
18074 // The last line of a file might not have a newline.
18075 var newLine = remainingLines.shift() || "";
18076 return lineContents + newLine;
18077 };
18078
18079 // We need to remember the position of "remainingLines"
18080 var lastGeneratedLine = 1, lastGeneratedColumn = 0;
18081
18082 // The generate SourceNodes we need a code range.
18083 // To extract it current and last mapping is used.
18084 // Here we store the last mapping.
18085 var lastMapping = null;
18086
18087 aSourceMapConsumer.eachMapping(function (mapping) {
18088 if (lastMapping !== null) {
18089 // We add the code from "lastMapping" to "mapping":
18090 // First check if there is a new line in between.
18091 if (lastGeneratedLine < mapping.generatedLine) {
18092 // Associate first line with "lastMapping"
18093 addMappingWithCode(lastMapping, shiftNextLine());
18094 lastGeneratedLine++;
18095 lastGeneratedColumn = 0;
18096 // The remaining code is added without mapping
18097 } else {
18098 // There is no new line in between.
18099 // Associate the code between "lastGeneratedColumn" and
18100 // "mapping.generatedColumn" with "lastMapping"
18101 var nextLine = remainingLines[0];
18102 var code = nextLine.substr(0, mapping.generatedColumn -
18103 lastGeneratedColumn);
18104 remainingLines[0] = nextLine.substr(mapping.generatedColumn -
18105 lastGeneratedColumn);
18106 lastGeneratedColumn = mapping.generatedColumn;
18107 addMappingWithCode(lastMapping, code);
18108 // No more remaining code, continue
18109 lastMapping = mapping;
18110 return;
18111 }
18112 }
18113 // We add the generated code until the first mapping
18114 // to the SourceNode without any mapping.
18115 // Each line is added as separate string.
18116 while (lastGeneratedLine < mapping.generatedLine) {
18117 node.add(shiftNextLine());
18118 lastGeneratedLine++;
18119 }
18120 if (lastGeneratedColumn < mapping.generatedColumn) {
18121 var nextLine = remainingLines[0];
18122 node.add(nextLine.substr(0, mapping.generatedColumn));
18123 remainingLines[0] = nextLine.substr(mapping.generatedColumn);
18124 lastGeneratedColumn = mapping.generatedColumn;
18125 }
18126 lastMapping = mapping;
18127 }, this);
18128 // We have processed all mappings.
18129 if (remainingLines.length > 0) {
18130 if (lastMapping) {
18131 // Associate the remaining code in the current line with "lastMapping"
18132 addMappingWithCode(lastMapping, shiftNextLine());
18133 }
18134 // and add the remaining lines without any mapping
18135 node.add(remainingLines.join(""));
18136 }
18137
18138 // Copy sourcesContent into SourceNode
18139 aSourceMapConsumer.sources.forEach(function (sourceFile) {
18140 var content = aSourceMapConsumer.sourceContentFor(sourceFile);
18141 if (content != null) {
18142 if (aRelativePath != null) {
18143 sourceFile = util.join(aRelativePath, sourceFile);
18144 }
18145 node.setSourceContent(sourceFile, content);
18146 }
18147 });
18148
18149 return node;
18150
18151 function addMappingWithCode(mapping, code) {
18152 if (mapping === null || mapping.source === undefined) {
18153 node.add(code);
18154 } else {
18155 var source = aRelativePath
18156 ? util.join(aRelativePath, mapping.source)
18157 : mapping.source;
18158 node.add(new SourceNode(mapping.originalLine,
18159 mapping.originalColumn,
18160 source,
18161 code,
18162 mapping.name));
18163 }
18164 }
18165 };
18166
18167/**
18168 * Add a chunk of generated JS to this source node.
18169 *
18170 * @param aChunk A string snippet of generated JS code, another instance of
18171 * SourceNode, or an array where each member is one of those things.
18172 */
18173SourceNode.prototype.add = function SourceNode_add(aChunk) {
18174 if (Array.isArray(aChunk)) {
18175 aChunk.forEach(function (chunk) {
18176 this.add(chunk);
18177 }, this);
18178 }
18179 else if (aChunk[isSourceNode] || typeof aChunk === "string") {
18180 if (aChunk) {
18181 this.children.push(aChunk);
18182 }
18183 }
18184 else {
18185 throw new TypeError(
18186 "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk
18187 );
18188 }
18189 return this;
18190};
18191
18192/**
18193 * Add a chunk of generated JS to the beginning of this source node.
18194 *
18195 * @param aChunk A string snippet of generated JS code, another instance of
18196 * SourceNode, or an array where each member is one of those things.
18197 */
18198SourceNode.prototype.prepend = function SourceNode_prepend(aChunk) {
18199 if (Array.isArray(aChunk)) {
18200 for (var i = aChunk.length-1; i >= 0; i--) {
18201 this.prepend(aChunk[i]);
18202 }
18203 }
18204 else if (aChunk[isSourceNode] || typeof aChunk === "string") {
18205 this.children.unshift(aChunk);
18206 }
18207 else {
18208 throw new TypeError(
18209 "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk
18210 );
18211 }
18212 return this;
18213};
18214
18215/**
18216 * Walk over the tree of JS snippets in this node and its children. The
18217 * walking function is called once for each snippet of JS and is passed that
18218 * snippet and the its original associated source's line/column location.
18219 *
18220 * @param aFn The traversal function.
18221 */
18222SourceNode.prototype.walk = function SourceNode_walk(aFn) {
18223 var chunk;
18224 for (var i = 0, len = this.children.length; i < len; i++) {
18225 chunk = this.children[i];
18226 if (chunk[isSourceNode]) {
18227 chunk.walk(aFn);
18228 }
18229 else {
18230 if (chunk !== '') {
18231 aFn(chunk, { source: this.source,
18232 line: this.line,
18233 column: this.column,
18234 name: this.name });
18235 }
18236 }
18237 }
18238};
18239
18240/**
18241 * Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between
18242 * each of `this.children`.
18243 *
18244 * @param aSep The separator.
18245 */
18246SourceNode.prototype.join = function SourceNode_join(aSep) {
18247 var newChildren;
18248 var i;
18249 var len = this.children.length;
18250 if (len > 0) {
18251 newChildren = [];
18252 for (i = 0; i < len-1; i++) {
18253 newChildren.push(this.children[i]);
18254 newChildren.push(aSep);
18255 }
18256 newChildren.push(this.children[i]);
18257 this.children = newChildren;
18258 }
18259 return this;
18260};
18261
18262/**
18263 * Call String.prototype.replace on the very right-most source snippet. Useful
18264 * for trimming whitespace from the end of a source node, etc.
18265 *
18266 * @param aPattern The pattern to replace.
18267 * @param aReplacement The thing to replace the pattern with.
18268 */
18269SourceNode.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) {
18270 var lastChild = this.children[this.children.length - 1];
18271 if (lastChild[isSourceNode]) {
18272 lastChild.replaceRight(aPattern, aReplacement);
18273 }
18274 else if (typeof lastChild === 'string') {
18275 this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement);
18276 }
18277 else {
18278 this.children.push(''.replace(aPattern, aReplacement));
18279 }
18280 return this;
18281};
18282
18283/**
18284 * Set the source content for a source file. This will be added to the SourceMapGenerator
18285 * in the sourcesContent field.
18286 *
18287 * @param aSourceFile The filename of the source file
18288 * @param aSourceContent The content of the source file
18289 */
18290SourceNode.prototype.setSourceContent =
18291 function SourceNode_setSourceContent(aSourceFile, aSourceContent) {
18292 this.sourceContents[util.toSetString(aSourceFile)] = aSourceContent;
18293 };
18294
18295/**
18296 * Walk over the tree of SourceNodes. The walking function is called for each
18297 * source file content and is passed the filename and source content.
18298 *
18299 * @param aFn The traversal function.
18300 */
18301SourceNode.prototype.walkSourceContents =
18302 function SourceNode_walkSourceContents(aFn) {
18303 for (var i = 0, len = this.children.length; i < len; i++) {
18304 if (this.children[i][isSourceNode]) {
18305 this.children[i].walkSourceContents(aFn);
18306 }
18307 }
18308
18309 var sources = Object.keys(this.sourceContents);
18310 for (var i = 0, len = sources.length; i < len; i++) {
18311 aFn(util.fromSetString(sources[i]), this.sourceContents[sources[i]]);
18312 }
18313 };
18314
18315/**
18316 * Return the string representation of this source node. Walks over the tree
18317 * and concatenates all the various snippets together to one string.
18318 */
18319SourceNode.prototype.toString = function SourceNode_toString() {
18320 var str = "";
18321 this.walk(function (chunk) {
18322 str += chunk;
18323 });
18324 return str;
18325};
18326
18327/**
18328 * Returns the string representation of this source node along with a source
18329 * map.
18330 */
18331SourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) {
18332 var generated = {
18333 code: "",
18334 line: 1,
18335 column: 0
18336 };
18337 var map = new SourceMapGenerator(aArgs);
18338 var sourceMappingActive = false;
18339 var lastOriginalSource = null;
18340 var lastOriginalLine = null;
18341 var lastOriginalColumn = null;
18342 var lastOriginalName = null;
18343 this.walk(function (chunk, original) {
18344 generated.code += chunk;
18345 if (original.source !== null
18346 && original.line !== null
18347 && original.column !== null) {
18348 if(lastOriginalSource !== original.source
18349 || lastOriginalLine !== original.line
18350 || lastOriginalColumn !== original.column
18351 || lastOriginalName !== original.name) {
18352 map.addMapping({
18353 source: original.source,
18354 original: {
18355 line: original.line,
18356 column: original.column
18357 },
18358 generated: {
18359 line: generated.line,
18360 column: generated.column
18361 },
18362 name: original.name
18363 });
18364 }
18365 lastOriginalSource = original.source;
18366 lastOriginalLine = original.line;
18367 lastOriginalColumn = original.column;
18368 lastOriginalName = original.name;
18369 sourceMappingActive = true;
18370 } else if (sourceMappingActive) {
18371 map.addMapping({
18372 generated: {
18373 line: generated.line,
18374 column: generated.column
18375 }
18376 });
18377 lastOriginalSource = null;
18378 sourceMappingActive = false;
18379 }
18380 for (var idx = 0, length = chunk.length; idx < length; idx++) {
18381 if (chunk.charCodeAt(idx) === NEWLINE_CODE) {
18382 generated.line++;
18383 generated.column = 0;
18384 // Mappings end at eol
18385 if (idx + 1 === length) {
18386 lastOriginalSource = null;
18387 sourceMappingActive = false;
18388 } else if (sourceMappingActive) {
18389 map.addMapping({
18390 source: original.source,
18391 original: {
18392 line: original.line,
18393 column: original.column
18394 },
18395 generated: {
18396 line: generated.line,
18397 column: generated.column
18398 },
18399 name: original.name
18400 });
18401 }
18402 } else {
18403 generated.column++;
18404 }
18405 }
18406 });
18407 this.walkSourceContents(function (sourceFile, sourceContent) {
18408 map.setSourceContent(sourceFile, sourceContent);
18409 });
18410
18411 return { code: generated.code, map: map };
18412};
18413
18414exports.SourceNode = SourceNode;
18415
18416},{"./source-map-generator":110,"./util":112}],112:[function(_dereq_,module,exports){
18417/* -*- Mode: js; js-indent-level: 2; -*- */
18418/*
18419 * Copyright 2011 Mozilla Foundation and contributors
18420 * Licensed under the New BSD license. See LICENSE or:
18421 * http://opensource.org/licenses/BSD-3-Clause
18422 */
18423
18424/**
18425 * This is a helper function for getting values from parameter/options
18426 * objects.
18427 *
18428 * @param args The object we are extracting values from
18429 * @param name The name of the property we are getting.
18430 * @param defaultValue An optional value to return if the property is missing
18431 * from the object. If this is not specified and the property is missing, an
18432 * error will be thrown.
18433 */
18434function getArg(aArgs, aName, aDefaultValue) {
18435 if (aName in aArgs) {
18436 return aArgs[aName];
18437 } else if (arguments.length === 3) {
18438 return aDefaultValue;
18439 } else {
18440 throw new Error('"' + aName + '" is a required argument.');
18441 }
18442}
18443exports.getArg = getArg;
18444
18445var urlRegexp = /^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.]*)(?::(\d+))?(\S*)$/;
18446var dataUrlRegexp = /^data:.+\,.+$/;
18447
18448function urlParse(aUrl) {
18449 var match = aUrl.match(urlRegexp);
18450 if (!match) {
18451 return null;
18452 }
18453 return {
18454 scheme: match[1],
18455 auth: match[2],
18456 host: match[3],
18457 port: match[4],
18458 path: match[5]
18459 };
18460}
18461exports.urlParse = urlParse;
18462
18463function urlGenerate(aParsedUrl) {
18464 var url = '';
18465 if (aParsedUrl.scheme) {
18466 url += aParsedUrl.scheme + ':';
18467 }
18468 url += '//';
18469 if (aParsedUrl.auth) {
18470 url += aParsedUrl.auth + '@';
18471 }
18472 if (aParsedUrl.host) {
18473 url += aParsedUrl.host;
18474 }
18475 if (aParsedUrl.port) {
18476 url += ":" + aParsedUrl.port
18477 }
18478 if (aParsedUrl.path) {
18479 url += aParsedUrl.path;
18480 }
18481 return url;
18482}
18483exports.urlGenerate = urlGenerate;
18484
18485/**
18486 * Normalizes a path, or the path portion of a URL:
18487 *
18488 * - Replaces consecutive slashes with one slash.
18489 * - Removes unnecessary '.' parts.
18490 * - Removes unnecessary '<dir>/..' parts.
18491 *
18492 * Based on code in the Node.js 'path' core module.
18493 *
18494 * @param aPath The path or url to normalize.
18495 */
18496function normalize(aPath) {
18497 var path = aPath;
18498 var url = urlParse(aPath);
18499 if (url) {
18500 if (!url.path) {
18501 return aPath;
18502 }
18503 path = url.path;
18504 }
18505 var isAbsolute = exports.isAbsolute(path);
18506
18507 var parts = path.split(/\/+/);
18508 for (var part, up = 0, i = parts.length - 1; i >= 0; i--) {
18509 part = parts[i];
18510 if (part === '.') {
18511 parts.splice(i, 1);
18512 } else if (part === '..') {
18513 up++;
18514 } else if (up > 0) {
18515 if (part === '') {
18516 // The first part is blank if the path is absolute. Trying to go
18517 // above the root is a no-op. Therefore we can remove all '..' parts
18518 // directly after the root.
18519 parts.splice(i + 1, up);
18520 up = 0;
18521 } else {
18522 parts.splice(i, 2);
18523 up--;
18524 }
18525 }
18526 }
18527 path = parts.join('/');
18528
18529 if (path === '') {
18530 path = isAbsolute ? '/' : '.';
18531 }
18532
18533 if (url) {
18534 url.path = path;
18535 return urlGenerate(url);
18536 }
18537 return path;
18538}
18539exports.normalize = normalize;
18540
18541/**
18542 * Joins two paths/URLs.
18543 *
18544 * @param aRoot The root path or URL.
18545 * @param aPath The path or URL to be joined with the root.
18546 *
18547 * - If aPath is a URL or a data URI, aPath is returned, unless aPath is a
18548 * scheme-relative URL: Then the scheme of aRoot, if any, is prepended
18549 * first.
18550 * - Otherwise aPath is a path. If aRoot is a URL, then its path portion
18551 * is updated with the result and aRoot is returned. Otherwise the result
18552 * is returned.
18553 * - If aPath is absolute, the result is aPath.
18554 * - Otherwise the two paths are joined with a slash.
18555 * - Joining for example 'http://' and 'www.example.com' is also supported.
18556 */
18557function join(aRoot, aPath) {
18558 if (aRoot === "") {
18559 aRoot = ".";
18560 }
18561 if (aPath === "") {
18562 aPath = ".";
18563 }
18564 var aPathUrl = urlParse(aPath);
18565 var aRootUrl = urlParse(aRoot);
18566 if (aRootUrl) {
18567 aRoot = aRootUrl.path || '/';
18568 }
18569
18570 // `join(foo, '//www.example.org')`
18571 if (aPathUrl && !aPathUrl.scheme) {
18572 if (aRootUrl) {
18573 aPathUrl.scheme = aRootUrl.scheme;
18574 }
18575 return urlGenerate(aPathUrl);
18576 }
18577
18578 if (aPathUrl || aPath.match(dataUrlRegexp)) {
18579 return aPath;
18580 }
18581
18582 // `join('http://', 'www.example.com')`
18583 if (aRootUrl && !aRootUrl.host && !aRootUrl.path) {
18584 aRootUrl.host = aPath;
18585 return urlGenerate(aRootUrl);
18586 }
18587
18588 var joined = aPath.charAt(0) === '/'
18589 ? aPath
18590 : normalize(aRoot.replace(/\/+$/, '') + '/' + aPath);
18591
18592 if (aRootUrl) {
18593 aRootUrl.path = joined;
18594 return urlGenerate(aRootUrl);
18595 }
18596 return joined;
18597}
18598exports.join = join;
18599
18600exports.isAbsolute = function (aPath) {
18601 return aPath.charAt(0) === '/' || !!aPath.match(urlRegexp);
18602};
18603
18604/**
18605 * Make a path relative to a URL or another path.
18606 *
18607 * @param aRoot The root path or URL.
18608 * @param aPath The path or URL to be made relative to aRoot.
18609 */
18610function relative(aRoot, aPath) {
18611 if (aRoot === "") {
18612 aRoot = ".";
18613 }
18614
18615 aRoot = aRoot.replace(/\/$/, '');
18616
18617 // It is possible for the path to be above the root. In this case, simply
18618 // checking whether the root is a prefix of the path won't work. Instead, we
18619 // need to remove components from the root one by one, until either we find
18620 // a prefix that fits, or we run out of components to remove.
18621 var level = 0;
18622 while (aPath.indexOf(aRoot + '/') !== 0) {
18623 var index = aRoot.lastIndexOf("/");
18624 if (index < 0) {
18625 return aPath;
18626 }
18627
18628 // If the only part of the root that is left is the scheme (i.e. http://,
18629 // file:///, etc.), one or more slashes (/), or simply nothing at all, we
18630 // have exhausted all components, so the path is not relative to the root.
18631 aRoot = aRoot.slice(0, index);
18632 if (aRoot.match(/^([^\/]+:\/)?\/*$/)) {
18633 return aPath;
18634 }
18635
18636 ++level;
18637 }
18638
18639 // Make sure we add a "../" for each component we removed from the root.
18640 return Array(level + 1).join("../") + aPath.substr(aRoot.length + 1);
18641}
18642exports.relative = relative;
18643
18644var supportsNullProto = (function () {
18645 var obj = Object.create(null);
18646 return !('__proto__' in obj);
18647}());
18648
18649function identity (s) {
18650 return s;
18651}
18652
18653/**
18654 * Because behavior goes wacky when you set `__proto__` on objects, we
18655 * have to prefix all the strings in our set with an arbitrary character.
18656 *
18657 * See https://github.com/mozilla/source-map/pull/31 and
18658 * https://github.com/mozilla/source-map/issues/30
18659 *
18660 * @param String aStr
18661 */
18662function toSetString(aStr) {
18663 if (isProtoString(aStr)) {
18664 return '$' + aStr;
18665 }
18666
18667 return aStr;
18668}
18669exports.toSetString = supportsNullProto ? identity : toSetString;
18670
18671function fromSetString(aStr) {
18672 if (isProtoString(aStr)) {
18673 return aStr.slice(1);
18674 }
18675
18676 return aStr;
18677}
18678exports.fromSetString = supportsNullProto ? identity : fromSetString;
18679
18680function isProtoString(s) {
18681 if (!s) {
18682 return false;
18683 }
18684
18685 var length = s.length;
18686
18687 if (length < 9 /* "__proto__".length */) {
18688 return false;
18689 }
18690
18691 if (s.charCodeAt(length - 1) !== 95 /* '_' */ ||
18692 s.charCodeAt(length - 2) !== 95 /* '_' */ ||
18693 s.charCodeAt(length - 3) !== 111 /* 'o' */ ||
18694 s.charCodeAt(length - 4) !== 116 /* 't' */ ||
18695 s.charCodeAt(length - 5) !== 111 /* 'o' */ ||
18696 s.charCodeAt(length - 6) !== 114 /* 'r' */ ||
18697 s.charCodeAt(length - 7) !== 112 /* 'p' */ ||
18698 s.charCodeAt(length - 8) !== 95 /* '_' */ ||
18699 s.charCodeAt(length - 9) !== 95 /* '_' */) {
18700 return false;
18701 }
18702
18703 for (var i = length - 10; i >= 0; i--) {
18704 if (s.charCodeAt(i) !== 36 /* '$' */) {
18705 return false;
18706 }
18707 }
18708
18709 return true;
18710}
18711
18712/**
18713 * Comparator between two mappings where the original positions are compared.
18714 *
18715 * Optionally pass in `true` as `onlyCompareGenerated` to consider two
18716 * mappings with the same original source/line/column, but different generated
18717 * line and column the same. Useful when searching for a mapping with a
18718 * stubbed out mapping.
18719 */
18720function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) {
18721 var cmp = mappingA.source - mappingB.source;
18722 if (cmp !== 0) {
18723 return cmp;
18724 }
18725
18726 cmp = mappingA.originalLine - mappingB.originalLine;
18727 if (cmp !== 0) {
18728 return cmp;
18729 }
18730
18731 cmp = mappingA.originalColumn - mappingB.originalColumn;
18732 if (cmp !== 0 || onlyCompareOriginal) {
18733 return cmp;
18734 }
18735
18736 cmp = mappingA.generatedColumn - mappingB.generatedColumn;
18737 if (cmp !== 0) {
18738 return cmp;
18739 }
18740
18741 cmp = mappingA.generatedLine - mappingB.generatedLine;
18742 if (cmp !== 0) {
18743 return cmp;
18744 }
18745
18746 return mappingA.name - mappingB.name;
18747}
18748exports.compareByOriginalPositions = compareByOriginalPositions;
18749
18750/**
18751 * Comparator between two mappings with deflated source and name indices where
18752 * the generated positions are compared.
18753 *
18754 * Optionally pass in `true` as `onlyCompareGenerated` to consider two
18755 * mappings with the same generated line and column, but different
18756 * source/name/original line and column the same. Useful when searching for a
18757 * mapping with a stubbed out mapping.
18758 */
18759function compareByGeneratedPositionsDeflated(mappingA, mappingB, onlyCompareGenerated) {
18760 var cmp = mappingA.generatedLine - mappingB.generatedLine;
18761 if (cmp !== 0) {
18762 return cmp;
18763 }
18764
18765 cmp = mappingA.generatedColumn - mappingB.generatedColumn;
18766 if (cmp !== 0 || onlyCompareGenerated) {
18767 return cmp;
18768 }
18769
18770 cmp = mappingA.source - mappingB.source;
18771 if (cmp !== 0) {
18772 return cmp;
18773 }
18774
18775 cmp = mappingA.originalLine - mappingB.originalLine;
18776 if (cmp !== 0) {
18777 return cmp;
18778 }
18779
18780 cmp = mappingA.originalColumn - mappingB.originalColumn;
18781 if (cmp !== 0) {
18782 return cmp;
18783 }
18784
18785 return mappingA.name - mappingB.name;
18786}
18787exports.compareByGeneratedPositionsDeflated = compareByGeneratedPositionsDeflated;
18788
18789function strcmp(aStr1, aStr2) {
18790 if (aStr1 === aStr2) {
18791 return 0;
18792 }
18793
18794 if (aStr1 > aStr2) {
18795 return 1;
18796 }
18797
18798 return -1;
18799}
18800
18801/**
18802 * Comparator between two mappings with inflated source and name strings where
18803 * the generated positions are compared.
18804 */
18805function compareByGeneratedPositionsInflated(mappingA, mappingB) {
18806 var cmp = mappingA.generatedLine - mappingB.generatedLine;
18807 if (cmp !== 0) {
18808 return cmp;
18809 }
18810
18811 cmp = mappingA.generatedColumn - mappingB.generatedColumn;
18812 if (cmp !== 0) {
18813 return cmp;
18814 }
18815
18816 cmp = strcmp(mappingA.source, mappingB.source);
18817 if (cmp !== 0) {
18818 return cmp;
18819 }
18820
18821 cmp = mappingA.originalLine - mappingB.originalLine;
18822 if (cmp !== 0) {
18823 return cmp;
18824 }
18825
18826 cmp = mappingA.originalColumn - mappingB.originalColumn;
18827 if (cmp !== 0) {
18828 return cmp;
18829 }
18830
18831 return strcmp(mappingA.name, mappingB.name);
18832}
18833exports.compareByGeneratedPositionsInflated = compareByGeneratedPositionsInflated;
18834
18835},{}],113:[function(_dereq_,module,exports){
18836/*
18837 * Copyright 2009-2011 Mozilla Foundation and contributors
18838 * Licensed under the New BSD license. See LICENSE.txt or:
18839 * http://opensource.org/licenses/BSD-3-Clause
18840 */
18841exports.SourceMapGenerator = _dereq_('./lib/source-map-generator').SourceMapGenerator;
18842exports.SourceMapConsumer = _dereq_('./lib/source-map-consumer').SourceMapConsumer;
18843exports.SourceNode = _dereq_('./lib/source-node').SourceNode;
18844
18845},{"./lib/source-map-consumer":109,"./lib/source-map-generator":110,"./lib/source-node":111}],114:[function(_dereq_,module,exports){
18846/**
18847 * type-name - Just a reasonable typeof
18848 *
18849 * https://github.com/twada/type-name
18850 *
18851 * Copyright (c) 2014-2016 Takuto Wada
18852 * Licensed under the MIT license.
18853 * http://twada.mit-license.org/2014-2016
18854 */
18855'use strict';
18856
18857var toStr = Object.prototype.toString;
18858
18859function funcName (f) {
18860 return f.name ? f.name : /^\s*function\s*([^\(]*)/im.exec(f.toString())[1];
18861}
18862
18863function ctorName (obj) {
18864 var strName = toStr.call(obj).slice(8, -1);
18865 if ((strName === 'Object' || strName === 'Error') && obj.constructor) {
18866 return funcName(obj.constructor);
18867 }
18868 return strName;
18869}
18870
18871function typeName (val) {
18872 var type;
18873 if (val === null) {
18874 return 'null';
18875 }
18876 type = typeof(val);
18877 if (type === 'object') {
18878 return ctorName(val);
18879 }
18880 return type;
18881}
18882
18883module.exports = typeName;
18884
18885},{}],115:[function(_dereq_,module,exports){
18886module.exports = extend
18887
18888var hasOwnProperty = Object.prototype.hasOwnProperty;
18889
18890function extend() {
18891 var target = {}
18892
18893 for (var i = 0; i < arguments.length; i++) {
18894 var source = arguments[i]
18895
18896 for (var key in source) {
18897 if (hasOwnProperty.call(source, key)) {
18898 target[key] = source[key]
18899 }
18900 }
18901 }
18902
18903 return target
18904}
18905
18906},{}]},{},[1])(1)
18907});
\No newline at end of file