Completed
Pull Request — master (#11)
by Anton
02:51
created

public/js/vendor/JSXTransformer.js   F

Complexity

Total Complexity 2868
Complexity/F 3.61

Size

Lines of Code 15917
Function Count 795

Duplication

Duplicated Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 0
c 1
b 0
f 0
nc 0
dl 0
loc 15917
rs 2.4
wmc 2868
mnd 9
bc 2237
fnc 795
bpm 2.8138
cpm 3.6075
noi 383

How to fix   Complexity   

Complexity

Complex classes like public/js/vendor/JSXTransformer.js often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

1
/**
2
 * JSXTransformer v0.13.3
3
 */
4
(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.JSXTransformer = 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){
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
Bug introduced by
The variable define seems to be never declared. If this is a global, consider adding a /** global: define */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
Bug introduced by
The variable self seems to be never declared. If this is a global, consider adding a /** global: self */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
Comprehensibility introduced by
Usage of the sequence operator is discouraged, since it may lead to obfuscated code.

The sequence or comma operator allows the inclusion of multiple expressions where only is permitted. The result of the sequence is the value of the last expression.

This operator is most often used in for statements.

Used in another places it can make code hard to read, especially when people do not realize it even exists as a seperate operator.

This check looks for usage of the sequence operator in locations where it is not necessary and could be replaced by a series of expressions or statements.

var a,b,c;

a = 1, b = 1,  c= 3;

could just as well be written as:

var a,b,c;

a = 1;
b = 1;
c = 3;

To learn more about the sequence operator, please refer to the MDN.

Loading history...
Unused Code introduced by
The variable module seems to be never used. Consider removing it.
Loading history...
5
/**
6
 * Copyright 2013-2015, Facebook, Inc.
7
 * All rights reserved.
8
 *
9
 * This source code is licensed under the BSD-style license found in the
10
 * LICENSE file in the root directory of this source tree. An additional grant
11
 * of patent rights can be found in the PATENTS file in the same directory.
12
 */
13
/* jshint browser: true */
14
/* jslint evil: true */
15
/*eslint-disable no-eval */
16
/*eslint-disable block-scoped-var */
17
18
'use strict';
19
20
var ReactTools = _dereq_('../main');
21
var inlineSourceMap = _dereq_('./inline-source-map');
22
23
var headEl;
24
var dummyAnchor;
25
var inlineScriptCount = 0;
26
27
// The source-map library relies on Object.defineProperty, but IE8 doesn't
28
// support it fully even with es5-sham. Indeed, es5-sham's defineProperty
29
// throws when Object.prototype.__defineGetter__ is missing, so we skip building
30
// the source map in that case.
31
var supportsAccessors = Object.prototype.hasOwnProperty('__defineGetter__');
32
33
/**
34
 * Run provided code through jstransform.
35
 *
36
 * @param {string} source Original source code
37
 * @param {object?} options Options to pass to jstransform
38
 * @return {object} object as returned from jstransform
39
 */
40
function transformReact(source, options) {
41
  options = options || {};
42
43
  // Force the sourcemaps option manually. We don't want to use it if it will
44
  // break (see above note about supportsAccessors). We'll only override the
45
  // value here if sourceMap was specified and is truthy. This guarantees that
46
  // we won't override any user intent (since this method is exposed publicly).
47
  if (options.sourceMap) {
48
    options.sourceMap = supportsAccessors;
49
  }
50
51
  // Otherwise just pass all options straight through to react-tools.
52
  return ReactTools.transformWithDetails(source, options);
53
}
54
55
/**
56
 * Eval provided source after transforming it.
57
 *
58
 * @param {string} source Original source code
59
 * @param {object?} options Options to pass to jstransform
60
 */
61
function exec(source, options) {
62
  return eval(transformReact(source, options).code);
0 ignored issues
show
Security Performance introduced by
Calls to eval are slow and potentially dangerous, especially on untrusted code. Please consider whether there is another way to achieve your goal.
Loading history...
63
}
64
65
/**
66
 * This method returns a nicely formated line of code pointing to the exact
67
 * location of the error `e`. The line is limited in size so big lines of code
68
 * are also shown in a readable way.
69
 *
70
 * Example:
71
 * ... x', overflow:'scroll'}} id={} onScroll={this.scroll} class=" ...
72
 * ^
73
 *
74
 * @param {string} code The full string of code
75
 * @param {Error} e The error being thrown
76
 * @return {string} formatted message
77
 * @internal
78
 */
79
function createSourceCodeErrorMessage(code, e) {
80
  var sourceLines = code.split('\n');
81
  // e.lineNumber is non-standard so we can't depend on its availability. If
82
  // we're in a browser where it isn't supported, don't even bother trying to
83
  // format anything. We may also hit a case where the line number is reported
84
  // incorrectly and is outside the bounds of the actual code. Handle that too.
85
  if (!e.lineNumber || e.lineNumber > sourceLines.length) {
86
    return '';
87
  }
88
  var erroneousLine = sourceLines[e.lineNumber - 1];
89
90
  // Removes any leading indenting spaces and gets the number of
91
  // chars indenting the `erroneousLine`
92
  var indentation = 0;
93
  erroneousLine = erroneousLine.replace(/^\s+/, function(leadingSpaces) {
94
    indentation = leadingSpaces.length;
95
    return '';
96
  });
97
98
  // Defines the number of characters that are going to show
99
  // before and after the erroneous code
100
  var LIMIT = 30;
101
  var errorColumn = e.column - indentation;
102
103
  if (errorColumn > LIMIT) {
104
    erroneousLine = '... ' + erroneousLine.slice(errorColumn - LIMIT);
105
    errorColumn = 4 + LIMIT;
106
  }
107
  if (erroneousLine.length - errorColumn > LIMIT) {
108
    erroneousLine = erroneousLine.slice(0, errorColumn + LIMIT) + ' ...';
109
  }
110
  var message = '\n\n' + erroneousLine + '\n';
111
  message += new Array(errorColumn - 1).join(' ') + '^';
112
  return message;
113
}
114
115
/**
116
 * Actually transform the code.
117
 *
118
 * @param {string} code
119
 * @param {string?} url
120
 * @param {object?} options
121
 * @return {string} The transformed code.
122
 * @internal
123
 */
124
function transformCode(code, url, options) {
125
  try {
126
    var transformed = transformReact(code, options);
127
  } catch(e) {
128
    e.message += '\n    at ';
129
    if (url) {
130
      if ('fileName' in e) {
131
        // We set `fileName` if it's supported by this error object and
132
        // a `url` was provided.
133
        // The error will correctly point to `url` in Firefox.
134
        e.fileName = url;
135
      }
136
      e.message += url + ':' + e.lineNumber + ':' + e.columnNumber;
137
    } else {
138
      e.message += location.href;
139
    }
140
    e.message += createSourceCodeErrorMessage(code, e);
141
    throw e;
142
  }
143
144
  if (!transformed.sourceMap) {
145
    return transformed.code;
146
  }
147
148
  var source;
149
  if (url == null) {
150
    source = 'Inline JSX script';
151
    inlineScriptCount++;
152
    if (inlineScriptCount > 1) {
153
      source += ' (' + inlineScriptCount + ')';
154
    }
155
  } else if (dummyAnchor) {
156
    // Firefox has problems when the sourcemap source is a proper URL with a
157
    // protocol and hostname, so use the pathname. We could use just the
158
    // filename, but hopefully using the full path will prevent potential
159
    // issues where the same filename exists in multiple directories.
160
    dummyAnchor.href = url;
161
    source = dummyAnchor.pathname.substr(1);
162
  }
163
164
  return (
165
    transformed.code +
166
    '\n' +
167
    inlineSourceMap(transformed.sourceMap, code, source)
0 ignored issues
show
Bug introduced by
The variable source does not seem to be initialized in case dummyAnchor on line 155 is false. Are you sure the function inlineSourceMap handles undefined variables?
Loading history...
168
  );
169
}
170
171
172
/**
173
 * Appends a script element at the end of the <head> with the content of code,
174
 * after transforming it.
175
 *
176
 * @param {string} code The original source code
177
 * @param {string?} url Where the code came from. null if inline
178
 * @param {object?} options Options to pass to jstransform
179
 * @internal
180
 */
181
function run(code, url, options) {
182
  var scriptEl = document.createElement('script');
183
  scriptEl.text = transformCode(code, url, options);
184
  headEl.appendChild(scriptEl);
185
}
186
187
/**
188
 * Load script from the provided url and pass the content to the callback.
189
 *
190
 * @param {string} url The location of the script src
191
 * @param {function} callback Function to call with the content of url
0 ignored issues
show
Documentation introduced by
The parameter callback does not exist. Did you maybe forget to remove this comment?
Loading history...
192
 * @internal
193
 */
194
function load(url, successCallback, errorCallback) {
195
  var xhr;
196
  xhr = window.ActiveXObject ? new window.ActiveXObject('Microsoft.XMLHTTP')
197
                             : new XMLHttpRequest();
0 ignored issues
show
Bug introduced by
The variable XMLHttpRequest seems to be never declared. If this is a global, consider adding a /** global: XMLHttpRequest */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
198
199
  // async, however scripts will be executed in the order they are in the
200
  // DOM to mirror normal script loading.
201
  xhr.open('GET', url, true);
202
  if ('overrideMimeType' in xhr) {
203
    xhr.overrideMimeType('text/plain');
204
  }
205
  xhr.onreadystatechange = function() {
206
    if (xhr.readyState === 4) {
207
      if (xhr.status === 0 || xhr.status === 200) {
208
        successCallback(xhr.responseText);
209
      } else {
210
        errorCallback();
211
        throw new Error('Could not load ' + url);
212
      }
213
    }
214
  };
215
  return xhr.send(null);
216
}
217
218
/**
219
 * Loop over provided script tags and get the content, via innerHTML if an
220
 * inline script, or by using XHR. Transforms are applied if needed. The scripts
221
 * are executed in the order they are found on the page.
222
 *
223
 * @param {array} scripts The <script> elements to load and run.
224
 * @internal
225
 */
226
function loadScripts(scripts) {
227
  var result = [];
228
  var count = scripts.length;
229
230
  function check() {
231
    var script, i;
232
233
    for (i = 0; i < count; i++) {
234
      script = result[i];
235
236
      if (script.loaded && !script.executed) {
237
        script.executed = true;
238
        run(script.content, script.url, script.options);
239
      } else if (!script.loaded && !script.error && !script.async) {
240
        break;
241
      }
242
    }
243
  }
244
245
  scripts.forEach(function(script, i) {
246
    var options = {
247
      // @philix: sourceMap support breaks r.js optimization. Leave it off by default
248
      sourceMap: false
249
    };
250
    if (/;harmony=true(;|$)/.test(script.type)) {
251
      options.harmony = true;
252
    }
253
    if (/;stripTypes=true(;|$)/.test(script.type)) {
254
      options.stripTypes = true;
255
    }
256
257
    // script.async is always true for non-javascript script tags
258
    var async = script.hasAttribute('async');
259
260
    if (script.src) {
261
      result[i] = {
262
        async: async,
263
        error: false,
264
        executed: false,
265
        content: null,
266
        loaded: false,
267
        url: script.src,
268
        options: options
269
      };
270
271
      load(script.src, function(content) {
272
        result[i].loaded = true;
273
        result[i].content = content;
274
        check();
275
      }, function() {
276
        result[i].error = true;
277
        check();
278
      });
279
    } else {
280
      result[i] = {
281
        async: async,
282
        error: false,
283
        executed: false,
284
        content: script.innerHTML,
285
        loaded: true,
286
        url: null,
287
        options: options
288
      };
289
    }
290
  });
291
292
  check();
293
}
294
295
/**
296
 * Find and run all script tags with type="text/jsx".
297
 *
298
 * @internal
299
 */
300
function runScripts() {
301
  var scripts = document.getElementsByTagName('script');
302
303
  // Array.prototype.slice cannot be used on NodeList on IE8
304
  var jsxScripts = [];
305
  for (var i = 0; i < scripts.length; i++) {
306
    if (/^text\/jsx(;|$)/.test(scripts.item(i).type)) {
307
      jsxScripts.push(scripts.item(i));
308
    }
309
  }
310
311
  if (jsxScripts.length < 1) {
312
    return;
313
  }
314
315
  console.warn(
316
    'You are using the in-browser JSX transformer. Be sure to precompile ' +
317
    'your JSX for production - ' +
318
    'http://facebook.github.io/react/docs/tooling-integration.html#jsx'
319
  );
320
321
  loadScripts(jsxScripts);
322
}
323
324
// Listen for load event if we're in a browser and then kick off finding and
325
// running of scripts.
326
if (typeof window !== 'undefined' && window !== null) {
327
  headEl = document.getElementsByTagName('head')[0];
328
  dummyAnchor = document.createElement('a');
329
330
  if (window.addEventListener) {
331
    window.addEventListener('DOMContentLoaded', runScripts, false);
332
  } else {
333
    window.attachEvent('onload', runScripts);
334
  }
335
}
336
337
module.exports = {
338
  transform: transformReact,
339
  exec: exec
340
};
341
342
},{"../main":2,"./inline-source-map":41}],2:[function(_dereq_,module,exports){
343
/**
344
 * Copyright 2013-2015, Facebook, Inc.
345
 * All rights reserved.
346
 *
347
 * This source code is licensed under the BSD-style license found in the
348
 * LICENSE file in the root directory of this source tree. An additional grant
349
 * of patent rights can be found in the PATENTS file in the same directory.
350
 */
351
352
'use strict';
353
/*eslint-disable no-undef*/
354
var visitors = _dereq_('./vendor/fbtransform/visitors');
355
var transform = _dereq_('jstransform').transform;
356
var typesSyntax = _dereq_('jstransform/visitors/type-syntax');
357
var inlineSourceMap = _dereq_('./vendor/inline-source-map');
358
359
module.exports = {
360
  transform: function(input, options) {
361
    options = processOptions(options);
362
    var output = innerTransform(input, options);
363
    var result = output.code;
364
    if (options.sourceMap) {
365
      var map = inlineSourceMap(
366
        output.sourceMap,
367
        input,
368
        options.filename
369
      );
370
      result += '\n' + map;
371
    }
372
    return result;
373
  },
374
  transformWithDetails: function(input, options) {
375
    options = processOptions(options);
376
    var output = innerTransform(input, options);
377
    var result = {};
378
    result.code = output.code;
379
    if (options.sourceMap) {
380
      result.sourceMap = output.sourceMap.toJSON();
381
    }
382
    if (options.filename) {
383
      result.sourceMap.sources = [options.filename];
384
    }
385
    return result;
386
  }
387
};
388
389
/**
390
 * Only copy the values that we need. We'll do some preprocessing to account for
391
 * converting command line flags to options that jstransform can actually use.
392
 */
393
function processOptions(opts) {
394
  opts = opts || {};
395
  var options = {};
396
397
  options.harmony = opts.harmony;
398
  options.stripTypes = opts.stripTypes;
399
  options.sourceMap = opts.sourceMap;
400
  options.filename = opts.sourceFilename;
401
402
  if (opts.es6module) {
403
    options.sourceType = 'module';
404
  }
405
  if (opts.nonStrictEs6module) {
406
    options.sourceType = 'nonStrictModule';
407
  }
408
409
  // Instead of doing any fancy validation, only look for 'es3'. If we have
410
  // that, then use it. Otherwise use 'es5'.
411
  options.es3 = opts.target === 'es3';
412
  options.es5 = !options.es3;
413
414
  return options;
415
}
416
417
function innerTransform(input, options) {
418
  var visitorSets = ['react'];
419
  if (options.harmony) {
420
    visitorSets.push('harmony');
421
  }
422
423
  if (options.es3) {
424
    visitorSets.push('es3');
425
  }
426
427
  if (options.stripTypes) {
428
    // Stripping types needs to happen before the other transforms
429
    // unfortunately, due to bad interactions. For example,
430
    // es6-rest-param-visitors conflict with stripping rest param type
431
    // annotation
432
    input = transform(typesSyntax.visitorList, input, options).code;
433
  }
434
435
  var visitorList = visitors.getVisitorsBySet(visitorSets);
436
  return transform(visitorList, input, options);
437
}
438
439
},{"./vendor/fbtransform/visitors":40,"./vendor/inline-source-map":41,"jstransform":22,"jstransform/visitors/type-syntax":36}],3:[function(_dereq_,module,exports){
440
/*!
441
 * The buffer module from node.js, for the browser.
442
 *
443
 * @author   Feross Aboukhadijeh <[email protected]> <http://feross.org>
444
 * @license  MIT
445
 */
446
447
var base64 = _dereq_('base64-js')
448
var ieee754 = _dereq_('ieee754')
449
var isArray = _dereq_('is-array')
450
451
exports.Buffer = Buffer
452
exports.SlowBuffer = SlowBuffer
453
exports.INSPECT_MAX_BYTES = 50
454
Buffer.poolSize = 8192 // not used by this implementation
455
456
var kMaxLength = 0x3fffffff
457
var rootParent = {}
458
459
/**
460
 * If `Buffer.TYPED_ARRAY_SUPPORT`:
461
 *   === true    Use Uint8Array implementation (fastest)
462
 *   === false   Use Object implementation (most compatible, even IE6)
463
 *
464
 * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
465
 * Opera 11.6+, iOS 4.2+.
466
 *
467
 * Note:
468
 *
469
 * - Implementation must support adding new properties to `Uint8Array` instances.
470
 *   Firefox 4-29 lacked support, fixed in Firefox 30+.
471
 *   See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438.
472
 *
473
 *  - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function.
474
 *
475
 *  - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of
476
 *    incorrect length in some situations.
477
 *
478
 * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they will
479
 * get the Object implementation, which is slower but will work correctly.
480
 */
481
Buffer.TYPED_ARRAY_SUPPORT = (function () {
482
  try {
483
    var buf = new ArrayBuffer(0)
484
    var arr = new Uint8Array(buf)
485
    arr.foo = function () { return 42 }
486
    return arr.foo() === 42 && // typed array instances can be augmented
487
        typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray`
488
        new Uint8Array(1).subarray(1, 1).byteLength === 0 // ie10 has broken `subarray`
489
  } catch (e) {
490
    return false
491
  }
492
})()
493
494
/**
495
 * Class: Buffer
496
 * =============
497
 *
498
 * The Buffer constructor returns instances of `Uint8Array` that are augmented
499
 * with function properties for all the node `Buffer` API functions. We use
500
 * `Uint8Array` so that square bracket notation works as expected -- it returns
501
 * a single octet.
502
 *
503
 * By augmenting the instances, we can avoid modifying the `Uint8Array`
504
 * prototype.
505
 */
506
function Buffer (subject, encoding) {
507
  var self = this
508
  if (!(self instanceof Buffer)) return new Buffer(subject, encoding)
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
509
510
  var type = typeof subject
511
  var length
512
513
  if (type === 'number') {
514
    length = +subject
515
  } else if (type === 'string') {
516
    length = Buffer.byteLength(subject, encoding)
517
  } else if (type === 'object' && subject !== null) {
518
    // assume object is array-like
519
    if (subject.type === 'Buffer' && isArray(subject.data)) subject = subject.data
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
520
    length = +subject.length
521
  } else {
522
    throw new TypeError('must start with number, buffer, array or string')
523
  }
524
525
  if (length > kMaxLength) {
526
    throw new RangeError('Attempt to allocate Buffer larger than maximum size: 0x' +
527
      kMaxLength.toString(16) + ' bytes')
528
  }
529
530
  if (length < 0) length = 0
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
531
  else length >>>= 0 // coerce to uint32
532
533
  if (Buffer.TYPED_ARRAY_SUPPORT) {
534
    // Preferred: Return an augmented `Uint8Array` instance for best performance
535
    self = Buffer._augment(new Uint8Array(length)) // eslint-disable-line consistent-this
536
  } else {
537
    // Fallback: Return THIS instance of Buffer (created by `new`)
538
    self.length = length
539
    self._isBuffer = true
540
  }
541
542
  var i
543
  if (Buffer.TYPED_ARRAY_SUPPORT && typeof subject.byteLength === 'number') {
544
    // Speed optimization -- use set if we're copying from a typed array
545
    self._set(subject)
546
  } else if (isArrayish(subject)) {
547
    // Treat array-ish objects as a byte array
548
    if (Buffer.isBuffer(subject)) {
549
      for (i = 0; i < length; i++) {
550
        self[i] = subject.readUInt8(i)
551
      }
552
    } else {
553
      for (i = 0; i < length; i++) {
554
        self[i] = ((subject[i] % 256) + 256) % 256
555
      }
556
    }
557
  } else if (type === 'string') {
558
    self.write(subject, 0, encoding)
559
  } else if (type === 'number' && !Buffer.TYPED_ARRAY_SUPPORT) {
560
    for (i = 0; i < length; i++) {
561
      self[i] = 0
562
    }
563
  }
564
565
  if (length > 0 && length <= Buffer.poolSize) self.parent = rootParent
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
566
567
  return self
568
}
569
570
function SlowBuffer (subject, encoding) {
571
  if (!(this instanceof SlowBuffer)) return new SlowBuffer(subject, encoding)
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
572
573
  var buf = new Buffer(subject, encoding)
574
  delete buf.parent
575
  return buf
576
}
577
578
Buffer.isBuffer = function isBuffer (b) {
579
  return !!(b != null && b._isBuffer)
580
}
581
582
Buffer.compare = function compare (a, b) {
583
  if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
584
    throw new TypeError('Arguments must be Buffers')
585
  }
586
587
  if (a === b) return 0
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
588
589
  var x = a.length
590
  var y = b.length
591
  for (var i = 0, len = Math.min(x, y); i < len && a[i] === b[i]; i++) {}
0 ignored issues
show
Comprehensibility Documentation Best Practice introduced by
This code block is empty. Consider removing it or adding a comment to explain.
Loading history...
592
  if (i !== len) {
593
    x = a[i]
594
    y = b[i]
595
  }
596
  if (x < y) return -1
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
597
  if (y < x) return 1
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
598
  return 0
599
}
600
601
Buffer.isEncoding = function isEncoding (encoding) {
602
  switch (String(encoding).toLowerCase()) {
603
    case 'hex':
604
    case 'utf8':
605
    case 'utf-8':
606
    case 'ascii':
607
    case 'binary':
608
    case 'base64':
609
    case 'raw':
610
    case 'ucs2':
611
    case 'ucs-2':
612
    case 'utf16le':
613
    case 'utf-16le':
614
      return true
615
    default:
616
      return false
617
  }
618
}
619
620
Buffer.concat = function concat (list, totalLength) {
621
  if (!isArray(list)) throw new TypeError('list argument must be an Array of Buffers.')
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
622
623
  if (list.length === 0) {
624
    return new Buffer(0)
625
  } else if (list.length === 1) {
626
    return list[0]
627
  }
628
629
  var i
630
  if (totalLength === undefined) {
631
    totalLength = 0
632
    for (i = 0; i < list.length; i++) {
633
      totalLength += list[i].length
634
    }
635
  }
636
637
  var buf = new Buffer(totalLength)
638
  var pos = 0
639
  for (i = 0; i < list.length; i++) {
640
    var item = list[i]
641
    item.copy(buf, pos)
642
    pos += item.length
643
  }
644
  return buf
645
}
646
647
Buffer.byteLength = function byteLength (str, encoding) {
648
  var ret
649
  str = str + ''
650
  switch (encoding || 'utf8') {
651
    case 'ascii':
652
    case 'binary':
653
    case 'raw':
654
      ret = str.length
655
      break
656
    case 'ucs2':
657
    case 'ucs-2':
658
    case 'utf16le':
659
    case 'utf-16le':
660
      ret = str.length * 2
661
      break
662
    case 'hex':
663
      ret = str.length >>> 1
664
      break
665
    case 'utf8':
666
    case 'utf-8':
667
      ret = utf8ToBytes(str).length
668
      break
669
    case 'base64':
670
      ret = base64ToBytes(str).length
671
      break
672
    default:
673
      ret = str.length
674
  }
675
  return ret
676
}
677
678
// pre-set for values that may exist in the future
679
Buffer.prototype.length = undefined
680
Buffer.prototype.parent = undefined
681
682
// toString(encoding, start=0, end=buffer.length)
683
Buffer.prototype.toString = function toString (encoding, start, end) {
684
  var loweredCase = false
685
686
  start = start >>> 0
687
  end = end === undefined || end === Infinity ? this.length : end >>> 0
688
689
  if (!encoding) encoding = 'utf8'
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
690
  if (start < 0) start = 0
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
691
  if (end > this.length) end = this.length
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
692
  if (end <= start) return ''
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
693
694
  while (true) {
695
    switch (encoding) {
696
      case 'hex':
697
        return hexSlice(this, start, end)
698
699
      case 'utf8':
700
      case 'utf-8':
701
        return utf8Slice(this, start, end)
702
703
      case 'ascii':
704
        return asciiSlice(this, start, end)
705
706
      case 'binary':
707
        return binarySlice(this, start, end)
708
709
      case 'base64':
710
        return base64Slice(this, start, end)
711
712
      case 'ucs2':
713
      case 'ucs-2':
714
      case 'utf16le':
715
      case 'utf-16le':
716
        return utf16leSlice(this, start, end)
717
718
      default:
719
        if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
720
        encoding = (encoding + '').toLowerCase()
721
        loweredCase = true
722
    }
723
  }
0 ignored issues
show
Best Practice introduced by
There is no return statement in this branch, but you do return something in other branches. Did you maybe miss it? If you do not want to return anything, consider adding return undefined; explicitly.
Loading history...
724
}
725
726
Buffer.prototype.equals = function equals (b) {
727
  if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
728
  if (this === b) return true
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
729
  return Buffer.compare(this, b) === 0
730
}
731
732
Buffer.prototype.inspect = function inspect () {
733
  var str = ''
734
  var max = exports.INSPECT_MAX_BYTES
735
  if (this.length > 0) {
736
    str = this.toString('hex', 0, max).match(/.{2}/g).join(' ')
737
    if (this.length > max) str += ' ... '
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
738
  }
739
  return '<Buffer ' + str + '>'
740
}
741
742
Buffer.prototype.compare = function compare (b) {
743
  if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
744
  if (this === b) return 0
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
745
  return Buffer.compare(this, b)
746
}
747
748
Buffer.prototype.indexOf = function indexOf (val, byteOffset) {
749
  if (byteOffset > 0x7fffffff) byteOffset = 0x7fffffff
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
750
  else if (byteOffset < -0x80000000) byteOffset = -0x80000000
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
751
  byteOffset >>= 0
752
753
  if (this.length === 0) return -1
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
754
  if (byteOffset >= this.length) return -1
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
755
756
  // Negative offsets start from the end of the buffer
757
  if (byteOffset < 0) byteOffset = Math.max(this.length + byteOffset, 0)
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
758
759
  if (typeof val === 'string') {
760
    if (val.length === 0) return -1 // special case: looking for empty string always fails
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
761
    return String.prototype.indexOf.call(this, val, byteOffset)
762
  }
763
  if (Buffer.isBuffer(val)) {
764
    return arrayIndexOf(this, val, byteOffset)
765
  }
766
  if (typeof val === 'number') {
767
    if (Buffer.TYPED_ARRAY_SUPPORT && Uint8Array.prototype.indexOf === 'function') {
768
      return Uint8Array.prototype.indexOf.call(this, val, byteOffset)
769
    }
770
    return arrayIndexOf(this, [ val ], byteOffset)
771
  }
772
773
  function arrayIndexOf (arr, val, byteOffset) {
774
    var foundIndex = -1
775
    for (var i = 0; byteOffset + i < arr.length; i++) {
776
      if (arr[byteOffset + i] === val[foundIndex === -1 ? 0 : i - foundIndex]) {
777
        if (foundIndex === -1) foundIndex = i
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
778
        if (i - foundIndex + 1 === val.length) return byteOffset + foundIndex
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
779
      } else {
780
        foundIndex = -1
781
      }
782
    }
783
    return -1
784
  }
785
786
  throw new TypeError('val must be string, number or Buffer')
787
}
788
789
// `get` will be removed in Node 0.13+
790
Buffer.prototype.get = function get (offset) {
791
  console.log('.get() is deprecated. Access using array indexes instead.')
0 ignored issues
show
Debugging Code introduced by
console.log looks like debug code. Are you sure you do not want to remove it?
Loading history...
792
  return this.readUInt8(offset)
793
}
794
795
// `set` will be removed in Node 0.13+
796
Buffer.prototype.set = function set (v, offset) {
797
  console.log('.set() is deprecated. Access using array indexes instead.')
0 ignored issues
show
Debugging Code introduced by
console.log looks like debug code. Are you sure you do not want to remove it?
Loading history...
798
  return this.writeUInt8(v, offset)
799
}
800
801
function hexWrite (buf, string, offset, length) {
802
  offset = Number(offset) || 0
803
  var remaining = buf.length - offset
804
  if (!length) {
805
    length = remaining
806
  } else {
807
    length = Number(length)
808
    if (length > remaining) {
809
      length = remaining
810
    }
811
  }
812
813
  // must be an even number of digits
814
  var strLen = string.length
815
  if (strLen % 2 !== 0) throw new Error('Invalid hex string')
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
816
817
  if (length > strLen / 2) {
818
    length = strLen / 2
819
  }
820
  for (var i = 0; i < length; i++) {
821
    var parsed = parseInt(string.substr(i * 2, 2), 16)
822
    if (isNaN(parsed)) throw new Error('Invalid hex string')
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
823
    buf[offset + i] = parsed
824
  }
825
  return i
826
}
827
828
function utf8Write (buf, string, offset, length) {
829
  var charsWritten = blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
830
  return charsWritten
831
}
832
833
function asciiWrite (buf, string, offset, length) {
834
  var charsWritten = blitBuffer(asciiToBytes(string), buf, offset, length)
835
  return charsWritten
836
}
837
838
function binaryWrite (buf, string, offset, length) {
839
  return asciiWrite(buf, string, offset, length)
840
}
841
842
function base64Write (buf, string, offset, length) {
843
  var charsWritten = blitBuffer(base64ToBytes(string), buf, offset, length)
844
  return charsWritten
845
}
846
847
function utf16leWrite (buf, string, offset, length) {
848
  var charsWritten = blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
849
  return charsWritten
850
}
851
852
Buffer.prototype.write = function write (string, offset, length, encoding) {
853
  // Support both (string, offset, length, encoding)
854
  // and the legacy (string, encoding, offset, length)
855
  if (isFinite(offset)) {
856
    if (!isFinite(length)) {
857
      encoding = length
858
      length = undefined
859
    }
860
  } else {  // legacy
861
    var swap = encoding
862
    encoding = offset
863
    offset = length
864
    length = swap
865
  }
866
867
  offset = Number(offset) || 0
868
869
  if (length < 0 || offset < 0 || offset > this.length) {
870
    throw new RangeError('attempt to write outside buffer bounds')
871
  }
872
873
  var remaining = this.length - offset
874
  if (!length) {
875
    length = remaining
876
  } else {
877
    length = Number(length)
878
    if (length > remaining) {
879
      length = remaining
880
    }
881
  }
882
  encoding = String(encoding || 'utf8').toLowerCase()
883
884
  var ret
885
  switch (encoding) {
886
    case 'hex':
887
      ret = hexWrite(this, string, offset, length)
888
      break
889
    case 'utf8':
890
    case 'utf-8':
891
      ret = utf8Write(this, string, offset, length)
892
      break
893
    case 'ascii':
894
      ret = asciiWrite(this, string, offset, length)
895
      break
896
    case 'binary':
897
      ret = binaryWrite(this, string, offset, length)
898
      break
899
    case 'base64':
900
      ret = base64Write(this, string, offset, length)
901
      break
902
    case 'ucs2':
903
    case 'ucs-2':
904
    case 'utf16le':
905
    case 'utf-16le':
906
      ret = utf16leWrite(this, string, offset, length)
907
      break
908
    default:
909
      throw new TypeError('Unknown encoding: ' + encoding)
910
  }
911
  return ret
912
}
913
914
Buffer.prototype.toJSON = function toJSON () {
915
  return {
916
    type: 'Buffer',
917
    data: Array.prototype.slice.call(this._arr || this, 0)
918
  }
919
}
920
921
function base64Slice (buf, start, end) {
922
  if (start === 0 && end === buf.length) {
923
    return base64.fromByteArray(buf)
924
  } else {
925
    return base64.fromByteArray(buf.slice(start, end))
926
  }
927
}
928
929
function utf8Slice (buf, start, end) {
930
  var res = ''
931
  var tmp = ''
932
  end = Math.min(buf.length, end)
933
934
  for (var i = start; i < end; i++) {
935
    if (buf[i] <= 0x7F) {
936
      res += decodeUtf8Char(tmp) + String.fromCharCode(buf[i])
937
      tmp = ''
938
    } else {
939
      tmp += '%' + buf[i].toString(16)
940
    }
941
  }
942
943
  return res + decodeUtf8Char(tmp)
944
}
945
946
function asciiSlice (buf, start, end) {
947
  var ret = ''
948
  end = Math.min(buf.length, end)
949
950
  for (var i = start; i < end; i++) {
951
    ret += String.fromCharCode(buf[i] & 0x7F)
952
  }
953
  return ret
954
}
955
956
function binarySlice (buf, start, end) {
957
  var ret = ''
958
  end = Math.min(buf.length, end)
959
960
  for (var i = start; i < end; i++) {
961
    ret += String.fromCharCode(buf[i])
962
  }
963
  return ret
964
}
965
966
function hexSlice (buf, start, end) {
967
  var len = buf.length
968
969
  if (!start || start < 0) start = 0
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
970
  if (!end || end < 0 || end > len) end = len
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
971
972
  var out = ''
973
  for (var i = start; i < end; i++) {
974
    out += toHex(buf[i])
975
  }
976
  return out
977
}
978
979
function utf16leSlice (buf, start, end) {
980
  var bytes = buf.slice(start, end)
981
  var res = ''
982
  for (var i = 0; i < bytes.length; i += 2) {
983
    res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256)
984
  }
985
  return res
986
}
987
988
Buffer.prototype.slice = function slice (start, end) {
989
  var len = this.length
990
  start = ~~start
991
  end = end === undefined ? len : ~~end
992
993
  if (start < 0) {
994
    start += len
995
    if (start < 0) start = 0
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
996
  } else if (start > len) {
997
    start = len
998
  }
999
1000
  if (end < 0) {
1001
    end += len
1002
    if (end < 0) end = 0
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
1003
  } else if (end > len) {
1004
    end = len
1005
  }
1006
1007
  if (end < start) end = start
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
1008
1009
  var newBuf
1010
  if (Buffer.TYPED_ARRAY_SUPPORT) {
1011
    newBuf = Buffer._augment(this.subarray(start, end))
1012
  } else {
1013
    var sliceLen = end - start
1014
    newBuf = new Buffer(sliceLen, undefined)
1015
    for (var i = 0; i < sliceLen; i++) {
1016
      newBuf[i] = this[i + start]
1017
    }
1018
  }
1019
1020
  if (newBuf.length) newBuf.parent = this.parent || this
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
1021
1022
  return newBuf
1023
}
1024
1025
/*
1026
 * Need to make sure that buffer isn't trying to write out of bounds.
1027
 */
1028
function checkOffset (offset, ext, length) {
1029
  if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
1030
  if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
1031
}
1032
1033
Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
1034
  offset = offset >>> 0
1035
  byteLength = byteLength >>> 0
1036
  if (!noAssert) checkOffset(offset, byteLength, this.length)
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
1037
1038
  var val = this[offset]
1039
  var mul = 1
1040
  var i = 0
1041
  while (++i < byteLength && (mul *= 0x100)) {
1042
    val += this[offset + i] * mul
1043
  }
1044
1045
  return val
1046
}
1047
1048
Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
1049
  offset = offset >>> 0
1050
  byteLength = byteLength >>> 0
1051
  if (!noAssert) {
1052
    checkOffset(offset, byteLength, this.length)
1053
  }
1054
1055
  var val = this[offset + --byteLength]
1056
  var mul = 1
1057
  while (byteLength > 0 && (mul *= 0x100)) {
1058
    val += this[offset + --byteLength] * mul
1059
  }
1060
1061
  return val
1062
}
1063
1064
Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
1065
  if (!noAssert) checkOffset(offset, 1, this.length)
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
1066
  return this[offset]
1067
}
1068
1069
Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
1070
  if (!noAssert) checkOffset(offset, 2, this.length)
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
1071
  return this[offset] | (this[offset + 1] << 8)
1072
}
1073
1074
Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
1075
  if (!noAssert) checkOffset(offset, 2, this.length)
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
1076
  return (this[offset] << 8) | this[offset + 1]
1077
}
1078
1079
Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
1080
  if (!noAssert) checkOffset(offset, 4, this.length)
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
1081
1082
  return ((this[offset]) |
1083
      (this[offset + 1] << 8) |
1084
      (this[offset + 2] << 16)) +
1085
      (this[offset + 3] * 0x1000000)
1086
}
1087
1088
Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
1089
  if (!noAssert) checkOffset(offset, 4, this.length)
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
1090
1091
  return (this[offset] * 0x1000000) +
1092
    ((this[offset + 1] << 16) |
1093
    (this[offset + 2] << 8) |
1094
    this[offset + 3])
1095
}
1096
1097
Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
1098
  offset = offset >>> 0
1099
  byteLength = byteLength >>> 0
1100
  if (!noAssert) checkOffset(offset, byteLength, this.length)
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
1101
1102
  var val = this[offset]
1103
  var mul = 1
1104
  var i = 0
1105
  while (++i < byteLength && (mul *= 0x100)) {
1106
    val += this[offset + i] * mul
1107
  }
1108
  mul *= 0x80
1109
1110
  if (val >= mul) val -= Math.pow(2, 8 * byteLength)
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
1111
1112
  return val
1113
}
1114
1115
Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
1116
  offset = offset >>> 0
1117
  byteLength = byteLength >>> 0
1118
  if (!noAssert) checkOffset(offset, byteLength, this.length)
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
1119
1120
  var i = byteLength
1121
  var mul = 1
1122
  var val = this[offset + --i]
1123
  while (i > 0 && (mul *= 0x100)) {
1124
    val += this[offset + --i] * mul
1125
  }
1126
  mul *= 0x80
1127
1128
  if (val >= mul) val -= Math.pow(2, 8 * byteLength)
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
1129
1130
  return val
1131
}
1132
1133
Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
1134
  if (!noAssert) checkOffset(offset, 1, this.length)
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
1135
  if (!(this[offset] & 0x80)) return (this[offset])
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
1136
  return ((0xff - this[offset] + 1) * -1)
1137
}
1138
1139
Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
1140
  if (!noAssert) checkOffset(offset, 2, this.length)
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
1141
  var val = this[offset] | (this[offset + 1] << 8)
1142
  return (val & 0x8000) ? val | 0xFFFF0000 : val
0 ignored issues
show
introduced by
You have used a bitwise operator & in a condition. Did you maybe want to use the logical operator &&
Loading history...
1143
}
1144
1145
Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
1146
  if (!noAssert) checkOffset(offset, 2, this.length)
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
1147
  var val = this[offset + 1] | (this[offset] << 8)
1148
  return (val & 0x8000) ? val | 0xFFFF0000 : val
0 ignored issues
show
introduced by
You have used a bitwise operator & in a condition. Did you maybe want to use the logical operator &&
Loading history...
1149
}
1150
1151
Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
1152
  if (!noAssert) checkOffset(offset, 4, this.length)
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
1153
1154
  return (this[offset]) |
1155
    (this[offset + 1] << 8) |
1156
    (this[offset + 2] << 16) |
1157
    (this[offset + 3] << 24)
1158
}
1159
1160
Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
1161
  if (!noAssert) checkOffset(offset, 4, this.length)
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
1162
1163
  return (this[offset] << 24) |
1164
    (this[offset + 1] << 16) |
1165
    (this[offset + 2] << 8) |
1166
    (this[offset + 3])
1167
}
1168
1169
Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
1170
  if (!noAssert) checkOffset(offset, 4, this.length)
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
1171
  return ieee754.read(this, offset, true, 23, 4)
1172
}
1173
1174
Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
1175
  if (!noAssert) checkOffset(offset, 4, this.length)
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
1176
  return ieee754.read(this, offset, false, 23, 4)
1177
}
1178
1179
Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
1180
  if (!noAssert) checkOffset(offset, 8, this.length)
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
1181
  return ieee754.read(this, offset, true, 52, 8)
1182
}
1183
1184
Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
1185
  if (!noAssert) checkOffset(offset, 8, this.length)
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
1186
  return ieee754.read(this, offset, false, 52, 8)
1187
}
1188
1189
function checkInt (buf, value, offset, ext, max, min) {
1190
  if (!Buffer.isBuffer(buf)) throw new TypeError('buffer must be a Buffer instance')
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
1191
  if (value > max || value < min) throw new RangeError('value is out of bounds')
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
1192
  if (offset + ext > buf.length) throw new RangeError('index out of range')
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
1193
}
1194
1195
Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
1196
  value = +value
1197
  offset = offset >>> 0
1198
  byteLength = byteLength >>> 0
1199
  if (!noAssert) checkInt(this, value, offset, byteLength, Math.pow(2, 8 * byteLength), 0)
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
1200
1201
  var mul = 1
1202
  var i = 0
1203
  this[offset] = value & 0xFF
1204
  while (++i < byteLength && (mul *= 0x100)) {
1205
    this[offset + i] = (value / mul) >>> 0 & 0xFF
1206
  }
1207
1208
  return offset + byteLength
1209
}
1210
1211
Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
1212
  value = +value
1213
  offset = offset >>> 0
1214
  byteLength = byteLength >>> 0
1215
  if (!noAssert) checkInt(this, value, offset, byteLength, Math.pow(2, 8 * byteLength), 0)
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
1216
1217
  var i = byteLength - 1
1218
  var mul = 1
1219
  this[offset + i] = value & 0xFF
1220
  while (--i >= 0 && (mul *= 0x100)) {
1221
    this[offset + i] = (value / mul) >>> 0 & 0xFF
1222
  }
1223
1224
  return offset + byteLength
1225
}
1226
1227
Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
1228
  value = +value
1229
  offset = offset >>> 0
1230
  if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
1231
  if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
1232
  this[offset] = value
1233
  return offset + 1
1234
}
1235
1236
function objectWriteUInt16 (buf, value, offset, littleEndian) {
1237
  if (value < 0) value = 0xffff + value + 1
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
1238
  for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; i++) {
1239
    buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>>
1240
      (littleEndian ? i : 1 - i) * 8
1241
  }
1242
}
1243
1244
Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
1245
  value = +value
1246
  offset = offset >>> 0
1247
  if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
1248
  if (Buffer.TYPED_ARRAY_SUPPORT) {
1249
    this[offset] = value
1250
    this[offset + 1] = (value >>> 8)
1251
  } else {
1252
    objectWriteUInt16(this, value, offset, true)
1253
  }
1254
  return offset + 2
1255
}
1256
1257
Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
1258
  value = +value
1259
  offset = offset >>> 0
1260
  if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
1261
  if (Buffer.TYPED_ARRAY_SUPPORT) {
1262
    this[offset] = (value >>> 8)
1263
    this[offset + 1] = value
1264
  } else {
1265
    objectWriteUInt16(this, value, offset, false)
1266
  }
1267
  return offset + 2
1268
}
1269
1270
function objectWriteUInt32 (buf, value, offset, littleEndian) {
1271
  if (value < 0) value = 0xffffffff + value + 1
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
1272
  for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; i++) {
1273
    buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff
1274
  }
1275
}
1276
1277
Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
1278
  value = +value
1279
  offset = offset >>> 0
1280
  if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
1281
  if (Buffer.TYPED_ARRAY_SUPPORT) {
1282
    this[offset + 3] = (value >>> 24)
1283
    this[offset + 2] = (value >>> 16)
1284
    this[offset + 1] = (value >>> 8)
1285
    this[offset] = value
1286
  } else {
1287
    objectWriteUInt32(this, value, offset, true)
1288
  }
1289
  return offset + 4
1290
}
1291
1292
Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
1293
  value = +value
1294
  offset = offset >>> 0
1295
  if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
1296
  if (Buffer.TYPED_ARRAY_SUPPORT) {
1297
    this[offset] = (value >>> 24)
1298
    this[offset + 1] = (value >>> 16)
1299
    this[offset + 2] = (value >>> 8)
1300
    this[offset + 3] = value
1301
  } else {
1302
    objectWriteUInt32(this, value, offset, false)
1303
  }
1304
  return offset + 4
1305
}
1306
1307
Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
1308
  value = +value
1309
  offset = offset >>> 0
1310
  if (!noAssert) {
1311
    checkInt(
1312
      this, value, offset, byteLength,
1313
      Math.pow(2, 8 * byteLength - 1) - 1,
1314
      -Math.pow(2, 8 * byteLength - 1)
1315
    )
1316
  }
1317
1318
  var i = 0
1319
  var mul = 1
1320
  var sub = value < 0 ? 1 : 0
1321
  this[offset] = value & 0xFF
1322
  while (++i < byteLength && (mul *= 0x100)) {
1323
    this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
1324
  }
1325
1326
  return offset + byteLength
1327
}
1328
1329
Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
1330
  value = +value
1331
  offset = offset >>> 0
1332
  if (!noAssert) {
1333
    checkInt(
1334
      this, value, offset, byteLength,
1335
      Math.pow(2, 8 * byteLength - 1) - 1,
1336
      -Math.pow(2, 8 * byteLength - 1)
1337
    )
1338
  }
1339
1340
  var i = byteLength - 1
1341
  var mul = 1
1342
  var sub = value < 0 ? 1 : 0
1343
  this[offset + i] = value & 0xFF
1344
  while (--i >= 0 && (mul *= 0x100)) {
1345
    this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
1346
  }
1347
1348
  return offset + byteLength
1349
}
1350
1351
Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
1352
  value = +value
1353
  offset = offset >>> 0
1354
  if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
1355
  if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
1356
  if (value < 0) value = 0xff + value + 1
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
1357
  this[offset] = value
1358
  return offset + 1
1359
}
1360
1361
Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
1362
  value = +value
1363
  offset = offset >>> 0
1364
  if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
1365
  if (Buffer.TYPED_ARRAY_SUPPORT) {
1366
    this[offset] = value
1367
    this[offset + 1] = (value >>> 8)
1368
  } else {
1369
    objectWriteUInt16(this, value, offset, true)
1370
  }
1371
  return offset + 2
1372
}
1373
1374
Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
1375
  value = +value
1376
  offset = offset >>> 0
1377
  if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
1378
  if (Buffer.TYPED_ARRAY_SUPPORT) {
1379
    this[offset] = (value >>> 8)
1380
    this[offset + 1] = value
1381
  } else {
1382
    objectWriteUInt16(this, value, offset, false)
1383
  }
1384
  return offset + 2
1385
}
1386
1387
Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
1388
  value = +value
1389
  offset = offset >>> 0
1390
  if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
1391
  if (Buffer.TYPED_ARRAY_SUPPORT) {
1392
    this[offset] = value
1393
    this[offset + 1] = (value >>> 8)
1394
    this[offset + 2] = (value >>> 16)
1395
    this[offset + 3] = (value >>> 24)
1396
  } else {
1397
    objectWriteUInt32(this, value, offset, true)
1398
  }
1399
  return offset + 4
1400
}
1401
1402
Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
1403
  value = +value
1404
  offset = offset >>> 0
1405
  if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
1406
  if (value < 0) value = 0xffffffff + value + 1
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
1407
  if (Buffer.TYPED_ARRAY_SUPPORT) {
1408
    this[offset] = (value >>> 24)
1409
    this[offset + 1] = (value >>> 16)
1410
    this[offset + 2] = (value >>> 8)
1411
    this[offset + 3] = value
1412
  } else {
1413
    objectWriteUInt32(this, value, offset, false)
1414
  }
1415
  return offset + 4
1416
}
1417
1418
function checkIEEE754 (buf, value, offset, ext, max, min) {
1419
  if (value > max || value < min) throw new RangeError('value is out of bounds')
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
1420
  if (offset + ext > buf.length) throw new RangeError('index out of range')
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
1421
  if (offset < 0) throw new RangeError('index out of range')
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
1422
}
1423
1424
function writeFloat (buf, value, offset, littleEndian, noAssert) {
1425
  if (!noAssert) {
1426
    checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
1427
  }
1428
  ieee754.write(buf, value, offset, littleEndian, 23, 4)
1429
  return offset + 4
1430
}
1431
1432
Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
1433
  return writeFloat(this, value, offset, true, noAssert)
1434
}
1435
1436
Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
1437
  return writeFloat(this, value, offset, false, noAssert)
1438
}
1439
1440
function writeDouble (buf, value, offset, littleEndian, noAssert) {
1441
  if (!noAssert) {
1442
    checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)
1443
  }
1444
  ieee754.write(buf, value, offset, littleEndian, 52, 8)
1445
  return offset + 8
1446
}
1447
1448
Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
1449
  return writeDouble(this, value, offset, true, noAssert)
1450
}
1451
1452
Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
1453
  return writeDouble(this, value, offset, false, noAssert)
1454
}
1455
1456
// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
1457
Buffer.prototype.copy = function copy (target, target_start, start, end) {
1458
  if (!start) start = 0
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
1459
  if (!end && end !== 0) end = this.length
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
1460
  if (target_start >= target.length) target_start = target.length
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
1461
  if (!target_start) target_start = 0
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
1462
  if (end > 0 && end < start) end = start
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
1463
1464
  // Copy 0 bytes; we're done
1465
  if (end === start) return 0
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
1466
  if (target.length === 0 || this.length === 0) return 0
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
1467
1468
  // Fatal error conditions
1469
  if (target_start < 0) {
1470
    throw new RangeError('targetStart out of bounds')
1471
  }
1472
  if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds')
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
1473
  if (end < 0) throw new RangeError('sourceEnd out of bounds')
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
1474
1475
  // Are we oob?
1476
  if (end > this.length) end = this.length
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
1477
  if (target.length - target_start < end - start) {
1478
    end = target.length - target_start + start
1479
  }
1480
1481
  var len = end - start
1482
1483
  if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) {
1484
    for (var i = 0; i < len; i++) {
1485
      target[i + target_start] = this[i + start]
1486
    }
1487
  } else {
1488
    target._set(this.subarray(start, start + len), target_start)
1489
  }
1490
1491
  return len
1492
}
1493
1494
// fill(value, start=0, end=buffer.length)
1495
Buffer.prototype.fill = function fill (value, start, end) {
1496
  if (!value) value = 0
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
1497
  if (!start) start = 0
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
1498
  if (!end) end = this.length
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
1499
1500
  if (end < start) throw new RangeError('end < start')
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
1501
1502
  // Fill 0 bytes; we're done
1503
  if (end === start) return
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
1504
  if (this.length === 0) return
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
1505
1506
  if (start < 0 || start >= this.length) throw new RangeError('start out of bounds')
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
1507
  if (end < 0 || end > this.length) throw new RangeError('end out of bounds')
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
1508
1509
  var i
1510
  if (typeof value === 'number') {
1511
    for (i = start; i < end; i++) {
1512
      this[i] = value
1513
    }
1514
  } else {
1515
    var bytes = utf8ToBytes(value.toString())
1516
    var len = bytes.length
1517
    for (i = start; i < end; i++) {
1518
      this[i] = bytes[i % len]
1519
    }
1520
  }
1521
1522
  return this
1523
}
1524
1525
/**
1526
 * Creates a new `ArrayBuffer` with the *copied* memory of the buffer instance.
1527
 * Added in Node 0.12. Only available in browsers that support ArrayBuffer.
1528
 */
1529
Buffer.prototype.toArrayBuffer = function toArrayBuffer () {
1530
  if (typeof Uint8Array !== 'undefined') {
1531
    if (Buffer.TYPED_ARRAY_SUPPORT) {
1532
      return (new Buffer(this)).buffer
1533
    } else {
1534
      var buf = new Uint8Array(this.length)
1535
      for (var i = 0, len = buf.length; i < len; i += 1) {
1536
        buf[i] = this[i]
1537
      }
1538
      return buf.buffer
1539
    }
1540
  } else {
1541
    throw new TypeError('Buffer.toArrayBuffer not supported in this browser')
1542
  }
1543
}
1544
1545
// HELPER FUNCTIONS
1546
// ================
1547
1548
var BP = Buffer.prototype
1549
1550
/**
1551
 * Augment a Uint8Array *instance* (not the Uint8Array class!) with Buffer methods
1552
 */
1553
Buffer._augment = function _augment (arr) {
1554
  arr.constructor = Buffer
1555
  arr._isBuffer = true
1556
1557
  // save reference to original Uint8Array set method before overwriting
1558
  arr._set = arr.set
1559
1560
  // deprecated, will be removed in node 0.13+
1561
  arr.get = BP.get
1562
  arr.set = BP.set
1563
1564
  arr.write = BP.write
1565
  arr.toString = BP.toString
1566
  arr.toLocaleString = BP.toString
1567
  arr.toJSON = BP.toJSON
1568
  arr.equals = BP.equals
1569
  arr.compare = BP.compare
1570
  arr.indexOf = BP.indexOf
1571
  arr.copy = BP.copy
1572
  arr.slice = BP.slice
1573
  arr.readUIntLE = BP.readUIntLE
1574
  arr.readUIntBE = BP.readUIntBE
1575
  arr.readUInt8 = BP.readUInt8
1576
  arr.readUInt16LE = BP.readUInt16LE
1577
  arr.readUInt16BE = BP.readUInt16BE
1578
  arr.readUInt32LE = BP.readUInt32LE
1579
  arr.readUInt32BE = BP.readUInt32BE
1580
  arr.readIntLE = BP.readIntLE
1581
  arr.readIntBE = BP.readIntBE
1582
  arr.readInt8 = BP.readInt8
1583
  arr.readInt16LE = BP.readInt16LE
1584
  arr.readInt16BE = BP.readInt16BE
1585
  arr.readInt32LE = BP.readInt32LE
1586
  arr.readInt32BE = BP.readInt32BE
1587
  arr.readFloatLE = BP.readFloatLE
1588
  arr.readFloatBE = BP.readFloatBE
1589
  arr.readDoubleLE = BP.readDoubleLE
1590
  arr.readDoubleBE = BP.readDoubleBE
1591
  arr.writeUInt8 = BP.writeUInt8
1592
  arr.writeUIntLE = BP.writeUIntLE
1593
  arr.writeUIntBE = BP.writeUIntBE
1594
  arr.writeUInt16LE = BP.writeUInt16LE
1595
  arr.writeUInt16BE = BP.writeUInt16BE
1596
  arr.writeUInt32LE = BP.writeUInt32LE
1597
  arr.writeUInt32BE = BP.writeUInt32BE
1598
  arr.writeIntLE = BP.writeIntLE
1599
  arr.writeIntBE = BP.writeIntBE
1600
  arr.writeInt8 = BP.writeInt8
1601
  arr.writeInt16LE = BP.writeInt16LE
1602
  arr.writeInt16BE = BP.writeInt16BE
1603
  arr.writeInt32LE = BP.writeInt32LE
1604
  arr.writeInt32BE = BP.writeInt32BE
1605
  arr.writeFloatLE = BP.writeFloatLE
1606
  arr.writeFloatBE = BP.writeFloatBE
1607
  arr.writeDoubleLE = BP.writeDoubleLE
1608
  arr.writeDoubleBE = BP.writeDoubleBE
1609
  arr.fill = BP.fill
1610
  arr.inspect = BP.inspect
1611
  arr.toArrayBuffer = BP.toArrayBuffer
1612
1613
  return arr
1614
}
1615
1616
var INVALID_BASE64_RE = /[^+\/0-9A-z\-]/g
1617
1618
function base64clean (str) {
1619
  // Node strips out invalid characters like \n and \t from the string, base64-js does not
1620
  str = stringtrim(str).replace(INVALID_BASE64_RE, '')
1621
  // Node converts strings with length < 2 to ''
1622
  if (str.length < 2) return ''
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
1623
  // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
1624
  while (str.length % 4 !== 0) {
1625
    str = str + '='
1626
  }
1627
  return str
1628
}
1629
1630
function stringtrim (str) {
1631
  if (str.trim) return str.trim()
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
1632
  return str.replace(/^\s+|\s+$/g, '')
1633
}
1634
1635
function isArrayish (subject) {
1636
  return isArray(subject) || Buffer.isBuffer(subject) ||
1637
      subject && typeof subject === 'object' &&
1638
      typeof subject.length === 'number'
1639
}
1640
1641
function toHex (n) {
1642
  if (n < 16) return '0' + n.toString(16)
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
1643
  return n.toString(16)
1644
}
1645
1646
function utf8ToBytes (string, units) {
1647
  units = units || Infinity
1648
  var codePoint
1649
  var length = string.length
1650
  var leadSurrogate = null
1651
  var bytes = []
1652
  var i = 0
1653
1654
  for (; i < length; i++) {
1655
    codePoint = string.charCodeAt(i)
1656
1657
    // is surrogate component
1658
    if (codePoint > 0xD7FF && codePoint < 0xE000) {
1659
      // last char was a lead
1660
      if (leadSurrogate) {
1661
        // 2 leads in a row
1662
        if (codePoint < 0xDC00) {
1663
          if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
1664
          leadSurrogate = codePoint
1665
          continue
1666
        } else {
1667
          // valid surrogate pair
1668
          codePoint = leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00 | 0x10000
1669
          leadSurrogate = null
1670
        }
1671
      } else {
1672
        // no lead yet
1673
1674
        if (codePoint > 0xDBFF) {
1675
          // unexpected trail
1676
          if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
1677
          continue
1678
        } else if (i + 1 === length) {
1679
          // unpaired lead
1680
          if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
1681
          continue
1682
        } else {
1683
          // valid lead
1684
          leadSurrogate = codePoint
1685
          continue
1686
        }
1687
      }
1688
    } else if (leadSurrogate) {
1689
      // valid bmp char, but last char was a lead
1690
      if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
1691
      leadSurrogate = null
1692
    }
1693
1694
    // encode utf8
1695
    if (codePoint < 0x80) {
1696
      if ((units -= 1) < 0) break
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
1697
      bytes.push(codePoint)
1698
    } else if (codePoint < 0x800) {
1699
      if ((units -= 2) < 0) break
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
1700
      bytes.push(
1701
        codePoint >> 0x6 | 0xC0,
1702
        codePoint & 0x3F | 0x80
1703
      )
1704
    } else if (codePoint < 0x10000) {
1705
      if ((units -= 3) < 0) break
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
1706
      bytes.push(
1707
        codePoint >> 0xC | 0xE0,
1708
        codePoint >> 0x6 & 0x3F | 0x80,
1709
        codePoint & 0x3F | 0x80
1710
      )
1711
    } else if (codePoint < 0x200000) {
1712
      if ((units -= 4) < 0) break
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
1713
      bytes.push(
1714
        codePoint >> 0x12 | 0xF0,
1715
        codePoint >> 0xC & 0x3F | 0x80,
1716
        codePoint >> 0x6 & 0x3F | 0x80,
1717
        codePoint & 0x3F | 0x80
1718
      )
1719
    } else {
1720
      throw new Error('Invalid code point')
1721
    }
1722
  }
1723
1724
  return bytes
1725
}
1726
1727
function asciiToBytes (str) {
1728
  var byteArray = []
1729
  for (var i = 0; i < str.length; i++) {
1730
    // Node's code seems to be doing this and not & 0x7F..
1731
    byteArray.push(str.charCodeAt(i) & 0xFF)
1732
  }
1733
  return byteArray
1734
}
1735
1736
function utf16leToBytes (str, units) {
1737
  var c, hi, lo
1738
  var byteArray = []
1739
  for (var i = 0; i < str.length; i++) {
1740
    if ((units -= 2) < 0) break
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
1741
1742
    c = str.charCodeAt(i)
1743
    hi = c >> 8
1744
    lo = c % 256
1745
    byteArray.push(lo)
1746
    byteArray.push(hi)
1747
  }
1748
1749
  return byteArray
1750
}
1751
1752
function base64ToBytes (str) {
1753
  return base64.toByteArray(base64clean(str))
1754
}
1755
1756
function blitBuffer (src, dst, offset, length) {
1757
  for (var i = 0; i < length; i++) {
1758
    if ((i + offset >= dst.length) || (i >= src.length)) break
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
1759
    dst[i + offset] = src[i]
1760
  }
1761
  return i
1762
}
1763
1764
function decodeUtf8Char (str) {
1765
  try {
1766
    return decodeURIComponent(str)
1767
  } catch (err) {
1768
    return String.fromCharCode(0xFFFD) // UTF 8 invalid char
1769
  }
1770
}
1771
1772
},{"base64-js":4,"ieee754":5,"is-array":6}],4:[function(_dereq_,module,exports){
1773
var lookup = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
1774
1775
;(function (exports) {
1776
	'use strict';
1777
1778
  var Arr = (typeof Uint8Array !== 'undefined')
1779
    ? Uint8Array
1780
    : Array
1781
1782
	var PLUS   = '+'.charCodeAt(0)
1783
	var SLASH  = '/'.charCodeAt(0)
1784
	var NUMBER = '0'.charCodeAt(0)
1785
	var LOWER  = 'a'.charCodeAt(0)
1786
	var UPPER  = 'A'.charCodeAt(0)
1787
	var PLUS_URL_SAFE = '-'.charCodeAt(0)
1788
	var SLASH_URL_SAFE = '_'.charCodeAt(0)
1789
1790
	function decode (elt) {
1791
		var code = elt.charCodeAt(0)
1792
		if (code === PLUS ||
1793
		    code === PLUS_URL_SAFE)
1794
			return 62 // '+'
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
1795
		if (code === SLASH ||
1796
		    code === SLASH_URL_SAFE)
1797
			return 63 // '/'
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
1798
		if (code < NUMBER)
1799
			return -1 //no match
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
1800
		if (code < NUMBER + 10)
1801
			return code - NUMBER + 26 + 26
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
1802
		if (code < UPPER + 26)
1803
			return code - UPPER
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
1804
		if (code < LOWER + 26)
0 ignored issues
show
Complexity Best Practice introduced by
There is no return statement if code < LOWER + 26 is false. Are you sure this is correct? If so, consider adding return; explicitly.

This check looks for functions where a return statement is found in some execution paths, but not in all.

Consider this little piece of code

function isBig(a) {
    if (a > 5000) {
        return "yes";
    }
}

console.log(isBig(5001)); //returns yes
console.log(isBig(42)); //returns undefined

The function isBig will only return a specific value when its parameter is bigger than 5000. In any other case, it will implicitly return undefined.

This behaviour may not be what you had intended. In any case, you can add a return undefined to the other execution path to make the return value explicit.

Loading history...
1805
			return code - LOWER + 26
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
1806
	}
1807
1808
	function b64ToByteArray (b64) {
1809
		var i, j, l, tmp, placeHolders, arr
1810
1811
		if (b64.length % 4 > 0) {
1812
			throw new Error('Invalid string. Length must be a multiple of 4')
1813
		}
1814
1815
		// the number of equal signs (place holders)
1816
		// if there are two placeholders, than the two characters before it
1817
		// represent one byte
1818
		// if there is only one, then the three characters before it represent 2 bytes
1819
		// this is just a cheap hack to not do indexOf twice
1820
		var len = b64.length
1821
		placeHolders = '=' === b64.charAt(len - 2) ? 2 : '=' === b64.charAt(len - 1) ? 1 : 0
1822
1823
		// base64 is 4/3 + up to two characters of the original data
1824
		arr = new Arr(b64.length * 3 / 4 - placeHolders)
1825
1826
		// if there are placeholders, only get up to the last complete 4 chars
1827
		l = placeHolders > 0 ? b64.length - 4 : b64.length
1828
1829
		var L = 0
1830
1831
		function push (v) {
1832
			arr[L++] = v
1833
		}
1834
1835
		for (i = 0, j = 0; i < l; i += 4, j += 3) {
1836
			tmp = (decode(b64.charAt(i)) << 18) | (decode(b64.charAt(i + 1)) << 12) | (decode(b64.charAt(i + 2)) << 6) | decode(b64.charAt(i + 3))
1837
			push((tmp & 0xFF0000) >> 16)
1838
			push((tmp & 0xFF00) >> 8)
1839
			push(tmp & 0xFF)
1840
		}
1841
1842
		if (placeHolders === 2) {
1843
			tmp = (decode(b64.charAt(i)) << 2) | (decode(b64.charAt(i + 1)) >> 4)
1844
			push(tmp & 0xFF)
1845
		} else if (placeHolders === 1) {
1846
			tmp = (decode(b64.charAt(i)) << 10) | (decode(b64.charAt(i + 1)) << 4) | (decode(b64.charAt(i + 2)) >> 2)
1847
			push((tmp >> 8) & 0xFF)
1848
			push(tmp & 0xFF)
1849
		}
1850
1851
		return arr
1852
	}
1853
1854
	function uint8ToBase64 (uint8) {
1855
		var i,
1856
			extraBytes = uint8.length % 3, // if we have 1 byte left, pad 2 bytes
1857
			output = "",
1858
			temp, length
1859
1860
		function encode (num) {
1861
			return lookup.charAt(num)
1862
		}
1863
1864
		function tripletToBase64 (num) {
1865
			return encode(num >> 18 & 0x3F) + encode(num >> 12 & 0x3F) + encode(num >> 6 & 0x3F) + encode(num & 0x3F)
1866
		}
1867
1868
		// go through the array every three bytes, we'll deal with trailing stuff later
1869
		for (i = 0, length = uint8.length - extraBytes; i < length; i += 3) {
1870
			temp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2])
1871
			output += tripletToBase64(temp)
1872
		}
1873
1874
		// pad the end with zeros, but make sure to not forget the extra bytes
1875
		switch (extraBytes) {
0 ignored issues
show
Coding Style introduced by
As per coding-style, switch statements should have a default case.
Loading history...
1876
			case 1:
1877
				temp = uint8[uint8.length - 1]
1878
				output += encode(temp >> 2)
1879
				output += encode((temp << 4) & 0x3F)
1880
				output += '=='
1881
				break
1882
			case 2:
1883
				temp = (uint8[uint8.length - 2] << 8) + (uint8[uint8.length - 1])
1884
				output += encode(temp >> 10)
1885
				output += encode((temp >> 4) & 0x3F)
1886
				output += encode((temp << 2) & 0x3F)
1887
				output += '='
1888
				break
1889
		}
1890
1891
		return output
1892
	}
1893
1894
	exports.toByteArray = b64ToByteArray
1895
	exports.fromByteArray = uint8ToBase64
1896
}(typeof exports === 'undefined' ? (this.base64js = {}) : exports))
1897
1898
},{}],5:[function(_dereq_,module,exports){
1899
exports.read = function(buffer, offset, isLE, mLen, nBytes) {
1900
  var e, m,
1901
      eLen = nBytes * 8 - mLen - 1,
1902
      eMax = (1 << eLen) - 1,
1903
      eBias = eMax >> 1,
1904
      nBits = -7,
1905
      i = isLE ? (nBytes - 1) : 0,
1906
      d = isLE ? -1 : 1,
1907
      s = buffer[offset + i];
1908
1909
  i += d;
1910
1911
  e = s & ((1 << (-nBits)) - 1);
1912
  s >>= (-nBits);
1913
  nBits += eLen;
1914
  for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8);
0 ignored issues
show
introduced by
The for loop does not have a body. Maybe you have misplaced a semicolon. If you do wish to have a loop without a body, use an empty body {}.
Loading history...
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
1915
1916
  m = e & ((1 << (-nBits)) - 1);
1917
  e >>= (-nBits);
1918
  nBits += mLen;
1919
  for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8);
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
introduced by
The for loop does not have a body. Maybe you have misplaced a semicolon. If you do wish to have a loop without a body, use an empty body {}.
Loading history...
1920
1921
  if (e === 0) {
1922
    e = 1 - eBias;
1923
  } else if (e === eMax) {
1924
    return m ? NaN : ((s ? -1 : 1) * Infinity);
1925
  } else {
1926
    m = m + Math.pow(2, mLen);
1927
    e = e - eBias;
1928
  }
1929
  return (s ? -1 : 1) * m * Math.pow(2, e - mLen);
1930
};
1931
1932
exports.write = function(buffer, value, offset, isLE, mLen, nBytes) {
1933
  var e, m, c,
1934
      eLen = nBytes * 8 - mLen - 1,
1935
      eMax = (1 << eLen) - 1,
1936
      eBias = eMax >> 1,
1937
      rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0),
1938
      i = isLE ? 0 : (nBytes - 1),
1939
      d = isLE ? 1 : -1,
1940
      s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0;
1941
1942
  value = Math.abs(value);
1943
1944
  if (isNaN(value) || value === Infinity) {
1945
    m = isNaN(value) ? 1 : 0;
1946
    e = eMax;
1947
  } else {
1948
    e = Math.floor(Math.log(value) / Math.LN2);
1949
    if (value * (c = Math.pow(2, -e)) < 1) {
1950
      e--;
1951
      c *= 2;
1952
    }
1953
    if (e + eBias >= 1) {
1954
      value += rt / c;
1955
    } else {
1956
      value += rt * Math.pow(2, 1 - eBias);
1957
    }
1958
    if (value * c >= 2) {
1959
      e++;
1960
      c /= 2;
1961
    }
1962
1963
    if (e + eBias >= eMax) {
1964
      m = 0;
1965
      e = eMax;
1966
    } else if (e + eBias >= 1) {
1967
      m = (value * c - 1) * Math.pow(2, mLen);
1968
      e = e + eBias;
1969
    } else {
1970
      m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen);
1971
      e = 0;
1972
    }
1973
  }
1974
1975
  for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8);
0 ignored issues
show
introduced by
The for loop does not have a body. Maybe you have misplaced a semicolon. If you do wish to have a loop without a body, use an empty body {}.
Loading history...
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
1976
1977
  e = (e << mLen) | m;
1978
  eLen += mLen;
1979
  for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8);
0 ignored issues
show
introduced by
The for loop does not have a body. Maybe you have misplaced a semicolon. If you do wish to have a loop without a body, use an empty body {}.
Loading history...
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
1980
1981
  buffer[offset + i - d] |= s * 128;
1982
};
1983
1984
},{}],6:[function(_dereq_,module,exports){
1985
1986
/**
1987
 * isArray
1988
 */
1989
1990
var isArray = Array.isArray;
1991
1992
/**
1993
 * toString
1994
 */
1995
1996
var str = Object.prototype.toString;
1997
1998
/**
1999
 * Whether or not the given `val`
2000
 * is an array.
2001
 *
2002
 * example:
2003
 *
2004
 *        isArray([]);
2005
 *        // > true
2006
 *        isArray(arguments);
2007
 *        // > false
2008
 *        isArray('');
2009
 *        // > false
2010
 *
2011
 * @param {mixed} val
2012
 * @return {bool}
2013
 */
2014
2015
module.exports = isArray || function (val) {
2016
  return !! val && '[object Array]' == str.call(val);
2017
};
2018
2019
},{}],7:[function(_dereq_,module,exports){
2020
(function (process){
2021
// Copyright Joyent, Inc. and other Node contributors.
2022
//
2023
// Permission is hereby granted, free of charge, to any person obtaining a
2024
// copy of this software and associated documentation files (the
2025
// "Software"), to deal in the Software without restriction, including
2026
// without limitation the rights to use, copy, modify, merge, publish,
2027
// distribute, sublicense, and/or sell copies of the Software, and to permit
2028
// persons to whom the Software is furnished to do so, subject to the
2029
// following conditions:
2030
//
2031
// The above copyright notice and this permission notice shall be included
2032
// in all copies or substantial portions of the Software.
2033
//
2034
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
2035
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
2036
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
2037
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
2038
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
2039
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
2040
// USE OR OTHER DEALINGS IN THE SOFTWARE.
2041
2042
// resolves . and .. elements in a path array with directory names there
2043
// must be no slashes, empty elements, or device names (c:\) in the array
2044
// (so also no leading and trailing slashes - it does not distinguish
2045
// relative and absolute paths)
2046
function normalizeArray(parts, allowAboveRoot) {
2047
  // if the path tries to go above the root, `up` ends up > 0
2048
  var up = 0;
2049
  for (var i = parts.length - 1; i >= 0; i--) {
2050
    var last = parts[i];
2051
    if (last === '.') {
2052
      parts.splice(i, 1);
2053
    } else if (last === '..') {
2054
      parts.splice(i, 1);
2055
      up++;
2056
    } else if (up) {
2057
      parts.splice(i, 1);
2058
      up--;
2059
    }
2060
  }
2061
2062
  // if the path is allowed to go above the root, restore leading ..s
2063
  if (allowAboveRoot) {
2064
    for (; up--; up) {
2065
      parts.unshift('..');
2066
    }
2067
  }
2068
2069
  return parts;
2070
}
2071
2072
// Split a filename into [root, dir, basename, ext], unix version
2073
// 'root' is just a slash, or nothing.
2074
var splitPathRe =
2075
    /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;
2076
var splitPath = function(filename) {
2077
  return splitPathRe.exec(filename).slice(1);
2078
};
2079
2080
// path.resolve([from ...], to)
2081
// posix version
2082
exports.resolve = function() {
2083
  var resolvedPath = '',
2084
      resolvedAbsolute = false;
2085
2086
  for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) {
2087
    var path = (i >= 0) ? arguments[i] : process.cwd();
2088
2089
    // Skip empty and invalid entries
2090
    if (typeof path !== 'string') {
2091
      throw new TypeError('Arguments to path.resolve must be strings');
2092
    } else if (!path) {
2093
      continue;
2094
    }
2095
2096
    resolvedPath = path + '/' + resolvedPath;
2097
    resolvedAbsolute = path.charAt(0) === '/';
2098
  }
2099
2100
  // At this point the path should be resolved to a full absolute path, but
2101
  // handle relative paths to be safe (might happen when process.cwd() fails)
2102
2103
  // Normalize the path
2104
  resolvedPath = normalizeArray(filter(resolvedPath.split('/'), function(p) {
2105
    return !!p;
2106
  }), !resolvedAbsolute).join('/');
2107
2108
  return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.';
2109
};
2110
2111
// path.normalize(path)
2112
// posix version
2113
exports.normalize = function(path) {
2114
  var isAbsolute = exports.isAbsolute(path),
2115
      trailingSlash = substr(path, -1) === '/';
2116
2117
  // Normalize the path
2118
  path = normalizeArray(filter(path.split('/'), function(p) {
2119
    return !!p;
2120
  }), !isAbsolute).join('/');
2121
2122
  if (!path && !isAbsolute) {
2123
    path = '.';
2124
  }
2125
  if (path && trailingSlash) {
2126
    path += '/';
2127
  }
2128
2129
  return (isAbsolute ? '/' : '') + path;
2130
};
2131
2132
// posix version
2133
exports.isAbsolute = function(path) {
2134
  return path.charAt(0) === '/';
2135
};
2136
2137
// posix version
2138
exports.join = function() {
2139
  var paths = Array.prototype.slice.call(arguments, 0);
2140
  return exports.normalize(filter(paths, function(p, index) {
0 ignored issues
show
Unused Code introduced by
The parameter index is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
2141
    if (typeof p !== 'string') {
2142
      throw new TypeError('Arguments to path.join must be strings');
2143
    }
2144
    return p;
2145
  }).join('/'));
2146
};
2147
2148
2149
// path.relative(from, to)
2150
// posix version
2151
exports.relative = function(from, to) {
2152
  from = exports.resolve(from).substr(1);
2153
  to = exports.resolve(to).substr(1);
2154
2155
  function trim(arr) {
2156
    var start = 0;
2157
    for (; start < arr.length; start++) {
2158
      if (arr[start] !== '') break;
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
2159
    }
2160
2161
    var end = arr.length - 1;
2162
    for (; end >= 0; end--) {
2163
      if (arr[end] !== '') break;
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
2164
    }
2165
2166
    if (start > end) return [];
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
2167
    return arr.slice(start, end - start + 1);
2168
  }
2169
2170
  var fromParts = trim(from.split('/'));
2171
  var toParts = trim(to.split('/'));
2172
2173
  var length = Math.min(fromParts.length, toParts.length);
2174
  var samePartsLength = length;
2175
  for (var i = 0; i < length; i++) {
2176
    if (fromParts[i] !== toParts[i]) {
2177
      samePartsLength = i;
2178
      break;
2179
    }
2180
  }
2181
2182
  var outputParts = [];
2183
  for (var i = samePartsLength; i < fromParts.length; i++) {
0 ignored issues
show
Comprehensibility Naming Best Practice introduced by
The variable i already seems to be declared on line 2175. Consider using another variable name or omitting the var keyword.

This check looks for variables that are declared in multiple lines. There may be several reasons for this.

In the simplest case the variable name was reused by mistake. This may lead to very hard to locate bugs.

If you want to reuse a variable for another purpose, consider declaring it at or near the top of your function and just assigning to it subsequently so it is always declared.

Loading history...
2184
    outputParts.push('..');
2185
  }
2186
2187
  outputParts = outputParts.concat(toParts.slice(samePartsLength));
2188
2189
  return outputParts.join('/');
2190
};
2191
2192
exports.sep = '/';
2193
exports.delimiter = ':';
2194
2195
exports.dirname = function(path) {
2196
  var result = splitPath(path),
2197
      root = result[0],
2198
      dir = result[1];
2199
2200
  if (!root && !dir) {
2201
    // No dirname whatsoever
2202
    return '.';
2203
  }
2204
2205
  if (dir) {
2206
    // It has a dirname, strip trailing slash
2207
    dir = dir.substr(0, dir.length - 1);
2208
  }
2209
2210
  return root + dir;
2211
};
2212
2213
2214
exports.basename = function(path, ext) {
2215
  var f = splitPath(path)[2];
2216
  // TODO: make this comparison case-insensitive on windows?
2217
  if (ext && f.substr(-1 * ext.length) === ext) {
2218
    f = f.substr(0, f.length - ext.length);
2219
  }
2220
  return f;
2221
};
2222
2223
2224
exports.extname = function(path) {
2225
  return splitPath(path)[3];
2226
};
2227
2228
function filter (xs, f) {
2229
    if (xs.filter) return xs.filter(f);
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
2230
    var res = [];
2231
    for (var i = 0; i < xs.length; i++) {
2232
        if (f(xs[i], i, xs)) res.push(xs[i]);
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
2233
    }
2234
    return res;
2235
}
2236
2237
// String.prototype.substr - negative index don't work in IE8
2238
var substr = 'ab'.substr(-1) === 'b'
2239
    ? function (str, start, len) { return str.substr(start, len) }
2240
    : function (str, start, len) {
2241
        if (start < 0) start = str.length + start;
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
2242
        return str.substr(start, len);
2243
    }
2244
;
2245
2246
}).call(this,_dereq_('_process'))
2247
},{"_process":8}],8:[function(_dereq_,module,exports){
2248
// shim for using process in browser
2249
2250
var process = module.exports = {};
2251
var queue = [];
2252
var draining = false;
2253
2254
function drainQueue() {
2255
    if (draining) {
2256
        return;
2257
    }
2258
    draining = true;
2259
    var currentQueue;
2260
    var len = queue.length;
2261
    while(len) {
2262
        currentQueue = queue;
0 ignored issues
show
Bug introduced by
The variable queue is changed as part of the while loop for example by [] on line 2263. Only the value of the last iteration will be visible in this function if it is called after the loop.
Loading history...
2263
        queue = [];
2264
        var i = -1;
2265
        while (++i < len) {
2266
            currentQueue[i]();
2267
        }
2268
        len = queue.length;
2269
    }
2270
    draining = false;
2271
}
2272
process.nextTick = function (fun) {
2273
    queue.push(fun);
2274
    if (!draining) {
2275
        setTimeout(drainQueue, 0);
2276
    }
2277
};
2278
2279
process.title = 'browser';
2280
process.browser = true;
2281
process.env = {};
2282
process.argv = [];
2283
process.version = ''; // empty string to avoid regexp issues
2284
process.versions = {};
2285
2286
function noop() {}
2287
2288
process.on = noop;
2289
process.addListener = noop;
2290
process.once = noop;
2291
process.off = noop;
2292
process.removeListener = noop;
2293
process.removeAllListeners = noop;
2294
process.emit = noop;
2295
2296
process.binding = function (name) {
0 ignored issues
show
Unused Code introduced by
The parameter name is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
2297
    throw new Error('process.binding is not supported');
2298
};
2299
2300
// TODO(shtylman)
2301
process.cwd = function () { return '/' };
2302
process.chdir = function (dir) {
0 ignored issues
show
Unused Code introduced by
The parameter dir is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
2303
    throw new Error('process.chdir is not supported');
2304
};
2305
process.umask = function() { return 0; };
2306
2307
},{}],9:[function(_dereq_,module,exports){
2308
/*
2309
  Copyright (C) 2013 Ariya Hidayat <[email protected]>
2310
  Copyright (C) 2013 Thaddee Tyl <[email protected]>
2311
  Copyright (C) 2012 Ariya Hidayat <[email protected]>
2312
  Copyright (C) 2012 Mathias Bynens <[email protected]>
2313
  Copyright (C) 2012 Joost-Wim Boekesteijn <[email protected]>
2314
  Copyright (C) 2012 Kris Kowal <[email protected]>
2315
  Copyright (C) 2012 Yusuke Suzuki <[email protected]>
2316
  Copyright (C) 2012 Arpad Borsos <[email protected]>
2317
  Copyright (C) 2011 Ariya Hidayat <[email protected]>
2318
2319
  Redistribution and use in source and binary forms, with or without
2320
  modification, are permitted provided that the following conditions are met:
2321
2322
    * Redistributions of source code must retain the above copyright
2323
      notice, this list of conditions and the following disclaimer.
2324
    * Redistributions in binary form must reproduce the above copyright
2325
      notice, this list of conditions and the following disclaimer in the
2326
      documentation and/or other materials provided with the distribution.
2327
2328
  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
2329
  AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
2330
  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
2331
  ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
2332
  DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
2333
  (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
2334
  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
2335
  ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
2336
  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
2337
  THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
2338
*/
2339
2340
(function (root, factory) {
2341
    'use strict';
2342
2343
    // Universal Module Definition (UMD) to support AMD, CommonJS/Node.js,
2344
    // Rhino, and plain browser loading.
2345
2346
    /* istanbul ignore next */
2347
    if (typeof define === 'function' && define.amd) {
0 ignored issues
show
Bug introduced by
The variable define seems to be never initialized.
Loading history...
2348
        define(['exports'], factory);
2349
    } else if (typeof exports !== 'undefined') {
2350
        factory(exports);
2351
    } else {
2352
        factory((root.esprima = {}));
2353
    }
2354
}(this, function (exports) {
2355
    'use strict';
2356
2357
    var Token,
2358
        TokenName,
2359
        FnExprTokens,
2360
        Syntax,
2361
        PropertyKind,
2362
        Messages,
2363
        Regex,
2364
        SyntaxTreeDelegate,
2365
        XHTMLEntities,
2366
        ClassPropertyType,
2367
        source,
2368
        strict,
2369
        index,
2370
        lineNumber,
2371
        lineStart,
2372
        length,
2373
        delegate,
2374
        lookahead,
2375
        state,
2376
        extra;
2377
2378
    Token = {
2379
        BooleanLiteral: 1,
2380
        EOF: 2,
2381
        Identifier: 3,
2382
        Keyword: 4,
2383
        NullLiteral: 5,
2384
        NumericLiteral: 6,
2385
        Punctuator: 7,
2386
        StringLiteral: 8,
2387
        RegularExpression: 9,
2388
        Template: 10,
2389
        JSXIdentifier: 11,
2390
        JSXText: 12
2391
    };
2392
2393
    TokenName = {};
2394
    TokenName[Token.BooleanLiteral] = 'Boolean';
2395
    TokenName[Token.EOF] = '<end>';
2396
    TokenName[Token.Identifier] = 'Identifier';
2397
    TokenName[Token.Keyword] = 'Keyword';
2398
    TokenName[Token.NullLiteral] = 'Null';
2399
    TokenName[Token.NumericLiteral] = 'Numeric';
2400
    TokenName[Token.Punctuator] = 'Punctuator';
2401
    TokenName[Token.StringLiteral] = 'String';
2402
    TokenName[Token.JSXIdentifier] = 'JSXIdentifier';
2403
    TokenName[Token.JSXText] = 'JSXText';
2404
    TokenName[Token.RegularExpression] = 'RegularExpression';
2405
2406
    // A function following one of those tokens is an expression.
2407
    FnExprTokens = ['(', '{', '[', 'in', 'typeof', 'instanceof', 'new',
2408
                    'return', 'case', 'delete', 'throw', 'void',
2409
                    // assignment operators
2410
                    '=', '+=', '-=', '*=', '/=', '%=', '<<=', '>>=', '>>>=',
2411
                    '&=', '|=', '^=', ',',
2412
                    // binary/unary operators
2413
                    '+', '-', '*', '/', '%', '++', '--', '<<', '>>', '>>>', '&',
2414
                    '|', '^', '!', '~', '&&', '||', '?', ':', '===', '==', '>=',
2415
                    '<=', '<', '>', '!=', '!=='];
2416
2417
    Syntax = {
2418
        AnyTypeAnnotation: 'AnyTypeAnnotation',
2419
        ArrayExpression: 'ArrayExpression',
2420
        ArrayPattern: 'ArrayPattern',
2421
        ArrayTypeAnnotation: 'ArrayTypeAnnotation',
2422
        ArrowFunctionExpression: 'ArrowFunctionExpression',
2423
        AssignmentExpression: 'AssignmentExpression',
2424
        BinaryExpression: 'BinaryExpression',
2425
        BlockStatement: 'BlockStatement',
2426
        BooleanTypeAnnotation: 'BooleanTypeAnnotation',
2427
        BreakStatement: 'BreakStatement',
2428
        CallExpression: 'CallExpression',
2429
        CatchClause: 'CatchClause',
2430
        ClassBody: 'ClassBody',
2431
        ClassDeclaration: 'ClassDeclaration',
2432
        ClassExpression: 'ClassExpression',
2433
        ClassImplements: 'ClassImplements',
2434
        ClassProperty: 'ClassProperty',
2435
        ComprehensionBlock: 'ComprehensionBlock',
2436
        ComprehensionExpression: 'ComprehensionExpression',
2437
        ConditionalExpression: 'ConditionalExpression',
2438
        ContinueStatement: 'ContinueStatement',
2439
        DebuggerStatement: 'DebuggerStatement',
2440
        DeclareClass: 'DeclareClass',
2441
        DeclareFunction: 'DeclareFunction',
2442
        DeclareModule: 'DeclareModule',
2443
        DeclareVariable: 'DeclareVariable',
2444
        DoWhileStatement: 'DoWhileStatement',
2445
        EmptyStatement: 'EmptyStatement',
2446
        ExportDeclaration: 'ExportDeclaration',
2447
        ExportBatchSpecifier: 'ExportBatchSpecifier',
2448
        ExportSpecifier: 'ExportSpecifier',
2449
        ExpressionStatement: 'ExpressionStatement',
2450
        ForInStatement: 'ForInStatement',
2451
        ForOfStatement: 'ForOfStatement',
2452
        ForStatement: 'ForStatement',
2453
        FunctionDeclaration: 'FunctionDeclaration',
2454
        FunctionExpression: 'FunctionExpression',
2455
        FunctionTypeAnnotation: 'FunctionTypeAnnotation',
2456
        FunctionTypeParam: 'FunctionTypeParam',
2457
        GenericTypeAnnotation: 'GenericTypeAnnotation',
2458
        Identifier: 'Identifier',
2459
        IfStatement: 'IfStatement',
2460
        ImportDeclaration: 'ImportDeclaration',
2461
        ImportDefaultSpecifier: 'ImportDefaultSpecifier',
2462
        ImportNamespaceSpecifier: 'ImportNamespaceSpecifier',
2463
        ImportSpecifier: 'ImportSpecifier',
2464
        InterfaceDeclaration: 'InterfaceDeclaration',
2465
        InterfaceExtends: 'InterfaceExtends',
2466
        IntersectionTypeAnnotation: 'IntersectionTypeAnnotation',
2467
        LabeledStatement: 'LabeledStatement',
2468
        Literal: 'Literal',
2469
        LogicalExpression: 'LogicalExpression',
2470
        MemberExpression: 'MemberExpression',
2471
        MethodDefinition: 'MethodDefinition',
2472
        ModuleSpecifier: 'ModuleSpecifier',
2473
        NewExpression: 'NewExpression',
2474
        NullableTypeAnnotation: 'NullableTypeAnnotation',
2475
        NumberTypeAnnotation: 'NumberTypeAnnotation',
2476
        ObjectExpression: 'ObjectExpression',
2477
        ObjectPattern: 'ObjectPattern',
2478
        ObjectTypeAnnotation: 'ObjectTypeAnnotation',
2479
        ObjectTypeCallProperty: 'ObjectTypeCallProperty',
2480
        ObjectTypeIndexer: 'ObjectTypeIndexer',
2481
        ObjectTypeProperty: 'ObjectTypeProperty',
2482
        Program: 'Program',
2483
        Property: 'Property',
2484
        QualifiedTypeIdentifier: 'QualifiedTypeIdentifier',
2485
        ReturnStatement: 'ReturnStatement',
2486
        SequenceExpression: 'SequenceExpression',
2487
        SpreadElement: 'SpreadElement',
2488
        SpreadProperty: 'SpreadProperty',
2489
        StringLiteralTypeAnnotation: 'StringLiteralTypeAnnotation',
2490
        StringTypeAnnotation: 'StringTypeAnnotation',
2491
        SwitchCase: 'SwitchCase',
2492
        SwitchStatement: 'SwitchStatement',
2493
        TaggedTemplateExpression: 'TaggedTemplateExpression',
2494
        TemplateElement: 'TemplateElement',
2495
        TemplateLiteral: 'TemplateLiteral',
2496
        ThisExpression: 'ThisExpression',
2497
        ThrowStatement: 'ThrowStatement',
2498
        TupleTypeAnnotation: 'TupleTypeAnnotation',
2499
        TryStatement: 'TryStatement',
2500
        TypeAlias: 'TypeAlias',
2501
        TypeAnnotation: 'TypeAnnotation',
2502
        TypeCastExpression: 'TypeCastExpression',
2503
        TypeofTypeAnnotation: 'TypeofTypeAnnotation',
2504
        TypeParameterDeclaration: 'TypeParameterDeclaration',
2505
        TypeParameterInstantiation: 'TypeParameterInstantiation',
2506
        UnaryExpression: 'UnaryExpression',
2507
        UnionTypeAnnotation: 'UnionTypeAnnotation',
2508
        UpdateExpression: 'UpdateExpression',
2509
        VariableDeclaration: 'VariableDeclaration',
2510
        VariableDeclarator: 'VariableDeclarator',
2511
        VoidTypeAnnotation: 'VoidTypeAnnotation',
2512
        WhileStatement: 'WhileStatement',
2513
        WithStatement: 'WithStatement',
2514
        JSXIdentifier: 'JSXIdentifier',
2515
        JSXNamespacedName: 'JSXNamespacedName',
2516
        JSXMemberExpression: 'JSXMemberExpression',
2517
        JSXEmptyExpression: 'JSXEmptyExpression',
2518
        JSXExpressionContainer: 'JSXExpressionContainer',
2519
        JSXElement: 'JSXElement',
2520
        JSXClosingElement: 'JSXClosingElement',
2521
        JSXOpeningElement: 'JSXOpeningElement',
2522
        JSXAttribute: 'JSXAttribute',
2523
        JSXSpreadAttribute: 'JSXSpreadAttribute',
2524
        JSXText: 'JSXText',
2525
        YieldExpression: 'YieldExpression',
2526
        AwaitExpression: 'AwaitExpression'
2527
    };
2528
2529
    PropertyKind = {
2530
        Data: 1,
2531
        Get: 2,
2532
        Set: 4
2533
    };
2534
2535
    ClassPropertyType = {
2536
        'static': 'static',
2537
        prototype: 'prototype'
2538
    };
2539
2540
    // Error messages should be identical to V8.
2541
    Messages = {
2542
        UnexpectedToken: 'Unexpected token %0',
2543
        UnexpectedNumber: 'Unexpected number',
2544
        UnexpectedString: 'Unexpected string',
2545
        UnexpectedIdentifier: 'Unexpected identifier',
2546
        UnexpectedReserved: 'Unexpected reserved word',
2547
        UnexpectedTemplate: 'Unexpected quasi %0',
2548
        UnexpectedEOS: 'Unexpected end of input',
2549
        NewlineAfterThrow: 'Illegal newline after throw',
2550
        InvalidRegExp: 'Invalid regular expression',
2551
        UnterminatedRegExp: 'Invalid regular expression: missing /',
2552
        InvalidLHSInAssignment: 'Invalid left-hand side in assignment',
2553
        InvalidLHSInFormalsList: 'Invalid left-hand side in formals list',
2554
        InvalidLHSInForIn: 'Invalid left-hand side in for-in',
2555
        MultipleDefaultsInSwitch: 'More than one default clause in switch statement',
2556
        NoCatchOrFinally: 'Missing catch or finally after try',
2557
        UnknownLabel: 'Undefined label \'%0\'',
2558
        Redeclaration: '%0 \'%1\' has already been declared',
2559
        IllegalContinue: 'Illegal continue statement',
2560
        IllegalBreak: 'Illegal break statement',
2561
        IllegalDuplicateClassProperty: 'Illegal duplicate property in class definition',
2562
        IllegalClassConstructorProperty: 'Illegal constructor property in class definition',
2563
        IllegalReturn: 'Illegal return statement',
2564
        IllegalSpread: 'Illegal spread element',
2565
        StrictModeWith: 'Strict mode code may not include a with statement',
2566
        StrictCatchVariable: 'Catch variable may not be eval or arguments in strict mode',
2567
        StrictVarName: 'Variable name may not be eval or arguments in strict mode',
2568
        StrictParamName: 'Parameter name eval or arguments is not allowed in strict mode',
2569
        StrictParamDupe: 'Strict mode function may not have duplicate parameter names',
2570
        ParameterAfterRestParameter: 'Rest parameter must be final parameter of an argument list',
2571
        DefaultRestParameter: 'Rest parameter can not have a default value',
2572
        ElementAfterSpreadElement: 'Spread must be the final element of an element list',
2573
        PropertyAfterSpreadProperty: 'A rest property must be the final property of an object literal',
2574
        ObjectPatternAsRestParameter: 'Invalid rest parameter',
2575
        ObjectPatternAsSpread: 'Invalid spread argument',
2576
        StrictFunctionName: 'Function name may not be eval or arguments in strict mode',
2577
        StrictOctalLiteral: 'Octal literals are not allowed in strict mode.',
2578
        StrictDelete: 'Delete of an unqualified identifier in strict mode.',
2579
        StrictDuplicateProperty: 'Duplicate data property in object literal not allowed in strict mode',
2580
        AccessorDataProperty: 'Object literal may not have data and accessor property with the same name',
2581
        AccessorGetSet: 'Object literal may not have multiple get/set accessors with the same name',
2582
        StrictLHSAssignment: 'Assignment to eval or arguments is not allowed in strict mode',
2583
        StrictLHSPostfix: 'Postfix increment/decrement may not have eval or arguments operand in strict mode',
2584
        StrictLHSPrefix: 'Prefix increment/decrement may not have eval or arguments operand in strict mode',
2585
        StrictReservedWord: 'Use of future reserved word in strict mode',
2586
        MissingFromClause: 'Missing from clause',
2587
        NoAsAfterImportNamespace: 'Missing as after import *',
2588
        InvalidModuleSpecifier: 'Invalid module specifier',
2589
        IllegalImportDeclaration: 'Illegal import declaration',
2590
        IllegalExportDeclaration: 'Illegal export declaration',
2591
        NoUninitializedConst: 'Const must be initialized',
2592
        ComprehensionRequiresBlock: 'Comprehension must have at least one block',
2593
        ComprehensionError: 'Comprehension Error',
2594
        EachNotAllowed: 'Each is not supported',
2595
        InvalidJSXAttributeValue: 'JSX value should be either an expression or a quoted JSX text',
2596
        ExpectedJSXClosingTag: 'Expected corresponding JSX closing tag for %0',
2597
        AdjacentJSXElements: 'Adjacent JSX elements must be wrapped in an enclosing tag',
2598
        ConfusedAboutFunctionType: 'Unexpected token =>. It looks like ' +
2599
            'you are trying to write a function type, but you ended up ' +
2600
            'writing a grouped type followed by an =>, which is a syntax ' +
2601
            'error. Remember, function type parameters are named so function ' +
2602
            'types look like (name1: type1, name2: type2) => returnType. You ' +
2603
            'probably wrote (type1) => returnType'
2604
    };
2605
2606
    // See also tools/generate-unicode-regex.py.
2607
    Regex = {
2608
        NonAsciiIdentifierStart: new RegExp('[\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u0527\u0531-\u0556\u0559\u0561-\u0587\u05d0-\u05ea\u05f0-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u08a0\u08a2-\u08ac\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0977\u0979-\u097f\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c33\u0c35-\u0c39\u0c3d\u0c58\u0c59\u0c60\u0c61\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d05-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d60\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e87\u0e88\u0e8a\u0e8d\u0e94-\u0e97\u0e99-\u0e9f\u0ea1-\u0ea3\u0ea5\u0ea7\u0eaa\u0eab\u0ead-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f4\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f0\u1700-\u170c\u170e-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1877\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191c\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19c1-\u19c7\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4b\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1ce9-\u1cec\u1cee-\u1cf1\u1cf5\u1cf6\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2119-\u211d\u2124\u2126\u2128\u212a-\u212d\u212f-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u2e2f\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309d-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312d\u3131-\u318e\u31a0-\u31ba\u31f0-\u31ff\u3400-\u4db5\u4e00-\u9fcc\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua697\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua78e\ua790-\ua793\ua7a0-\ua7aa\ua7f8-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa80-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uabc0-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc]'),
2609
        NonAsciiIdentifierPart: new RegExp('[\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0300-\u0374\u0376\u0377\u037a-\u037d\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u0483-\u0487\u048a-\u0527\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u05d0-\u05ea\u05f0-\u05f2\u0610-\u061a\u0620-\u0669\u066e-\u06d3\u06d5-\u06dc\u06df-\u06e8\u06ea-\u06fc\u06ff\u0710-\u074a\u074d-\u07b1\u07c0-\u07f5\u07fa\u0800-\u082d\u0840-\u085b\u08a0\u08a2-\u08ac\u08e4-\u08fe\u0900-\u0963\u0966-\u096f\u0971-\u0977\u0979-\u097f\u0981-\u0983\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bc-\u09c4\u09c7\u09c8\u09cb-\u09ce\u09d7\u09dc\u09dd\u09df-\u09e3\u09e6-\u09f1\u0a01-\u0a03\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a59-\u0a5c\u0a5e\u0a66-\u0a75\u0a81-\u0a83\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abc-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ad0\u0ae0-\u0ae3\u0ae6-\u0aef\u0b01-\u0b03\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3c-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b56\u0b57\u0b5c\u0b5d\u0b5f-\u0b63\u0b66-\u0b6f\u0b71\u0b82\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd0\u0bd7\u0be6-\u0bef\u0c01-\u0c03\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c33\u0c35-\u0c39\u0c3d-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c58\u0c59\u0c60-\u0c63\u0c66-\u0c6f\u0c82\u0c83\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbc-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0cde\u0ce0-\u0ce3\u0ce6-\u0cef\u0cf1\u0cf2\u0d02\u0d03\u0d05-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d-\u0d44\u0d46-\u0d48\u0d4a-\u0d4e\u0d57\u0d60-\u0d63\u0d66-\u0d6f\u0d7a-\u0d7f\u0d82\u0d83\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0df2\u0df3\u0e01-\u0e3a\u0e40-\u0e4e\u0e50-\u0e59\u0e81\u0e82\u0e84\u0e87\u0e88\u0e8a\u0e8d\u0e94-\u0e97\u0e99-\u0e9f\u0ea1-\u0ea3\u0ea5\u0ea7\u0eaa\u0eab\u0ead-\u0eb9\u0ebb-\u0ebd\u0ec0-\u0ec4\u0ec6\u0ec8-\u0ecd\u0ed0-\u0ed9\u0edc-\u0edf\u0f00\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f3e-\u0f47\u0f49-\u0f6c\u0f71-\u0f84\u0f86-\u0f97\u0f99-\u0fbc\u0fc6\u1000-\u1049\u1050-\u109d\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u135d-\u135f\u1380-\u138f\u13a0-\u13f4\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f0\u1700-\u170c\u170e-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176c\u176e-\u1770\u1772\u1773\u1780-\u17d3\u17d7\u17dc\u17dd\u17e0-\u17e9\u180b-\u180d\u1810-\u1819\u1820-\u1877\u1880-\u18aa\u18b0-\u18f5\u1900-\u191c\u1920-\u192b\u1930-\u193b\u1946-\u196d\u1970-\u1974\u1980-\u19ab\u19b0-\u19c9\u19d0-\u19d9\u1a00-\u1a1b\u1a20-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1aa7\u1b00-\u1b4b\u1b50-\u1b59\u1b6b-\u1b73\u1b80-\u1bf3\u1c00-\u1c37\u1c40-\u1c49\u1c4d-\u1c7d\u1cd0-\u1cd2\u1cd4-\u1cf6\u1d00-\u1de6\u1dfc-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u200c\u200d\u203f\u2040\u2054\u2071\u207f\u2090-\u209c\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2102\u2107\u210a-\u2113\u2115\u2119-\u211d\u2124\u2126\u2128\u212a-\u212d\u212f-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d7f-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u2de0-\u2dff\u2e2f\u3005-\u3007\u3021-\u302f\u3031-\u3035\u3038-\u303c\u3041-\u3096\u3099\u309a\u309d-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312d\u3131-\u318e\u31a0-\u31ba\u31f0-\u31ff\u3400-\u4db5\u4e00-\u9fcc\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua62b\ua640-\ua66f\ua674-\ua67d\ua67f-\ua697\ua69f-\ua6f1\ua717-\ua71f\ua722-\ua788\ua78b-\ua78e\ua790-\ua793\ua7a0-\ua7aa\ua7f8-\ua827\ua840-\ua873\ua880-\ua8c4\ua8d0-\ua8d9\ua8e0-\ua8f7\ua8fb\ua900-\ua92d\ua930-\ua953\ua960-\ua97c\ua980-\ua9c0\ua9cf-\ua9d9\uaa00-\uaa36\uaa40-\uaa4d\uaa50-\uaa59\uaa60-\uaa76\uaa7a\uaa7b\uaa80-\uaac2\uaadb-\uaadd\uaae0-\uaaef\uaaf2-\uaaf6\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uabc0-\uabea\uabec\uabed\uabf0-\uabf9\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe00-\ufe0f\ufe20-\ufe26\ufe33\ufe34\ufe4d-\ufe4f\ufe70-\ufe74\ufe76-\ufefc\uff10-\uff19\uff21-\uff3a\uff3f\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc]'),
2610
        LeadingZeros: new RegExp('^0+(?!$)')
2611
    };
2612
2613
    // Ensure the condition is true, otherwise throw an error.
2614
    // This is only to have a better contract semantic, i.e. another safety net
2615
    // to catch a logic error. The condition shall be fulfilled in normal case.
2616
    // Do NOT use this to enforce a certain condition on any user input.
2617
2618
    function assert(condition, message) {
2619
        /* istanbul ignore if */
2620
        if (!condition) {
2621
            throw new Error('ASSERT: ' + message);
2622
        }
2623
    }
2624
2625
    function StringMap() {
2626
        this.$data = {};
2627
    }
2628
2629
    StringMap.prototype.get = function (key) {
2630
        key = '$' + key;
2631
        return this.$data[key];
2632
    };
2633
2634
    StringMap.prototype.set = function (key, value) {
2635
        key = '$' + key;
2636
        this.$data[key] = value;
2637
        return this;
2638
    };
2639
2640
    StringMap.prototype.has = function (key) {
2641
        key = '$' + key;
2642
        return Object.prototype.hasOwnProperty.call(this.$data, key);
2643
    };
2644
2645
    StringMap.prototype["delete"] = function (key) {
2646
        key = '$' + key;
2647
        return delete this.$data[key];
2648
    };
2649
2650
    function isDecimalDigit(ch) {
2651
        return (ch >= 48 && ch <= 57);   // 0..9
2652
    }
2653
2654
    function isHexDigit(ch) {
2655
        return '0123456789abcdefABCDEF'.indexOf(ch) >= 0;
2656
    }
2657
2658
    function isOctalDigit(ch) {
2659
        return '01234567'.indexOf(ch) >= 0;
2660
    }
2661
2662
2663
    // 7.2 White Space
2664
2665
    function isWhiteSpace(ch) {
2666
        return (ch === 32) ||  // space
2667
            (ch === 9) ||      // tab
2668
            (ch === 0xB) ||
2669
            (ch === 0xC) ||
2670
            (ch === 0xA0) ||
2671
            (ch >= 0x1680 && '\u1680\u180E\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\uFEFF'.indexOf(String.fromCharCode(ch)) > 0);
2672
    }
2673
2674
    // 7.3 Line Terminators
2675
2676
    function isLineTerminator(ch) {
2677
        return (ch === 10) || (ch === 13) || (ch === 0x2028) || (ch === 0x2029);
2678
    }
2679
2680
    // 7.6 Identifier Names and Identifiers
2681
2682
    function isIdentifierStart(ch) {
2683
        return (ch === 36) || (ch === 95) ||  // $ (dollar) and _ (underscore)
2684
            (ch >= 65 && ch <= 90) ||         // A..Z
2685
            (ch >= 97 && ch <= 122) ||        // a..z
2686
            (ch === 92) ||                    // \ (backslash)
2687
            ((ch >= 0x80) && Regex.NonAsciiIdentifierStart.test(String.fromCharCode(ch)));
2688
    }
2689
2690
    function isIdentifierPart(ch) {
2691
        return (ch === 36) || (ch === 95) ||  // $ (dollar) and _ (underscore)
2692
            (ch >= 65 && ch <= 90) ||         // A..Z
2693
            (ch >= 97 && ch <= 122) ||        // a..z
2694
            (ch >= 48 && ch <= 57) ||         // 0..9
2695
            (ch === 92) ||                    // \ (backslash)
2696
            ((ch >= 0x80) && Regex.NonAsciiIdentifierPart.test(String.fromCharCode(ch)));
2697
    }
2698
2699
    // 7.6.1.2 Future Reserved Words
2700
2701
    function isFutureReservedWord(id) {
2702
        switch (id) {
2703
        case 'class':
2704
        case 'enum':
2705
        case 'export':
2706
        case 'extends':
2707
        case 'import':
2708
        case 'super':
2709
            return true;
2710
        default:
2711
            return false;
2712
        }
2713
    }
2714
2715
    function isStrictModeReservedWord(id) {
2716
        switch (id) {
2717
        case 'implements':
2718
        case 'interface':
2719
        case 'package':
2720
        case 'private':
2721
        case 'protected':
2722
        case 'public':
2723
        case 'static':
2724
        case 'yield':
2725
        case 'let':
2726
            return true;
2727
        default:
2728
            return false;
2729
        }
2730
    }
2731
2732
    function isRestrictedWord(id) {
2733
        return id === 'eval' || id === 'arguments';
2734
    }
2735
2736
    // 7.6.1.1 Keywords
2737
2738
    function isKeyword(id) {
2739
        if (strict && isStrictModeReservedWord(id)) {
2740
            return true;
2741
        }
2742
2743
        // 'const' is specialized as Keyword in V8.
2744
        // 'yield' is only treated as a keyword in strict mode.
2745
        // 'let' is for compatiblity with SpiderMonkey and ES.next.
2746
        // Some others are from future reserved words.
2747
2748
        switch (id.length) {
2749
        case 2:
2750
            return (id === 'if') || (id === 'in') || (id === 'do');
2751
        case 3:
2752
            return (id === 'var') || (id === 'for') || (id === 'new') ||
2753
                (id === 'try') || (id === 'let');
2754
        case 4:
2755
            return (id === 'this') || (id === 'else') || (id === 'case') ||
2756
                (id === 'void') || (id === 'with') || (id === 'enum');
2757
        case 5:
2758
            return (id === 'while') || (id === 'break') || (id === 'catch') ||
2759
                (id === 'throw') || (id === 'const') ||
2760
                (id === 'class') || (id === 'super');
2761
        case 6:
2762
            return (id === 'return') || (id === 'typeof') || (id === 'delete') ||
2763
                (id === 'switch') || (id === 'export') || (id === 'import');
2764
        case 7:
2765
            return (id === 'default') || (id === 'finally') || (id === 'extends');
2766
        case 8:
2767
            return (id === 'function') || (id === 'continue') || (id === 'debugger');
2768
        case 10:
2769
            return (id === 'instanceof');
2770
        default:
2771
            return false;
2772
        }
2773
    }
2774
2775
    // 7.4 Comments
2776
2777
    function addComment(type, value, start, end, loc) {
2778
        var comment;
2779
        assert(typeof start === 'number', 'Comment must have valid position');
2780
2781
        // Because the way the actual token is scanned, often the comments
2782
        // (if any) are skipped twice during the lexical analysis.
2783
        // Thus, we need to skip adding a comment if the comment array already
2784
        // handled it.
2785
        if (state.lastCommentStart >= start) {
2786
            return;
2787
        }
2788
        state.lastCommentStart = start;
2789
2790
        comment = {
2791
            type: type,
2792
            value: value
2793
        };
2794
        if (extra.range) {
2795
            comment.range = [start, end];
2796
        }
2797
        if (extra.loc) {
2798
            comment.loc = loc;
2799
        }
2800
        extra.comments.push(comment);
2801
        if (extra.attachComment) {
2802
            extra.leadingComments.push(comment);
2803
            extra.trailingComments.push(comment);
2804
        }
2805
    }
2806
2807
    function skipSingleLineComment() {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
2808
        var start, loc, ch, comment;
2809
2810
        start = index - 2;
2811
        loc = {
2812
            start: {
2813
                line: lineNumber,
2814
                column: index - lineStart - 2
2815
            }
2816
        };
2817
2818
        while (index < length) {
0 ignored issues
show
Comprehensibility Bug introduced by
The variable index does not seem to be initialized in case the while loop on line 2818 is not entered. Are you sure this can never be the case?
Loading history...
2819
            ch = source.charCodeAt(index);
2820
            ++index;
2821
            if (isLineTerminator(ch)) {
2822
                if (extra.comments) {
2823
                    comment = source.slice(start + 2, index - 1);
0 ignored issues
show
Bug introduced by
The variable index is changed as part of the while loop for example by ++index on line 2820. Only the value of the last iteration will be visible in this function if it is called after the loop.
Loading history...
2824
                    loc.end = {
2825
                        line: lineNumber,
2826
                        column: index - lineStart - 1
2827
                    };
2828
                    addComment('Line', comment, start, index - 1, loc);
2829
                }
2830
                if (ch === 13 && source.charCodeAt(index) === 10) {
2831
                    ++index;
2832
                }
2833
                ++lineNumber;
2834
                lineStart = index;
2835
                return;
2836
            }
2837
        }
2838
2839
        if (extra.comments) {
2840
            comment = source.slice(start + 2, index);
2841
            loc.end = {
2842
                line: lineNumber,
2843
                column: index - lineStart
2844
            };
2845
            addComment('Line', comment, start, index, loc);
2846
        }
2847
    }
2848
2849
    function skipMultiLineComment() {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
2850
        var start, loc, ch, comment;
2851
2852
        if (extra.comments) {
2853
            start = index - 2;
2854
            loc = {
2855
                start: {
2856
                    line: lineNumber,
2857
                    column: index - lineStart - 2
2858
                }
2859
            };
2860
        }
2861
2862
        while (index < length) {
0 ignored issues
show
Bug introduced by
The variable index seems to not be initialized for all possible execution paths.
Loading history...
2863
            ch = source.charCodeAt(index);
2864
            if (isLineTerminator(ch)) {
2865
                if (ch === 13 && source.charCodeAt(index + 1) === 10) {
2866
                    ++index;
2867
                }
2868
                ++lineNumber;
0 ignored issues
show
Bug introduced by
The variable lineNumber seems to not be initialized for all possible execution paths.
Loading history...
2869
                ++index;
2870
                lineStart = index;
0 ignored issues
show
Bug introduced by
The variable index is changed as part of the while loop for example by ++index on line 2869. Only the value of the last iteration will be visible in this function if it is called after the loop.
Loading history...
2871
                if (index >= length) {
2872
                    throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
2873
                }
2874
            } else if (ch === 42) {
2875
                // Block comment ends with '*/' (char #42, char #47).
2876
                if (source.charCodeAt(index + 1) === 47) {
2877
                    ++index;
2878
                    ++index;
2879
                    if (extra.comments) {
2880
                        comment = source.slice(start + 2, index - 2);
0 ignored issues
show
Bug introduced by
The variable start does not seem to be initialized in case extra.comments on line 2852 is false. Are you sure this can never be the case?
Loading history...
2881
                        loc.end = {
0 ignored issues
show
Bug introduced by
The variable loc does not seem to be initialized in case extra.comments on line 2852 is false. Are you sure this can never be the case?
Loading history...
2882
                            line: lineNumber,
2883
                            column: index - lineStart
0 ignored issues
show
Bug introduced by
The variable lineStart seems to not be initialized for all possible execution paths.
Loading history...
2884
                        };
2885
                        addComment('Block', comment, start, index, loc);
2886
                    }
2887
                    return;
2888
                }
2889
                ++index;
2890
            } else {
2891
                ++index;
2892
            }
2893
        }
2894
2895
        throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
2896
    }
2897
2898
    function skipComment() {
2899
        var ch;
2900
2901
        while (index < length) {
0 ignored issues
show
Comprehensibility Bug introduced by
The variable index does not seem to be initialized in case the while loop on line 2901 is not entered. Are you sure this can never be the case?
Loading history...
2902
            ch = source.charCodeAt(index);
2903
2904
            if (isWhiteSpace(ch)) {
2905
                ++index;
2906
            } else if (isLineTerminator(ch)) {
2907
                ++index;
2908
                if (ch === 13 && source.charCodeAt(index) === 10) {
0 ignored issues
show
Bug introduced by
The variable index is changed as part of the while loop for example by ++index on line 2907. Only the value of the last iteration will be visible in this function if it is called after the loop.
Loading history...
2909
                    ++index;
2910
                }
2911
                ++lineNumber;
0 ignored issues
show
Comprehensibility Bug introduced by
The variable lineNumber does not seem to be initialized in case the while loop on line 2901 is not entered. Are you sure this can never be the case?
Loading history...
2912
                lineStart = index;
2913
            } else if (ch === 47) { // 47 is '/'
2914
                ch = source.charCodeAt(index + 1);
2915
                if (ch === 47) {
2916
                    ++index;
2917
                    ++index;
2918
                    skipSingleLineComment();
2919
                } else if (ch === 42) {  // 42 is '*'
2920
                    ++index;
2921
                    ++index;
2922
                    skipMultiLineComment();
2923
                } else {
2924
                    break;
2925
                }
2926
            } else {
2927
                break;
2928
            }
2929
        }
2930
    }
2931
2932
    function scanHexEscape(prefix) {
2933
        var i, len, ch, code = 0;
2934
2935
        len = (prefix === 'u') ? 4 : 2;
2936
        for (i = 0; i < len; ++i) {
2937
            if (index < length && isHexDigit(source[index])) {
0 ignored issues
show
Bug introduced by
The variable index seems to not be initialized for all possible execution paths.
Loading history...
2938
                ch = source[index++];
2939
                code = code * 16 + '0123456789abcdef'.indexOf(ch.toLowerCase());
2940
            } else {
2941
                return '';
2942
            }
2943
        }
2944
        return String.fromCharCode(code);
2945
    }
2946
2947
    function scanUnicodeCodePointEscape() {
2948
        var ch, code, cu1, cu2;
2949
2950
        ch = source[index];
2951
        code = 0;
2952
2953
        // At least, one hex digit is required.
2954
        if (ch === '}') {
2955
            throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
2956
        }
2957
2958
        while (index < length) {
0 ignored issues
show
Bug introduced by
The variable index seems to not be initialized for all possible execution paths.
Loading history...
2959
            ch = source[index++];
2960
            if (!isHexDigit(ch)) {
2961
                break;
2962
            }
2963
            code = code * 16 + '0123456789abcdef'.indexOf(ch.toLowerCase());
2964
        }
2965
2966
        if (code > 0x10FFFF || ch !== '}') {
2967
            throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
2968
        }
2969
2970
        // UTF-16 Encoding
2971
        if (code <= 0xFFFF) {
2972
            return String.fromCharCode(code);
2973
        }
2974
        cu1 = ((code - 0x10000) >> 10) + 0xD800;
2975
        cu2 = ((code - 0x10000) & 1023) + 0xDC00;
2976
        return String.fromCharCode(cu1, cu2);
2977
    }
2978
2979
    function getEscapedIdentifier() {
2980
        var ch, id;
2981
2982
        ch = source.charCodeAt(index++);
2983
        id = String.fromCharCode(ch);
2984
2985
        // '\u' (char #92, char #117) denotes an escaped character.
2986
        if (ch === 92) {
2987
            if (source.charCodeAt(index) !== 117) {
2988
                throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
2989
            }
2990
            ++index;
2991
            ch = scanHexEscape('u');
2992
            if (!ch || ch === '\\' || !isIdentifierStart(ch.charCodeAt(0))) {
2993
                throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
2994
            }
2995
            id = ch;
2996
        }
2997
2998
        while (index < length) {
0 ignored issues
show
Bug introduced by
The variable index is changed as part of the while loop for example by ++index on line 3012. Only the value of the last iteration will be visible in this function if it is called after the loop.
Loading history...
2999
            ch = source.charCodeAt(index);
3000
            if (!isIdentifierPart(ch)) {
3001
                break;
3002
            }
3003
            ++index;
3004
            id += String.fromCharCode(ch);
3005
3006
            // '\u' (char #92, char #117) denotes an escaped character.
3007
            if (ch === 92) {
3008
                id = id.substr(0, id.length - 1);
3009
                if (source.charCodeAt(index) !== 117) {
3010
                    throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
3011
                }
3012
                ++index;
3013
                ch = scanHexEscape('u');
3014
                if (!ch || ch === '\\' || !isIdentifierPart(ch.charCodeAt(0))) {
3015
                    throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
3016
                }
3017
                id += ch;
3018
            }
3019
        }
3020
3021
        return id;
3022
    }
3023
3024
    function getIdentifier() {
3025
        var start, ch;
3026
3027
        start = index++;
3028
        while (index < length) {
0 ignored issues
show
Bug introduced by
The variable index is changed as part of the while loop for example by ++index on line 3036. Only the value of the last iteration will be visible in this function if it is called after the loop.
Loading history...
3029
            ch = source.charCodeAt(index);
3030
            if (ch === 92) {
3031
                // Blackslash (char #92) marks Unicode escape sequence.
3032
                index = start;
3033
                return getEscapedIdentifier();
3034
            }
3035
            if (isIdentifierPart(ch)) {
3036
                ++index;
3037
            } else {
3038
                break;
3039
            }
3040
        }
3041
3042
        return source.slice(start, index);
3043
    }
3044
3045
    function scanIdentifier() {
3046
        var start, id, type;
3047
3048
        start = index;
3049
3050
        // Backslash (char #92) starts an escaped character.
3051
        id = (source.charCodeAt(index) === 92) ? getEscapedIdentifier() : getIdentifier();
3052
3053
        // There is no keyword or literal with only one character.
3054
        // Thus, it must be an identifier.
3055
        if (id.length === 1) {
3056
            type = Token.Identifier;
3057
        } else if (isKeyword(id)) {
3058
            type = Token.Keyword;
3059
        } else if (id === 'null') {
3060
            type = Token.NullLiteral;
3061
        } else if (id === 'true' || id === 'false') {
3062
            type = Token.BooleanLiteral;
3063
        } else {
3064
            type = Token.Identifier;
3065
        }
3066
3067
        return {
3068
            type: type,
3069
            value: id,
3070
            lineNumber: lineNumber,
3071
            lineStart: lineStart,
3072
            range: [start, index]
3073
        };
3074
    }
3075
3076
3077
    // 7.7 Punctuators
3078
3079
    function scanPunctuator() {
3080
        var start = index,
3081
            code = source.charCodeAt(index),
3082
            code2,
3083
            ch1 = source[index],
3084
            ch2,
3085
            ch3,
3086
            ch4;
3087
3088
        if (state.inJSXTag || state.inJSXChild) {
3089
            // Don't need to check for '{' and '}' as it's already handled
3090
            // correctly by default.
3091
            switch (code) {
0 ignored issues
show
Coding Style introduced by
As per coding-style, switch statements should have a default case.
Loading history...
3092
            case 60:  // <
3093
            case 62:  // >
3094
                ++index;
3095
                return {
3096
                    type: Token.Punctuator,
3097
                    value: String.fromCharCode(code),
3098
                    lineNumber: lineNumber,
3099
                    lineStart: lineStart,
3100
                    range: [start, index]
3101
                };
3102
            }
3103
        }
3104
3105
        switch (code) {
3106
        // Check for most common single-character punctuators.
3107
        case 40:   // ( open bracket
3108
        case 41:   // ) close bracket
3109
        case 59:   // ; semicolon
3110
        case 44:   // , comma
3111
        case 123:  // { open curly brace
3112
        case 125:  // } close curly brace
3113
        case 91:   // [
3114
        case 93:   // ]
3115
        case 58:   // :
3116
        case 63:   // ?
3117
        case 126:  // ~
3118
            ++index;
3119
            if (extra.tokenize) {
3120
                if (code === 40) {
3121
                    extra.openParenToken = extra.tokens.length;
3122
                } else if (code === 123) {
3123
                    extra.openCurlyToken = extra.tokens.length;
3124
                }
3125
            }
3126
            return {
3127
                type: Token.Punctuator,
3128
                value: String.fromCharCode(code),
3129
                lineNumber: lineNumber,
3130
                lineStart: lineStart,
3131
                range: [start, index]
3132
            };
3133
3134
        default:
3135
            code2 = source.charCodeAt(index + 1);
3136
3137
            // '=' (char #61) marks an assignment or comparison operator.
3138
            if (code2 === 61) {
3139
                switch (code) {
3140
                case 37:  // %
3141
                case 38:  // &
3142
                case 42:  // *:
3143
                case 43:  // +
3144
                case 45:  // -
3145
                case 47:  // /
3146
                case 60:  // <
3147
                case 62:  // >
3148
                case 94:  // ^
3149
                case 124: // |
3150
                    index += 2;
3151
                    return {
3152
                        type: Token.Punctuator,
3153
                        value: String.fromCharCode(code) + String.fromCharCode(code2),
3154
                        lineNumber: lineNumber,
3155
                        lineStart: lineStart,
3156
                        range: [start, index]
3157
                    };
3158
3159
                case 33: // !
3160
                case 61: // =
3161
                    index += 2;
3162
3163
                    // !== and ===
3164
                    if (source.charCodeAt(index) === 61) {
3165
                        ++index;
3166
                    }
3167
                    return {
3168
                        type: Token.Punctuator,
3169
                        value: source.slice(start, index),
3170
                        lineNumber: lineNumber,
3171
                        lineStart: lineStart,
3172
                        range: [start, index]
3173
                    };
3174
                default:
3175
                    break;
3176
                }
3177
            }
3178
            break;
3179
        }
3180
3181
        // Peek more characters.
3182
3183
        ch2 = source[index + 1];
3184
        ch3 = source[index + 2];
3185
        ch4 = source[index + 3];
3186
3187
        // 4-character punctuator: >>>=
3188
3189
        if (ch1 === '>' && ch2 === '>' && ch3 === '>') {
3190
            if (ch4 === '=') {
3191
                index += 4;
3192
                return {
3193
                    type: Token.Punctuator,
3194
                    value: '>>>=',
3195
                    lineNumber: lineNumber,
3196
                    lineStart: lineStart,
3197
                    range: [start, index]
3198
                };
3199
            }
3200
        }
3201
3202
        // 3-character punctuators: === !== >>> <<= >>=
3203
3204
        if (ch1 === '>' && ch2 === '>' && ch3 === '>' && !state.inType) {
3205
            index += 3;
3206
            return {
3207
                type: Token.Punctuator,
3208
                value: '>>>',
3209
                lineNumber: lineNumber,
3210
                lineStart: lineStart,
3211
                range: [start, index]
3212
            };
3213
        }
3214
3215
        if (ch1 === '<' && ch2 === '<' && ch3 === '=') {
3216
            index += 3;
3217
            return {
3218
                type: Token.Punctuator,
3219
                value: '<<=',
3220
                lineNumber: lineNumber,
3221
                lineStart: lineStart,
3222
                range: [start, index]
3223
            };
3224
        }
3225
3226
        if (ch1 === '>' && ch2 === '>' && ch3 === '=') {
3227
            index += 3;
3228
            return {
3229
                type: Token.Punctuator,
3230
                value: '>>=',
3231
                lineNumber: lineNumber,
3232
                lineStart: lineStart,
3233
                range: [start, index]
3234
            };
3235
        }
3236
3237
        if (ch1 === '.' && ch2 === '.' && ch3 === '.') {
3238
            index += 3;
3239
            return {
3240
                type: Token.Punctuator,
3241
                value: '...',
3242
                lineNumber: lineNumber,
3243
                lineStart: lineStart,
3244
                range: [start, index]
3245
            };
3246
        }
3247
3248
        // Other 2-character punctuators: ++ -- << >> && ||
3249
3250
        // Don't match these tokens if we're in a type, since they never can
3251
        // occur and can mess up types like Map<string, Array<string>>
3252
        if (ch1 === ch2 && ('+-<>&|'.indexOf(ch1) >= 0) && !state.inType) {
3253
            index += 2;
3254
            return {
3255
                type: Token.Punctuator,
3256
                value: ch1 + ch2,
3257
                lineNumber: lineNumber,
3258
                lineStart: lineStart,
3259
                range: [start, index]
3260
            };
3261
        }
3262
3263
        if (ch1 === '=' && ch2 === '>') {
3264
            index += 2;
3265
            return {
3266
                type: Token.Punctuator,
3267
                value: '=>',
3268
                lineNumber: lineNumber,
3269
                lineStart: lineStart,
3270
                range: [start, index]
3271
            };
3272
        }
3273
3274
        if ('<>=!+-*%&|^/'.indexOf(ch1) >= 0) {
3275
            ++index;
3276
            return {
3277
                type: Token.Punctuator,
3278
                value: ch1,
3279
                lineNumber: lineNumber,
3280
                lineStart: lineStart,
3281
                range: [start, index]
3282
            };
3283
        }
3284
3285
        if (ch1 === '.') {
3286
            ++index;
3287
            return {
3288
                type: Token.Punctuator,
3289
                value: ch1,
3290
                lineNumber: lineNumber,
3291
                lineStart: lineStart,
3292
                range: [start, index]
3293
            };
3294
        }
3295
3296
        throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
0 ignored issues
show
Best Practice introduced by
There is no return statement in this branch, but you do return something in other branches. Did you maybe miss it? If you do not want to return anything, consider adding return undefined; explicitly.
Loading history...
3297
    }
3298
3299
    // 7.8.3 Numeric Literals
3300
3301
    function scanHexLiteral(start) {
3302
        var number = '';
3303
3304
        while (index < length) {
0 ignored issues
show
Comprehensibility Bug introduced by
The variable index does not seem to be initialized in case the while loop on line 3304 is not entered. Are you sure this can never be the case?
Loading history...
3305
            if (!isHexDigit(source[index])) {
3306
                break;
3307
            }
3308
            number += source[index++];
3309
        }
3310
3311
        if (number.length === 0) {
3312
            throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
3313
        }
3314
3315
        if (isIdentifierStart(source.charCodeAt(index))) {
3316
            throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
3317
        }
3318
3319
        return {
3320
            type: Token.NumericLiteral,
3321
            value: parseInt('0x' + number, 16),
3322
            lineNumber: lineNumber,
3323
            lineStart: lineStart,
3324
            range: [start, index]
3325
        };
3326
    }
3327
3328
    function scanBinaryLiteral(start) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
3329
        var ch, number;
3330
3331
        number = '';
3332
3333
        while (index < length) {
0 ignored issues
show
Comprehensibility Bug introduced by
The variable index does not seem to be initialized in case the while loop on line 3333 is not entered. Are you sure this can never be the case?
Loading history...
3334
            ch = source[index];
3335
            if (ch !== '0' && ch !== '1') {
3336
                break;
3337
            }
3338
            number += source[index++];
3339
        }
3340
3341
        if (number.length === 0) {
3342
            // only 0b or 0B
3343
            throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
3344
        }
3345
3346
        if (index < length) {
3347
            ch = source.charCodeAt(index);
3348
            /* istanbul ignore else */
3349
            if (isIdentifierStart(ch) || isDecimalDigit(ch)) {
3350
                throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
3351
            }
3352
        }
3353
3354
        return {
3355
            type: Token.NumericLiteral,
3356
            value: parseInt(number, 2),
3357
            lineNumber: lineNumber,
3358
            lineStart: lineStart,
3359
            range: [start, index]
3360
        };
3361
    }
3362
3363
    function scanOctalLiteral(prefix, start) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
3364
        var number, octal;
3365
3366
        if (isOctalDigit(prefix)) {
3367
            octal = true;
3368
            number = '0' + source[index++];
3369
        } else {
3370
            octal = false;
3371
            ++index;
3372
            number = '';
3373
        }
3374
3375
        while (index < length) {
0 ignored issues
show
Bug introduced by
The variable index is changed as part of the while loop for example by index++ on line 3379. Only the value of the last iteration will be visible in this function if it is called after the loop.
Loading history...
3376
            if (!isOctalDigit(source[index])) {
3377
                break;
3378
            }
3379
            number += source[index++];
3380
        }
3381
3382
        if (!octal && number.length === 0) {
3383
            // only 0o or 0O
3384
            throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
3385
        }
3386
3387
        if (isIdentifierStart(source.charCodeAt(index)) || isDecimalDigit(source.charCodeAt(index))) {
3388
            throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
3389
        }
3390
3391
        return {
3392
            type: Token.NumericLiteral,
3393
            value: parseInt(number, 8),
3394
            octal: octal,
3395
            lineNumber: lineNumber,
3396
            lineStart: lineStart,
3397
            range: [start, index]
3398
        };
3399
    }
3400
3401
    function scanNumericLiteral() {
3402
        var number, start, ch;
3403
3404
        ch = source[index];
3405
        assert(isDecimalDigit(ch.charCodeAt(0)) || (ch === '.'),
3406
            'Numeric literal must start with a decimal digit or a decimal point');
3407
3408
        start = index;
3409
        number = '';
3410
        if (ch !== '.') {
3411
            number = source[index++];
3412
            ch = source[index];
3413
3414
            // Hex number starts with '0x'.
3415
            // Octal number starts with '0'.
3416
            // Octal number in ES6 starts with '0o'.
3417
            // Binary number in ES6 starts with '0b'.
3418
            if (number === '0') {
3419
                if (ch === 'x' || ch === 'X') {
3420
                    ++index;
3421
                    return scanHexLiteral(start);
3422
                }
3423
                if (ch === 'b' || ch === 'B') {
3424
                    ++index;
3425
                    return scanBinaryLiteral(start);
3426
                }
3427
                if (ch === 'o' || ch === 'O' || isOctalDigit(ch)) {
3428
                    return scanOctalLiteral(ch, start);
3429
                }
3430
                // decimal number starts with '0' such as '09' is illegal.
3431
                if (ch && isDecimalDigit(ch.charCodeAt(0))) {
3432
                    throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
3433
                }
3434
            }
3435
3436
            while (isDecimalDigit(source.charCodeAt(index))) {
0 ignored issues
show
Bug introduced by
The variable index is changed as part of the while loop for example by index++ on line 3437. Only the value of the last iteration will be visible in this function if it is called after the loop.
Loading history...
3437
                number += source[index++];
3438
            }
3439
            ch = source[index];
3440
        }
3441
3442
        if (ch === '.') {
3443
            number += source[index++];
0 ignored issues
show
Bug introduced by
The variable index does not seem to be initialized in case ch !== "." on line 3410 is false. Are you sure this can never be the case?
Loading history...
3444
            while (isDecimalDigit(source.charCodeAt(index))) {
3445
                number += source[index++];
3446
            }
3447
            ch = source[index];
3448
        }
3449
3450
        if (ch === 'e' || ch === 'E') {
3451
            number += source[index++];
3452
3453
            ch = source[index];
3454
            if (ch === '+' || ch === '-') {
3455
                number += source[index++];
3456
            }
3457
            if (isDecimalDigit(source.charCodeAt(index))) {
3458
                while (isDecimalDigit(source.charCodeAt(index))) {
3459
                    number += source[index++];
3460
                }
3461
            } else {
3462
                throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
3463
            }
3464
        }
3465
3466
        if (isIdentifierStart(source.charCodeAt(index))) {
3467
            throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
3468
        }
3469
3470
        return {
3471
            type: Token.NumericLiteral,
3472
            value: parseFloat(number),
3473
            lineNumber: lineNumber,
3474
            lineStart: lineStart,
3475
            range: [start, index]
3476
        };
3477
    }
3478
3479
    // 7.8.4 String Literals
3480
3481
    function scanStringLiteral() {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
3482
        var str = '', quote, start, ch, code, unescaped, restore, octal = false;
3483
3484
        quote = source[index];
3485
        assert((quote === '\'' || quote === '"'),
3486
            'String literal must starts with a quote');
3487
3488
        start = index;
3489
        ++index;
3490
3491
        while (index < length) {
0 ignored issues
show
Bug introduced by
The variable index is changed as part of the while loop for example by index++ on line 3492. Only the value of the last iteration will be visible in this function if it is called after the loop.
Loading history...
3492
            ch = source[index++];
3493
3494
            if (ch === quote) {
3495
                quote = '';
3496
                break;
3497
            } else if (ch === '\\') {
3498
                ch = source[index++];
3499
                if (!ch || !isLineTerminator(ch.charCodeAt(0))) {
3500
                    switch (ch) {
3501
                    case 'n':
3502
                        str += '\n';
3503
                        break;
3504
                    case 'r':
3505
                        str += '\r';
3506
                        break;
3507
                    case 't':
3508
                        str += '\t';
3509
                        break;
3510
                    case 'u':
3511
                    case 'x':
3512
                        if (source[index] === '{') {
3513
                            ++index;
3514
                            str += scanUnicodeCodePointEscape();
3515
                        } else {
3516
                            restore = index;
3517
                            unescaped = scanHexEscape(ch);
3518
                            if (unescaped) {
3519
                                str += unescaped;
3520
                            } else {
3521
                                index = restore;
3522
                                str += ch;
3523
                            }
3524
                        }
3525
                        break;
3526
                    case 'b':
3527
                        str += '\b';
3528
                        break;
3529
                    case 'f':
3530
                        str += '\f';
3531
                        break;
3532
                    case 'v':
3533
                        str += '\x0B';
3534
                        break;
3535
3536
                    default:
3537
                        if (isOctalDigit(ch)) {
3538
                            code = '01234567'.indexOf(ch);
3539
3540
                            // \0 is not octal escape sequence
3541
                            if (code !== 0) {
3542
                                octal = true;
3543
                            }
3544
3545
                            /* istanbul ignore else */
3546
                            if (index < length && isOctalDigit(source[index])) {
3547
                                octal = true;
3548
                                code = code * 8 + '01234567'.indexOf(source[index++]);
3549
3550
                                // 3 digits are only allowed when string starts
3551
                                // with 0, 1, 2, 3
3552
                                if ('0123'.indexOf(ch) >= 0 &&
3553
                                        index < length &&
3554
                                        isOctalDigit(source[index])) {
3555
                                    code = code * 8 + '01234567'.indexOf(source[index++]);
3556
                                }
3557
                            }
3558
                            str += String.fromCharCode(code);
3559
                        } else {
3560
                            str += ch;
3561
                        }
3562
                        break;
3563
                    }
3564
                } else {
3565
                    ++lineNumber;
0 ignored issues
show
Bug introduced by
The variable lineNumber seems to not be initialized for all possible execution paths.
Loading history...
3566
                    if (ch === '\r' && source[index] === '\n') {
3567
                        ++index;
3568
                    }
3569
                    lineStart = index;
3570
                }
3571
            } else if (isLineTerminator(ch.charCodeAt(0))) {
3572
                break;
3573
            } else {
3574
                str += ch;
3575
            }
3576
        }
3577
3578
        if (quote !== '') {
3579
            throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
3580
        }
3581
3582
        return {
3583
            type: Token.StringLiteral,
3584
            value: str,
3585
            octal: octal,
3586
            lineNumber: lineNumber,
3587
            lineStart: lineStart,
0 ignored issues
show
Bug introduced by
The variable lineStart seems to not be initialized for all possible execution paths.
Loading history...
3588
            range: [start, index]
3589
        };
3590
    }
3591
3592
    function scanTemplate() {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
3593
        var cooked = '', ch, start, terminated, tail, restore, unescaped, code, octal;
3594
3595
        terminated = false;
3596
        tail = false;
3597
        start = index;
3598
3599
        ++index;
3600
3601
        while (index < length) {
0 ignored issues
show
Bug introduced by
The variable index is changed as part of the while loop for example by index++ on line 3665. Only the value of the last iteration will be visible in this function if it is called after the loop.
Loading history...
3602
            ch = source[index++];
3603
            if (ch === '`') {
3604
                tail = true;
3605
                terminated = true;
3606
                break;
3607
            } else if (ch === '$') {
3608
                if (source[index] === '{') {
3609
                    ++index;
3610
                    terminated = true;
3611
                    break;
3612
                }
3613
                cooked += ch;
3614
            } else if (ch === '\\') {
3615
                ch = source[index++];
3616
                if (!isLineTerminator(ch.charCodeAt(0))) {
3617
                    switch (ch) {
3618
                    case 'n':
3619
                        cooked += '\n';
3620
                        break;
3621
                    case 'r':
3622
                        cooked += '\r';
3623
                        break;
3624
                    case 't':
3625
                        cooked += '\t';
3626
                        break;
3627
                    case 'u':
3628
                    case 'x':
3629
                        if (source[index] === '{') {
3630
                            ++index;
3631
                            cooked += scanUnicodeCodePointEscape();
3632
                        } else {
3633
                            restore = index;
3634
                            unescaped = scanHexEscape(ch);
3635
                            if (unescaped) {
3636
                                cooked += unescaped;
3637
                            } else {
3638
                                index = restore;
3639
                                cooked += ch;
3640
                            }
3641
                        }
3642
                        break;
3643
                    case 'b':
3644
                        cooked += '\b';
3645
                        break;
3646
                    case 'f':
3647
                        cooked += '\f';
3648
                        break;
3649
                    case 'v':
3650
                        cooked += '\v';
3651
                        break;
3652
3653
                    default:
3654
                        if (isOctalDigit(ch)) {
3655
                            code = '01234567'.indexOf(ch);
3656
3657
                            // \0 is not octal escape sequence
3658
                            if (code !== 0) {
3659
                                octal = true;
3660
                            }
3661
3662
                            /* istanbul ignore else */
3663
                            if (index < length && isOctalDigit(source[index])) {
3664
                                octal = true;
3665
                                code = code * 8 + '01234567'.indexOf(source[index++]);
3666
3667
                                // 3 digits are only allowed when string starts
3668
                                // with 0, 1, 2, 3
3669
                                if ('0123'.indexOf(ch) >= 0 &&
3670
                                        index < length &&
3671
                                        isOctalDigit(source[index])) {
3672
                                    code = code * 8 + '01234567'.indexOf(source[index++]);
3673
                                }
3674
                            }
3675
                            cooked += String.fromCharCode(code);
3676
                        } else {
3677
                            cooked += ch;
3678
                        }
3679
                        break;
3680
                    }
3681
                } else {
3682
                    ++lineNumber;
0 ignored issues
show
Bug introduced by
The variable lineNumber seems to not be initialized for all possible execution paths.
Loading history...
3683
                    if (ch === '\r' && source[index] === '\n') {
3684
                        ++index;
3685
                    }
3686
                    lineStart = index;
3687
                }
3688
            } else if (isLineTerminator(ch.charCodeAt(0))) {
3689
                ++lineNumber;
3690
                if (ch === '\r' && source[index] === '\n') {
3691
                    ++index;
3692
                }
3693
                lineStart = index;
3694
                cooked += '\n';
3695
            } else {
3696
                cooked += ch;
3697
            }
3698
        }
3699
3700
        if (!terminated) {
3701
            throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
3702
        }
3703
3704
        return {
3705
            type: Token.Template,
3706
            value: {
3707
                cooked: cooked,
3708
                raw: source.slice(start + 1, index - ((tail) ? 1 : 2))
3709
            },
3710
            tail: tail,
3711
            octal: octal,
0 ignored issues
show
Bug introduced by
The variable octal seems to not be initialized for all possible execution paths.
Loading history...
3712
            lineNumber: lineNumber,
3713
            lineStart: lineStart,
0 ignored issues
show
Bug introduced by
The variable lineStart seems to not be initialized for all possible execution paths.
Loading history...
3714
            range: [start, index]
3715
        };
3716
    }
3717
3718
    function scanTemplateElement(option) {
3719
        var startsWith, template;
3720
3721
        lookahead = null;
3722
        skipComment();
3723
3724
        startsWith = (option.head) ? '`' : '}';
3725
3726
        if (source[index] !== startsWith) {
3727
            throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
3728
        }
3729
3730
        template = scanTemplate();
3731
3732
        peek();
3733
3734
        return template;
3735
    }
3736
3737
    function testRegExp(pattern, flags) {
3738
        var tmp = pattern,
3739
            value;
3740
3741
        if (flags.indexOf('u') >= 0) {
3742
            // Replace each astral symbol and every Unicode code point
3743
            // escape sequence with a single ASCII symbol to avoid throwing on
3744
            // regular expressions that are only valid in combination with the
3745
            // `/u` flag.
3746
            // Note: replacing with the ASCII symbol `x` might cause false
3747
            // negatives in unlikely scenarios. For example, `[\u{61}-b]` is a
3748
            // perfectly valid pattern that is equivalent to `[a-b]`, but it
3749
            // would be replaced by `[x-b]` which throws an error.
3750
            tmp = tmp
3751
                .replace(/\\u\{([0-9a-fA-F]+)\}/g, function ($0, $1) {
3752
                    if (parseInt($1, 16) <= 0x10FFFF) {
3753
                        return 'x';
3754
                    }
3755
                    throwError({}, Messages.InvalidRegExp);
0 ignored issues
show
Best Practice introduced by
There is no return statement in this branch, but you do return something in other branches. Did you maybe miss it? If you do not want to return anything, consider adding return undefined; explicitly.
Loading history...
3756
                })
3757
                .replace(/[\uD800-\uDBFF][\uDC00-\uDFFF]/g, 'x');
3758
        }
3759
3760
        // First, detect invalid regular expressions.
3761
        try {
3762
            value = new RegExp(tmp);
0 ignored issues
show
Unused Code introduced by
The variable value seems to be never used. Consider removing it.
Loading history...
3763
        } catch (e) {
3764
            throwError({}, Messages.InvalidRegExp);
3765
        }
3766
3767
        // Return a regular expression object for this pattern-flag pair, or
3768
        // `null` in case the current environment doesn't support the flags it
3769
        // uses.
3770
        try {
3771
            return new RegExp(pattern, flags);
3772
        } catch (exception) {
3773
            return null;
3774
        }
3775
    }
3776
3777
    function scanRegExpBody() {
3778
        var ch, str, classMarker, terminated, body;
3779
3780
        ch = source[index];
3781
        assert(ch === '/', 'Regular expression literal must start with a slash');
3782
        str = source[index++];
3783
3784
        classMarker = false;
3785
        terminated = false;
3786
        while (index < length) {
0 ignored issues
show
Bug introduced by
The variable index is changed as part of the while loop for example by index++ on line 3790. Only the value of the last iteration will be visible in this function if it is called after the loop.
Loading history...
3787
            ch = source[index++];
3788
            str += ch;
3789
            if (ch === '\\') {
3790
                ch = source[index++];
3791
                // ECMA-262 7.8.5
3792
                if (isLineTerminator(ch.charCodeAt(0))) {
3793
                    throwError({}, Messages.UnterminatedRegExp);
3794
                }
3795
                str += ch;
3796
            } else if (isLineTerminator(ch.charCodeAt(0))) {
3797
                throwError({}, Messages.UnterminatedRegExp);
3798
            } else if (classMarker) {
3799
                if (ch === ']') {
3800
                    classMarker = false;
3801
                }
3802
            } else {
3803
                if (ch === '/') {
3804
                    terminated = true;
3805
                    break;
3806
                } else if (ch === '[') {
3807
                    classMarker = true;
3808
                }
3809
            }
3810
        }
3811
3812
        if (!terminated) {
3813
            throwError({}, Messages.UnterminatedRegExp);
3814
        }
3815
3816
        // Exclude leading and trailing slash.
3817
        body = str.substr(1, str.length - 2);
3818
        return {
3819
            value: body,
3820
            literal: str
3821
        };
3822
    }
3823
3824
    function scanRegExpFlags() {
3825
        var ch, str, flags, restore;
3826
3827
        str = '';
3828
        flags = '';
3829
        while (index < length) {
0 ignored issues
show
Comprehensibility Bug introduced by
The variable index does not seem to be initialized in case the while loop on line 3829 is not entered. Are you sure this can never be the case?
Loading history...
3830
            ch = source[index];
3831
            if (!isIdentifierPart(ch.charCodeAt(0))) {
3832
                break;
3833
            }
3834
3835
            ++index;
3836
            if (ch === '\\' && index < length) {
0 ignored issues
show
Bug introduced by
The variable index is changed as part of the while loop for example by ++index on line 3835. Only the value of the last iteration will be visible in this function if it is called after the loop.
Loading history...
3837
                ch = source[index];
3838
                if (ch === 'u') {
3839
                    ++index;
3840
                    restore = index;
3841
                    ch = scanHexEscape('u');
3842
                    if (ch) {
3843
                        flags += ch;
3844
                        for (str += '\\u'; restore < index; ++restore) {
3845
                            str += source[restore];
3846
                        }
3847
                    } else {
3848
                        index = restore;
3849
                        flags += 'u';
3850
                        str += '\\u';
3851
                    }
3852
                    throwErrorTolerant({}, Messages.UnexpectedToken, 'ILLEGAL');
3853
                } else {
3854
                    str += '\\';
3855
                    throwErrorTolerant({}, Messages.UnexpectedToken, 'ILLEGAL');
3856
                }
3857
            } else {
3858
                flags += ch;
3859
                str += ch;
3860
            }
3861
        }
3862
3863
        return {
3864
            value: flags,
3865
            literal: str
3866
        };
3867
    }
3868
3869
    function scanRegExp() {
3870
        var start, body, flags, value;
3871
3872
        lookahead = null;
3873
        skipComment();
3874
        start = index;
3875
3876
        body = scanRegExpBody();
3877
        flags = scanRegExpFlags();
3878
        value = testRegExp(body.value, flags.value);
3879
3880
        if (extra.tokenize) {
3881
            return {
3882
                type: Token.RegularExpression,
3883
                value: value,
3884
                regex: {
3885
                    pattern: body.value,
3886
                    flags: flags.value
3887
                },
3888
                lineNumber: lineNumber,
3889
                lineStart: lineStart,
3890
                range: [start, index]
3891
            };
3892
        }
3893
3894
        return {
3895
            literal: body.literal + flags.literal,
3896
            value: value,
3897
            regex: {
3898
                pattern: body.value,
3899
                flags: flags.value
3900
            },
3901
            range: [start, index]
3902
        };
3903
    }
3904
3905
    function isIdentifierName(token) {
3906
        return token.type === Token.Identifier ||
3907
            token.type === Token.Keyword ||
3908
            token.type === Token.BooleanLiteral ||
3909
            token.type === Token.NullLiteral;
3910
    }
3911
3912
    function advanceSlash() {
3913
        var prevToken,
3914
            checkToken;
3915
        // Using the following algorithm:
3916
        // https://github.com/mozilla/sweet.js/wiki/design
3917
        prevToken = extra.tokens[extra.tokens.length - 1];
3918
        if (!prevToken) {
3919
            // Nothing before that: it cannot be a division.
3920
            return scanRegExp();
3921
        }
3922
        if (prevToken.type === 'Punctuator') {
3923
            if (prevToken.value === ')') {
3924
                checkToken = extra.tokens[extra.openParenToken - 1];
3925
                if (checkToken &&
3926
                        checkToken.type === 'Keyword' &&
3927
                        (checkToken.value === 'if' ||
3928
                         checkToken.value === 'while' ||
3929
                         checkToken.value === 'for' ||
3930
                         checkToken.value === 'with')) {
3931
                    return scanRegExp();
3932
                }
3933
                return scanPunctuator();
3934
            }
3935
            if (prevToken.value === '}') {
3936
                // Dividing a function by anything makes little sense,
3937
                // but we have to check for that.
3938
                if (extra.tokens[extra.openCurlyToken - 3] &&
3939
                        extra.tokens[extra.openCurlyToken - 3].type === 'Keyword') {
3940
                    // Anonymous function.
3941
                    checkToken = extra.tokens[extra.openCurlyToken - 4];
3942
                    if (!checkToken) {
3943
                        return scanPunctuator();
3944
                    }
3945
                } else if (extra.tokens[extra.openCurlyToken - 4] &&
3946
                        extra.tokens[extra.openCurlyToken - 4].type === 'Keyword') {
3947
                    // Named function.
3948
                    checkToken = extra.tokens[extra.openCurlyToken - 5];
3949
                    if (!checkToken) {
3950
                        return scanRegExp();
3951
                    }
3952
                } else {
3953
                    return scanPunctuator();
3954
                }
3955
                // checkToken determines whether the function is
3956
                // a declaration or an expression.
3957
                if (FnExprTokens.indexOf(checkToken.value) >= 0) {
3958
                    // It is an expression.
3959
                    return scanPunctuator();
3960
                }
3961
                // It is a declaration.
3962
                return scanRegExp();
3963
            }
3964
            return scanRegExp();
3965
        }
3966
        if (prevToken.type === 'Keyword' && prevToken.value !== 'this') {
3967
            return scanRegExp();
3968
        }
3969
        return scanPunctuator();
3970
    }
3971
3972
    function advance() {
3973
        var ch;
3974
3975
        if (!state.inJSXChild) {
3976
            skipComment();
3977
        }
3978
3979
        if (index >= length) {
3980
            return {
3981
                type: Token.EOF,
3982
                lineNumber: lineNumber,
3983
                lineStart: lineStart,
3984
                range: [index, index]
3985
            };
3986
        }
3987
3988
        if (state.inJSXChild) {
3989
            return advanceJSXChild();
3990
        }
3991
3992
        ch = source.charCodeAt(index);
3993
3994
        // Very common: ( and ) and ;
3995
        if (ch === 40 || ch === 41 || ch === 58) {
3996
            return scanPunctuator();
3997
        }
3998
3999
        // String literal starts with single quote (#39) or double quote (#34).
4000
        if (ch === 39 || ch === 34) {
4001
            if (state.inJSXTag) {
4002
                return scanJSXStringLiteral();
4003
            }
4004
            return scanStringLiteral();
4005
        }
4006
4007
        if (state.inJSXTag && isJSXIdentifierStart(ch)) {
4008
            return scanJSXIdentifier();
4009
        }
4010
4011
        if (ch === 96) {
4012
            return scanTemplate();
4013
        }
4014
        if (isIdentifierStart(ch)) {
4015
            return scanIdentifier();
4016
        }
4017
4018
        // Dot (.) char #46 can also start a floating-point number, hence the need
4019
        // to check the next character.
4020
        if (ch === 46) {
4021
            if (isDecimalDigit(source.charCodeAt(index + 1))) {
4022
                return scanNumericLiteral();
4023
            }
4024
            return scanPunctuator();
4025
        }
4026
4027
        if (isDecimalDigit(ch)) {
4028
            return scanNumericLiteral();
4029
        }
4030
4031
        // Slash (/) char #47 can also start a regex.
4032
        if (extra.tokenize && ch === 47) {
4033
            return advanceSlash();
4034
        }
4035
4036
        return scanPunctuator();
4037
    }
4038
4039
    function lex() {
4040
        var token;
4041
4042
        token = lookahead;
4043
        index = token.range[1];
4044
        lineNumber = token.lineNumber;
4045
        lineStart = token.lineStart;
4046
4047
        lookahead = advance();
4048
4049
        index = token.range[1];
4050
        lineNumber = token.lineNumber;
4051
        lineStart = token.lineStart;
4052
4053
        return token;
4054
    }
4055
4056
    function peek() {
4057
        var pos, line, start;
4058
4059
        pos = index;
4060
        line = lineNumber;
4061
        start = lineStart;
4062
        lookahead = advance();
4063
        index = pos;
4064
        lineNumber = line;
4065
        lineStart = start;
4066
    }
4067
4068
    function lookahead2() {
4069
        var adv, pos, line, start, result;
4070
4071
        // If we are collecting the tokens, don't grab the next one yet.
4072
        /* istanbul ignore next */
4073
        adv = (typeof extra.advance === 'function') ? extra.advance : advance;
4074
4075
        pos = index;
4076
        line = lineNumber;
4077
        start = lineStart;
4078
4079
        // Scan for the next immediate token.
4080
        /* istanbul ignore if */
4081
        if (lookahead === null) {
4082
            lookahead = adv();
4083
        }
4084
        index = lookahead.range[1];
0 ignored issues
show
Bug introduced by
The variable lookahead does not seem to be initialized in case lookahead === null on line 4081 is false. Are you sure this can never be the case?
Loading history...
4085
        lineNumber = lookahead.lineNumber;
4086
        lineStart = lookahead.lineStart;
4087
4088
        // Grab the token right after.
4089
        result = adv();
4090
        index = pos;
4091
        lineNumber = line;
4092
        lineStart = start;
4093
4094
        return result;
4095
    }
4096
4097
    function rewind(token) {
4098
        index = token.range[0];
4099
        lineNumber = token.lineNumber;
4100
        lineStart = token.lineStart;
4101
        lookahead = token;
4102
    }
4103
4104
    function markerCreate() {
4105
        if (!extra.loc && !extra.range) {
4106
            return undefined;
4107
        }
4108
        skipComment();
4109
        return {offset: index, line: lineNumber, col: index - lineStart};
4110
    }
4111
4112
    function markerCreatePreserveWhitespace() {
4113
        if (!extra.loc && !extra.range) {
4114
            return undefined;
4115
        }
4116
        return {offset: index, line: lineNumber, col: index - lineStart};
4117
    }
4118
4119
    function processComment(node) {
4120
        var lastChild,
4121
            trailingComments,
4122
            bottomRight = extra.bottomRightStack,
4123
            last = bottomRight[bottomRight.length - 1];
4124
4125
        if (node.type === Syntax.Program) {
4126
            /* istanbul ignore else */
4127
            if (node.body.length > 0) {
4128
                return;
4129
            }
4130
        }
4131
4132
        if (extra.trailingComments.length > 0) {
4133
            if (extra.trailingComments[0].range[0] >= node.range[1]) {
4134
                trailingComments = extra.trailingComments;
4135
                extra.trailingComments = [];
4136
            } else {
4137
                extra.trailingComments.length = 0;
4138
            }
4139
        } else {
4140
            if (last && last.trailingComments && last.trailingComments[0].range[0] >= node.range[1]) {
4141
                trailingComments = last.trailingComments;
4142
                delete last.trailingComments;
4143
            }
4144
        }
4145
4146
        // Eating the stack.
4147
        if (last) {
4148
            while (last && last.range[0] >= node.range[0]) {
4149
                lastChild = last;
4150
                last = bottomRight.pop();
4151
            }
4152
        }
4153
4154
        if (lastChild) {
4155
            if (lastChild.leadingComments && lastChild.leadingComments[lastChild.leadingComments.length - 1].range[1] <= node.range[0]) {
4156
                node.leadingComments = lastChild.leadingComments;
4157
                delete lastChild.leadingComments;
4158
            }
4159
        } else if (extra.leadingComments.length > 0 && extra.leadingComments[extra.leadingComments.length - 1].range[1] <= node.range[0]) {
4160
            node.leadingComments = extra.leadingComments;
4161
            extra.leadingComments = [];
4162
        }
4163
4164
        if (trailingComments) {
4165
            node.trailingComments = trailingComments;
4166
        }
4167
4168
        bottomRight.push(node);
4169
    }
4170
4171
    function markerApply(marker, node) {
4172
        if (extra.range) {
4173
            node.range = [marker.offset, index];
4174
        }
4175
        if (extra.loc) {
4176
            node.loc = {
4177
                start: {
4178
                    line: marker.line,
4179
                    column: marker.col
4180
                },
4181
                end: {
4182
                    line: lineNumber,
4183
                    column: index - lineStart
4184
                }
4185
            };
4186
            node = delegate.postProcess(node);
4187
        }
4188
        if (extra.attachComment) {
4189
            processComment(node);
4190
        }
4191
        return node;
4192
    }
4193
4194
    SyntaxTreeDelegate = {
4195
4196
        name: 'SyntaxTree',
4197
4198
        postProcess: function (node) {
4199
            return node;
4200
        },
4201
4202
        createArrayExpression: function (elements) {
4203
            return {
4204
                type: Syntax.ArrayExpression,
4205
                elements: elements
4206
            };
4207
        },
4208
4209
        createAssignmentExpression: function (operator, left, right) {
4210
            return {
4211
                type: Syntax.AssignmentExpression,
4212
                operator: operator,
4213
                left: left,
4214
                right: right
4215
            };
4216
        },
4217
4218
        createBinaryExpression: function (operator, left, right) {
4219
            var type = (operator === '||' || operator === '&&') ? Syntax.LogicalExpression :
4220
                        Syntax.BinaryExpression;
4221
            return {
4222
                type: type,
4223
                operator: operator,
4224
                left: left,
4225
                right: right
4226
            };
4227
        },
4228
4229
        createBlockStatement: function (body) {
4230
            return {
4231
                type: Syntax.BlockStatement,
4232
                body: body
4233
            };
4234
        },
4235
4236
        createBreakStatement: function (label) {
4237
            return {
4238
                type: Syntax.BreakStatement,
4239
                label: label
4240
            };
4241
        },
4242
4243
        createCallExpression: function (callee, args) {
4244
            return {
4245
                type: Syntax.CallExpression,
4246
                callee: callee,
4247
                'arguments': args
4248
            };
4249
        },
4250
4251
        createCatchClause: function (param, body) {
4252
            return {
4253
                type: Syntax.CatchClause,
4254
                param: param,
4255
                body: body
4256
            };
4257
        },
4258
4259
        createConditionalExpression: function (test, consequent, alternate) {
4260
            return {
4261
                type: Syntax.ConditionalExpression,
4262
                test: test,
4263
                consequent: consequent,
4264
                alternate: alternate
4265
            };
4266
        },
4267
4268
        createContinueStatement: function (label) {
4269
            return {
4270
                type: Syntax.ContinueStatement,
4271
                label: label
4272
            };
4273
        },
4274
4275
        createDebuggerStatement: function () {
4276
            return {
4277
                type: Syntax.DebuggerStatement
4278
            };
4279
        },
4280
4281
        createDoWhileStatement: function (body, test) {
4282
            return {
4283
                type: Syntax.DoWhileStatement,
4284
                body: body,
4285
                test: test
4286
            };
4287
        },
4288
4289
        createEmptyStatement: function () {
4290
            return {
4291
                type: Syntax.EmptyStatement
4292
            };
4293
        },
4294
4295
        createExpressionStatement: function (expression) {
4296
            return {
4297
                type: Syntax.ExpressionStatement,
4298
                expression: expression
4299
            };
4300
        },
4301
4302
        createForStatement: function (init, test, update, body) {
4303
            return {
4304
                type: Syntax.ForStatement,
4305
                init: init,
4306
                test: test,
4307
                update: update,
4308
                body: body
4309
            };
4310
        },
4311
4312
        createForInStatement: function (left, right, body) {
4313
            return {
4314
                type: Syntax.ForInStatement,
4315
                left: left,
4316
                right: right,
4317
                body: body,
4318
                each: false
4319
            };
4320
        },
4321
4322
        createForOfStatement: function (left, right, body) {
4323
            return {
4324
                type: Syntax.ForOfStatement,
4325
                left: left,
4326
                right: right,
4327
                body: body
4328
            };
4329
        },
4330
4331
        createFunctionDeclaration: function (id, params, defaults, body, rest, generator, expression,
4332
                                             isAsync, returnType, typeParameters) {
4333
            var funDecl = {
4334
                type: Syntax.FunctionDeclaration,
4335
                id: id,
4336
                params: params,
4337
                defaults: defaults,
4338
                body: body,
4339
                rest: rest,
4340
                generator: generator,
4341
                expression: expression,
4342
                returnType: returnType,
4343
                typeParameters: typeParameters
4344
            };
4345
4346
            if (isAsync) {
4347
                funDecl.async = true;
4348
            }
4349
4350
            return funDecl;
4351
        },
4352
4353
        createFunctionExpression: function (id, params, defaults, body, rest, generator, expression,
4354
                                            isAsync, returnType, typeParameters) {
4355
            var funExpr = {
4356
                type: Syntax.FunctionExpression,
4357
                id: id,
4358
                params: params,
4359
                defaults: defaults,
4360
                body: body,
4361
                rest: rest,
4362
                generator: generator,
4363
                expression: expression,
4364
                returnType: returnType,
4365
                typeParameters: typeParameters
4366
            };
4367
4368
            if (isAsync) {
4369
                funExpr.async = true;
4370
            }
4371
4372
            return funExpr;
4373
        },
4374
4375
        createIdentifier: function (name) {
4376
            return {
4377
                type: Syntax.Identifier,
4378
                name: name,
4379
                // Only here to initialize the shape of the object to ensure
4380
                // that the 'typeAnnotation' key is ordered before others that
4381
                // are added later (like 'loc' and 'range'). This just helps
4382
                // keep the shape of Identifier nodes consistent with everything
4383
                // else.
4384
                typeAnnotation: undefined,
4385
                optional: undefined
4386
            };
4387
        },
4388
4389
        createTypeAnnotation: function (typeAnnotation) {
4390
            return {
4391
                type: Syntax.TypeAnnotation,
4392
                typeAnnotation: typeAnnotation
4393
            };
4394
        },
4395
4396
        createTypeCast: function (expression, typeAnnotation) {
4397
            return {
4398
                type: Syntax.TypeCastExpression,
4399
                expression: expression,
4400
                typeAnnotation: typeAnnotation
4401
            };
4402
        },
4403
4404
        createFunctionTypeAnnotation: function (params, returnType, rest, typeParameters) {
4405
            return {
4406
                type: Syntax.FunctionTypeAnnotation,
4407
                params: params,
4408
                returnType: returnType,
4409
                rest: rest,
4410
                typeParameters: typeParameters
4411
            };
4412
        },
4413
4414
        createFunctionTypeParam: function (name, typeAnnotation, optional) {
4415
            return {
4416
                type: Syntax.FunctionTypeParam,
4417
                name: name,
4418
                typeAnnotation: typeAnnotation,
4419
                optional: optional
4420
            };
4421
        },
4422
4423
        createNullableTypeAnnotation: function (typeAnnotation) {
4424
            return {
4425
                type: Syntax.NullableTypeAnnotation,
4426
                typeAnnotation: typeAnnotation
4427
            };
4428
        },
4429
4430
        createArrayTypeAnnotation: function (elementType) {
4431
            return {
4432
                type: Syntax.ArrayTypeAnnotation,
4433
                elementType: elementType
4434
            };
4435
        },
4436
4437
        createGenericTypeAnnotation: function (id, typeParameters) {
4438
            return {
4439
                type: Syntax.GenericTypeAnnotation,
4440
                id: id,
4441
                typeParameters: typeParameters
4442
            };
4443
        },
4444
4445
        createQualifiedTypeIdentifier: function (qualification, id) {
4446
            return {
4447
                type: Syntax.QualifiedTypeIdentifier,
4448
                qualification: qualification,
4449
                id: id
4450
            };
4451
        },
4452
4453
        createTypeParameterDeclaration: function (params) {
4454
            return {
4455
                type: Syntax.TypeParameterDeclaration,
4456
                params: params
4457
            };
4458
        },
4459
4460
        createTypeParameterInstantiation: function (params) {
4461
            return {
4462
                type: Syntax.TypeParameterInstantiation,
4463
                params: params
4464
            };
4465
        },
4466
4467
        createAnyTypeAnnotation: function () {
4468
            return {
4469
                type: Syntax.AnyTypeAnnotation
4470
            };
4471
        },
4472
4473
        createBooleanTypeAnnotation: function () {
4474
            return {
4475
                type: Syntax.BooleanTypeAnnotation
4476
            };
4477
        },
4478
4479
        createNumberTypeAnnotation: function () {
4480
            return {
4481
                type: Syntax.NumberTypeAnnotation
4482
            };
4483
        },
4484
4485
        createStringTypeAnnotation: function () {
4486
            return {
4487
                type: Syntax.StringTypeAnnotation
4488
            };
4489
        },
4490
4491
        createStringLiteralTypeAnnotation: function (token) {
4492
            return {
4493
                type: Syntax.StringLiteralTypeAnnotation,
4494
                value: token.value,
4495
                raw: source.slice(token.range[0], token.range[1])
4496
            };
4497
        },
4498
4499
        createVoidTypeAnnotation: function () {
4500
            return {
4501
                type: Syntax.VoidTypeAnnotation
4502
            };
4503
        },
4504
4505
        createTypeofTypeAnnotation: function (argument) {
4506
            return {
4507
                type: Syntax.TypeofTypeAnnotation,
4508
                argument: argument
4509
            };
4510
        },
4511
4512
        createTupleTypeAnnotation: function (types) {
4513
            return {
4514
                type: Syntax.TupleTypeAnnotation,
4515
                types: types
4516
            };
4517
        },
4518
4519
        createObjectTypeAnnotation: function (properties, indexers, callProperties) {
4520
            return {
4521
                type: Syntax.ObjectTypeAnnotation,
4522
                properties: properties,
4523
                indexers: indexers,
4524
                callProperties: callProperties
4525
            };
4526
        },
4527
4528
        createObjectTypeIndexer: function (id, key, value, isStatic) {
4529
            return {
4530
                type: Syntax.ObjectTypeIndexer,
4531
                id: id,
4532
                key: key,
4533
                value: value,
4534
                "static": isStatic
4535
            };
4536
        },
4537
4538
        createObjectTypeCallProperty: function (value, isStatic) {
4539
            return {
4540
                type: Syntax.ObjectTypeCallProperty,
4541
                value: value,
4542
                "static": isStatic
4543
            };
4544
        },
4545
4546
        createObjectTypeProperty: function (key, value, optional, isStatic) {
4547
            return {
4548
                type: Syntax.ObjectTypeProperty,
4549
                key: key,
4550
                value: value,
4551
                optional: optional,
4552
                "static": isStatic
4553
            };
4554
        },
4555
4556
        createUnionTypeAnnotation: function (types) {
4557
            return {
4558
                type: Syntax.UnionTypeAnnotation,
4559
                types: types
4560
            };
4561
        },
4562
4563
        createIntersectionTypeAnnotation: function (types) {
4564
            return {
4565
                type: Syntax.IntersectionTypeAnnotation,
4566
                types: types
4567
            };
4568
        },
4569
4570
        createTypeAlias: function (id, typeParameters, right) {
4571
            return {
4572
                type: Syntax.TypeAlias,
4573
                id: id,
4574
                typeParameters: typeParameters,
4575
                right: right
4576
            };
4577
        },
4578
4579
        createInterface: function (id, typeParameters, body, extended) {
4580
            return {
4581
                type: Syntax.InterfaceDeclaration,
4582
                id: id,
4583
                typeParameters: typeParameters,
4584
                body: body,
4585
                "extends": extended
4586
            };
4587
        },
4588
4589
        createInterfaceExtends: function (id, typeParameters) {
4590
            return {
4591
                type: Syntax.InterfaceExtends,
4592
                id: id,
4593
                typeParameters: typeParameters
4594
            };
4595
        },
4596
4597
        createDeclareFunction: function (id) {
4598
            return {
4599
                type: Syntax.DeclareFunction,
4600
                id: id
4601
            };
4602
        },
4603
4604
        createDeclareVariable: function (id) {
4605
            return {
4606
                type: Syntax.DeclareVariable,
4607
                id: id
4608
            };
4609
        },
4610
4611
        createDeclareModule: function (id, body) {
4612
            return {
4613
                type: Syntax.DeclareModule,
4614
                id: id,
4615
                body: body
4616
            };
4617
        },
4618
4619
        createJSXAttribute: function (name, value) {
4620
            return {
4621
                type: Syntax.JSXAttribute,
4622
                name: name,
4623
                value: value || null
4624
            };
4625
        },
4626
4627
        createJSXSpreadAttribute: function (argument) {
4628
            return {
4629
                type: Syntax.JSXSpreadAttribute,
4630
                argument: argument
4631
            };
4632
        },
4633
4634
        createJSXIdentifier: function (name) {
4635
            return {
4636
                type: Syntax.JSXIdentifier,
4637
                name: name
4638
            };
4639
        },
4640
4641
        createJSXNamespacedName: function (namespace, name) {
4642
            return {
4643
                type: Syntax.JSXNamespacedName,
4644
                namespace: namespace,
4645
                name: name
4646
            };
4647
        },
4648
4649
        createJSXMemberExpression: function (object, property) {
4650
            return {
4651
                type: Syntax.JSXMemberExpression,
4652
                object: object,
4653
                property: property
4654
            };
4655
        },
4656
4657
        createJSXElement: function (openingElement, closingElement, children) {
4658
            return {
4659
                type: Syntax.JSXElement,
4660
                openingElement: openingElement,
4661
                closingElement: closingElement,
4662
                children: children
4663
            };
4664
        },
4665
4666
        createJSXEmptyExpression: function () {
4667
            return {
4668
                type: Syntax.JSXEmptyExpression
4669
            };
4670
        },
4671
4672
        createJSXExpressionContainer: function (expression) {
4673
            return {
4674
                type: Syntax.JSXExpressionContainer,
4675
                expression: expression
4676
            };
4677
        },
4678
4679
        createJSXOpeningElement: function (name, attributes, selfClosing) {
4680
            return {
4681
                type: Syntax.JSXOpeningElement,
4682
                name: name,
4683
                selfClosing: selfClosing,
4684
                attributes: attributes
4685
            };
4686
        },
4687
4688
        createJSXClosingElement: function (name) {
4689
            return {
4690
                type: Syntax.JSXClosingElement,
4691
                name: name
4692
            };
4693
        },
4694
4695
        createIfStatement: function (test, consequent, alternate) {
4696
            return {
4697
                type: Syntax.IfStatement,
4698
                test: test,
4699
                consequent: consequent,
4700
                alternate: alternate
4701
            };
4702
        },
4703
4704
        createLabeledStatement: function (label, body) {
4705
            return {
4706
                type: Syntax.LabeledStatement,
4707
                label: label,
4708
                body: body
4709
            };
4710
        },
4711
4712
        createLiteral: function (token) {
4713
            var object = {
4714
                type: Syntax.Literal,
4715
                value: token.value,
4716
                raw: source.slice(token.range[0], token.range[1])
4717
            };
4718
            if (token.regex) {
4719
                object.regex = token.regex;
4720
            }
4721
            return object;
4722
        },
4723
4724
        createMemberExpression: function (accessor, object, property) {
4725
            return {
4726
                type: Syntax.MemberExpression,
4727
                computed: accessor === '[',
4728
                object: object,
4729
                property: property
4730
            };
4731
        },
4732
4733
        createNewExpression: function (callee, args) {
4734
            return {
4735
                type: Syntax.NewExpression,
4736
                callee: callee,
4737
                'arguments': args
4738
            };
4739
        },
4740
4741
        createObjectExpression: function (properties) {
4742
            return {
4743
                type: Syntax.ObjectExpression,
4744
                properties: properties
4745
            };
4746
        },
4747
4748
        createPostfixExpression: function (operator, argument) {
4749
            return {
4750
                type: Syntax.UpdateExpression,
4751
                operator: operator,
4752
                argument: argument,
4753
                prefix: false
4754
            };
4755
        },
4756
4757
        createProgram: function (body) {
4758
            return {
4759
                type: Syntax.Program,
4760
                body: body
4761
            };
4762
        },
4763
4764
        createProperty: function (kind, key, value, method, shorthand, computed) {
4765
            return {
4766
                type: Syntax.Property,
4767
                key: key,
4768
                value: value,
4769
                kind: kind,
4770
                method: method,
4771
                shorthand: shorthand,
4772
                computed: computed
4773
            };
4774
        },
4775
4776
        createReturnStatement: function (argument) {
4777
            return {
4778
                type: Syntax.ReturnStatement,
4779
                argument: argument
4780
            };
4781
        },
4782
4783
        createSequenceExpression: function (expressions) {
4784
            return {
4785
                type: Syntax.SequenceExpression,
4786
                expressions: expressions
4787
            };
4788
        },
4789
4790
        createSwitchCase: function (test, consequent) {
4791
            return {
4792
                type: Syntax.SwitchCase,
4793
                test: test,
4794
                consequent: consequent
4795
            };
4796
        },
4797
4798
        createSwitchStatement: function (discriminant, cases) {
4799
            return {
4800
                type: Syntax.SwitchStatement,
4801
                discriminant: discriminant,
4802
                cases: cases
4803
            };
4804
        },
4805
4806
        createThisExpression: function () {
4807
            return {
4808
                type: Syntax.ThisExpression
4809
            };
4810
        },
4811
4812
        createThrowStatement: function (argument) {
4813
            return {
4814
                type: Syntax.ThrowStatement,
4815
                argument: argument
4816
            };
4817
        },
4818
4819
        createTryStatement: function (block, guardedHandlers, handlers, finalizer) {
4820
            return {
4821
                type: Syntax.TryStatement,
4822
                block: block,
4823
                guardedHandlers: guardedHandlers,
4824
                handlers: handlers,
4825
                finalizer: finalizer
4826
            };
4827
        },
4828
4829
        createUnaryExpression: function (operator, argument) {
4830
            if (operator === '++' || operator === '--') {
4831
                return {
4832
                    type: Syntax.UpdateExpression,
4833
                    operator: operator,
4834
                    argument: argument,
4835
                    prefix: true
4836
                };
4837
            }
4838
            return {
4839
                type: Syntax.UnaryExpression,
4840
                operator: operator,
4841
                argument: argument,
4842
                prefix: true
4843
            };
4844
        },
4845
4846
        createVariableDeclaration: function (declarations, kind) {
4847
            return {
4848
                type: Syntax.VariableDeclaration,
4849
                declarations: declarations,
4850
                kind: kind
4851
            };
4852
        },
4853
4854
        createVariableDeclarator: function (id, init) {
4855
            return {
4856
                type: Syntax.VariableDeclarator,
4857
                id: id,
4858
                init: init
4859
            };
4860
        },
4861
4862
        createWhileStatement: function (test, body) {
4863
            return {
4864
                type: Syntax.WhileStatement,
4865
                test: test,
4866
                body: body
4867
            };
4868
        },
4869
4870
        createWithStatement: function (object, body) {
4871
            return {
4872
                type: Syntax.WithStatement,
4873
                object: object,
4874
                body: body
4875
            };
4876
        },
4877
4878
        createTemplateElement: function (value, tail) {
4879
            return {
4880
                type: Syntax.TemplateElement,
4881
                value: value,
4882
                tail: tail
4883
            };
4884
        },
4885
4886
        createTemplateLiteral: function (quasis, expressions) {
4887
            return {
4888
                type: Syntax.TemplateLiteral,
4889
                quasis: quasis,
4890
                expressions: expressions
4891
            };
4892
        },
4893
4894
        createSpreadElement: function (argument) {
4895
            return {
4896
                type: Syntax.SpreadElement,
4897
                argument: argument
4898
            };
4899
        },
4900
4901
        createSpreadProperty: function (argument) {
4902
            return {
4903
                type: Syntax.SpreadProperty,
4904
                argument: argument
4905
            };
4906
        },
4907
4908
        createTaggedTemplateExpression: function (tag, quasi) {
4909
            return {
4910
                type: Syntax.TaggedTemplateExpression,
4911
                tag: tag,
4912
                quasi: quasi
4913
            };
4914
        },
4915
4916
        createArrowFunctionExpression: function (params, defaults, body, rest, expression, isAsync) {
4917
            var arrowExpr = {
4918
                type: Syntax.ArrowFunctionExpression,
4919
                id: null,
4920
                params: params,
4921
                defaults: defaults,
4922
                body: body,
4923
                rest: rest,
4924
                generator: false,
4925
                expression: expression
4926
            };
4927
4928
            if (isAsync) {
4929
                arrowExpr.async = true;
4930
            }
4931
4932
            return arrowExpr;
4933
        },
4934
4935
        createMethodDefinition: function (propertyType, kind, key, value, computed) {
4936
            return {
4937
                type: Syntax.MethodDefinition,
4938
                key: key,
4939
                value: value,
4940
                kind: kind,
4941
                'static': propertyType === ClassPropertyType["static"],
4942
                computed: computed
4943
            };
4944
        },
4945
4946
        createClassProperty: function (key, typeAnnotation, computed, isStatic) {
4947
            return {
4948
                type: Syntax.ClassProperty,
4949
                key: key,
4950
                typeAnnotation: typeAnnotation,
4951
                computed: computed,
4952
                "static": isStatic
4953
            };
4954
        },
4955
4956
        createClassBody: function (body) {
4957
            return {
4958
                type: Syntax.ClassBody,
4959
                body: body
4960
            };
4961
        },
4962
4963
        createClassImplements: function (id, typeParameters) {
4964
            return {
4965
                type: Syntax.ClassImplements,
4966
                id: id,
4967
                typeParameters: typeParameters
4968
            };
4969
        },
4970
4971
        createClassExpression: function (id, superClass, body, typeParameters, superTypeParameters, implemented) {
4972
            return {
4973
                type: Syntax.ClassExpression,
4974
                id: id,
4975
                superClass: superClass,
4976
                body: body,
4977
                typeParameters: typeParameters,
4978
                superTypeParameters: superTypeParameters,
4979
                "implements": implemented
4980
            };
4981
        },
4982
4983
        createClassDeclaration: function (id, superClass, body, typeParameters, superTypeParameters, implemented) {
4984
            return {
4985
                type: Syntax.ClassDeclaration,
4986
                id: id,
4987
                superClass: superClass,
4988
                body: body,
4989
                typeParameters: typeParameters,
4990
                superTypeParameters: superTypeParameters,
4991
                "implements": implemented
4992
            };
4993
        },
4994
4995
        createModuleSpecifier: function (token) {
4996
            return {
4997
                type: Syntax.ModuleSpecifier,
4998
                value: token.value,
4999
                raw: source.slice(token.range[0], token.range[1])
5000
            };
5001
        },
5002
5003
        createExportSpecifier: function (id, name) {
5004
            return {
5005
                type: Syntax.ExportSpecifier,
5006
                id: id,
5007
                name: name
5008
            };
5009
        },
5010
5011
        createExportBatchSpecifier: function () {
5012
            return {
5013
                type: Syntax.ExportBatchSpecifier
5014
            };
5015
        },
5016
5017
        createImportDefaultSpecifier: function (id) {
5018
            return {
5019
                type: Syntax.ImportDefaultSpecifier,
5020
                id: id
5021
            };
5022
        },
5023
5024
        createImportNamespaceSpecifier: function (id) {
5025
            return {
5026
                type: Syntax.ImportNamespaceSpecifier,
5027
                id: id
5028
            };
5029
        },
5030
5031
        createExportDeclaration: function (isDefault, declaration, specifiers, src) {
5032
            return {
5033
                type: Syntax.ExportDeclaration,
5034
                'default': !!isDefault,
5035
                declaration: declaration,
5036
                specifiers: specifiers,
5037
                source: src
5038
            };
5039
        },
5040
5041
        createImportSpecifier: function (id, name) {
5042
            return {
5043
                type: Syntax.ImportSpecifier,
5044
                id: id,
5045
                name: name
5046
            };
5047
        },
5048
5049
        createImportDeclaration: function (specifiers, src, isType) {
5050
            return {
5051
                type: Syntax.ImportDeclaration,
5052
                specifiers: specifiers,
5053
                source: src,
5054
                isType: isType
5055
            };
5056
        },
5057
5058
        createYieldExpression: function (argument, dlg) {
5059
            return {
5060
                type: Syntax.YieldExpression,
5061
                argument: argument,
5062
                delegate: dlg
5063
            };
5064
        },
5065
5066
        createAwaitExpression: function (argument) {
5067
            return {
5068
                type: Syntax.AwaitExpression,
5069
                argument: argument
5070
            };
5071
        },
5072
5073
        createComprehensionExpression: function (filter, blocks, body) {
5074
            return {
5075
                type: Syntax.ComprehensionExpression,
5076
                filter: filter,
5077
                blocks: blocks,
5078
                body: body
5079
            };
5080
        }
5081
5082
    };
5083
5084
    // Return true if there is a line terminator before the next token.
5085
5086
    function peekLineTerminator() {
5087
        var pos, line, start, found;
5088
5089
        pos = index;
5090
        line = lineNumber;
5091
        start = lineStart;
5092
        skipComment();
5093
        found = lineNumber !== line;
5094
        index = pos;
5095
        lineNumber = line;
5096
        lineStart = start;
5097
5098
        return found;
5099
    }
5100
5101
    // Throw an exception
5102
5103
    function throwError(token, messageFormat) {
5104
        var error,
5105
            args = Array.prototype.slice.call(arguments, 2),
5106
            msg = messageFormat.replace(
5107
                /%(\d)/g,
5108
                function (whole, idx) {
5109
                    assert(idx < args.length, 'Message reference must be in range');
5110
                    return args[idx];
5111
                }
5112
            );
5113
5114
        if (typeof token.lineNumber === 'number') {
5115
            error = new Error('Line ' + token.lineNumber + ': ' + msg);
5116
            error.index = token.range[0];
5117
            error.lineNumber = token.lineNumber;
5118
            error.column = token.range[0] - lineStart + 1;
5119
        } else {
5120
            error = new Error('Line ' + lineNumber + ': ' + msg);
5121
            error.index = index;
5122
            error.lineNumber = lineNumber;
5123
            error.column = index - lineStart + 1;
5124
        }
5125
5126
        error.description = msg;
5127
        throw error;
5128
    }
5129
5130
    function throwErrorTolerant() {
5131
        try {
5132
            throwError.apply(null, arguments);
5133
        } catch (e) {
5134
            if (extra.errors) {
5135
                extra.errors.push(e);
5136
            } else {
5137
                throw e;
5138
            }
5139
        }
5140
    }
5141
5142
5143
    // Throw an exception because of the token.
5144
5145
    function throwUnexpected(token) {
5146
        if (token.type === Token.EOF) {
5147
            throwError(token, Messages.UnexpectedEOS);
5148
        }
5149
5150
        if (token.type === Token.NumericLiteral) {
5151
            throwError(token, Messages.UnexpectedNumber);
5152
        }
5153
5154
        if (token.type === Token.StringLiteral || token.type === Token.JSXText) {
5155
            throwError(token, Messages.UnexpectedString);
5156
        }
5157
5158
        if (token.type === Token.Identifier) {
5159
            throwError(token, Messages.UnexpectedIdentifier);
5160
        }
5161
5162
        if (token.type === Token.Keyword) {
5163
            if (isFutureReservedWord(token.value)) {
5164
                throwError(token, Messages.UnexpectedReserved);
5165
            } else if (strict && isStrictModeReservedWord(token.value)) {
5166
                throwErrorTolerant(token, Messages.StrictReservedWord);
5167
                return;
5168
            }
5169
            throwError(token, Messages.UnexpectedToken, token.value);
5170
        }
5171
5172
        if (token.type === Token.Template) {
5173
            throwError(token, Messages.UnexpectedTemplate, token.value.raw);
5174
        }
5175
5176
        // BooleanLiteral, NullLiteral, or Punctuator.
5177
        throwError(token, Messages.UnexpectedToken, token.value);
5178
    }
5179
5180
    // Expect the next token to match the specified punctuator.
5181
    // If not, an exception will be thrown.
5182
5183
    function expect(value) {
5184
        var token = lex();
5185
        if (token.type !== Token.Punctuator || token.value !== value) {
5186
            throwUnexpected(token);
5187
        }
5188
    }
5189
5190
    // Expect the next token to match the specified keyword.
5191
    // If not, an exception will be thrown.
5192
5193
    function expectKeyword(keyword, contextual) {
5194
        var token = lex();
5195
        if (token.type !== (contextual ? Token.Identifier : Token.Keyword) ||
5196
                token.value !== keyword) {
5197
            throwUnexpected(token);
5198
        }
5199
    }
5200
5201
    // Expect the next token to match the specified contextual keyword.
5202
    // If not, an exception will be thrown.
5203
5204
    function expectContextualKeyword(keyword) {
5205
        return expectKeyword(keyword, true);
5206
    }
5207
5208
    // Return true if the next token matches the specified punctuator.
5209
5210
    function match(value) {
5211
        return lookahead.type === Token.Punctuator && lookahead.value === value;
5212
    }
5213
5214
    // Return true if the next token matches the specified keyword
5215
5216
    function matchKeyword(keyword, contextual) {
5217
        var expectedType = contextual ? Token.Identifier : Token.Keyword;
5218
        return lookahead.type === expectedType && lookahead.value === keyword;
5219
    }
5220
5221
    // Return true if the next token matches the specified contextual keyword
5222
5223
    function matchContextualKeyword(keyword) {
5224
        return matchKeyword(keyword, true);
5225
    }
5226
5227
    // Return true if the next token is an assignment operator
5228
5229
    function matchAssign() {
5230
        var op;
5231
5232
        if (lookahead.type !== Token.Punctuator) {
5233
            return false;
5234
        }
5235
        op = lookahead.value;
5236
        return op === '=' ||
5237
            op === '*=' ||
5238
            op === '/=' ||
5239
            op === '%=' ||
5240
            op === '+=' ||
5241
            op === '-=' ||
5242
            op === '<<=' ||
5243
            op === '>>=' ||
5244
            op === '>>>=' ||
5245
            op === '&=' ||
5246
            op === '^=' ||
5247
            op === '|=';
5248
    }
5249
5250
    // Note that 'yield' is treated as a keyword in strict mode, but a
5251
    // contextual keyword (identifier) in non-strict mode, so we need to
5252
    // use matchKeyword('yield', false) and matchKeyword('yield', true)
5253
    // (i.e. matchContextualKeyword) appropriately.
5254
    function matchYield() {
5255
        return state.yieldAllowed && matchKeyword('yield', !strict);
5256
    }
5257
5258
    function matchAsync() {
5259
        var backtrackToken = lookahead, matches = false;
5260
5261
        if (matchContextualKeyword('async')) {
5262
            lex(); // Make sure peekLineTerminator() starts after 'async'.
5263
            matches = !peekLineTerminator();
5264
            rewind(backtrackToken); // Revert the lex().
5265
        }
5266
5267
        return matches;
5268
    }
5269
5270
    function matchAwait() {
5271
        return state.awaitAllowed && matchContextualKeyword('await');
5272
    }
5273
5274
    function consumeSemicolon() {
5275
        var line, oldIndex = index, oldLineNumber = lineNumber,
5276
            oldLineStart = lineStart, oldLookahead = lookahead;
5277
5278
        // Catch the very common case first: immediately a semicolon (char #59).
5279
        if (source.charCodeAt(index) === 59) {
5280
            lex();
5281
            return;
5282
        }
5283
5284
        line = lineNumber;
5285
        skipComment();
5286
        if (lineNumber !== line) {
5287
            index = oldIndex;
5288
            lineNumber = oldLineNumber;
5289
            lineStart = oldLineStart;
5290
            lookahead = oldLookahead;
5291
            return;
5292
        }
5293
5294
        if (match(';')) {
5295
            lex();
5296
            return;
5297
        }
5298
5299
        if (lookahead.type !== Token.EOF && !match('}')) {
5300
            throwUnexpected(lookahead);
5301
        }
5302
    }
5303
5304
    // Return true if provided expression is LeftHandSideExpression
5305
5306
    function isLeftHandSide(expr) {
5307
        return expr.type === Syntax.Identifier || expr.type === Syntax.MemberExpression;
5308
    }
5309
5310
    function isAssignableLeftHandSide(expr) {
5311
        return isLeftHandSide(expr) || expr.type === Syntax.ObjectPattern || expr.type === Syntax.ArrayPattern;
5312
    }
5313
5314
    // 11.1.4 Array Initialiser
5315
5316
    function parseArrayInitialiser() {
5317
        var elements = [], blocks = [], filter = null, tmp, possiblecomprehension = true,
5318
            marker = markerCreate();
5319
5320
        expect('[');
5321
        while (!match(']')) {
5322
            if (lookahead.value === 'for' &&
5323
                    lookahead.type === Token.Keyword) {
5324
                if (!possiblecomprehension) {
5325
                    throwError({}, Messages.ComprehensionError);
5326
                }
5327
                matchKeyword('for');
5328
                tmp = parseForStatement({ignoreBody: true});
5329
                tmp.of = tmp.type === Syntax.ForOfStatement;
5330
                tmp.type = Syntax.ComprehensionBlock;
5331
                if (tmp.left.kind) { // can't be let or const
5332
                    throwError({}, Messages.ComprehensionError);
5333
                }
5334
                blocks.push(tmp);
5335
            } else if (lookahead.value === 'if' &&
5336
                           lookahead.type === Token.Keyword) {
5337
                if (!possiblecomprehension) {
5338
                    throwError({}, Messages.ComprehensionError);
5339
                }
5340
                expectKeyword('if');
5341
                expect('(');
5342
                filter = parseExpression();
5343
                expect(')');
5344
            } else if (lookahead.value === ',' &&
5345
                           lookahead.type === Token.Punctuator) {
5346
                possiblecomprehension = false; // no longer allowed.
5347
                lex();
5348
                elements.push(null);
5349
            } else {
5350
                tmp = parseSpreadOrAssignmentExpression();
5351
                elements.push(tmp);
5352
                if (tmp && tmp.type === Syntax.SpreadElement) {
5353
                    if (!match(']')) {
5354
                        throwError({}, Messages.ElementAfterSpreadElement);
5355
                    }
5356
                } else if (!(match(']') || matchKeyword('for') || matchKeyword('if'))) {
5357
                    expect(','); // this lexes.
5358
                    possiblecomprehension = false;
5359
                }
5360
            }
5361
        }
5362
5363
        expect(']');
5364
5365
        if (filter && !blocks.length) {
5366
            throwError({}, Messages.ComprehensionRequiresBlock);
5367
        }
5368
5369
        if (blocks.length) {
5370
            if (elements.length !== 1) {
5371
                throwError({}, Messages.ComprehensionError);
5372
            }
5373
            return markerApply(marker, delegate.createComprehensionExpression(filter, blocks, elements[0]));
5374
        }
5375
        return markerApply(marker, delegate.createArrayExpression(elements));
5376
    }
5377
5378
    // 11.1.5 Object Initialiser
5379
5380
    function parsePropertyFunction(options) {
5381
        var previousStrict, previousYieldAllowed, previousAwaitAllowed,
5382
            params, defaults, body, marker = markerCreate();
5383
5384
        previousStrict = strict;
5385
        previousYieldAllowed = state.yieldAllowed;
5386
        state.yieldAllowed = options.generator;
5387
        previousAwaitAllowed = state.awaitAllowed;
5388
        state.awaitAllowed = options.async;
5389
        params = options.params || [];
5390
        defaults = options.defaults || [];
5391
5392
        body = parseConciseBody();
5393
        if (options.name && strict && isRestrictedWord(params[0].name)) {
5394
            throwErrorTolerant(options.name, Messages.StrictParamName);
5395
        }
5396
        strict = previousStrict;
5397
        state.yieldAllowed = previousYieldAllowed;
5398
        state.awaitAllowed = previousAwaitAllowed;
5399
5400
        return markerApply(marker, delegate.createFunctionExpression(
5401
            null,
5402
            params,
5403
            defaults,
5404
            body,
5405
            options.rest || null,
5406
            options.generator,
5407
            body.type !== Syntax.BlockStatement,
5408
            options.async,
5409
            options.returnType,
5410
            options.typeParameters
5411
        ));
5412
    }
5413
5414
5415
    function parsePropertyMethodFunction(options) {
5416
        var previousStrict, tmp, method;
5417
5418
        previousStrict = strict;
5419
        strict = true;
5420
5421
        tmp = parseParams();
5422
5423
        if (tmp.stricted) {
5424
            throwErrorTolerant(tmp.stricted, tmp.message);
5425
        }
5426
5427
        method = parsePropertyFunction({
5428
            params: tmp.params,
5429
            defaults: tmp.defaults,
5430
            rest: tmp.rest,
5431
            generator: options.generator,
5432
            async: options.async,
5433
            returnType: tmp.returnType,
5434
            typeParameters: options.typeParameters
5435
        });
5436
5437
        strict = previousStrict;
5438
5439
        return method;
5440
    }
5441
5442
5443
    function parseObjectPropertyKey() {
5444
        var marker = markerCreate(),
5445
            token = lex(),
5446
            propertyKey,
5447
            result;
5448
5449
        // Note: This function is called only from parseObjectProperty(), where
5450
        // EOF and Punctuator tokens are already filtered out.
5451
5452
        if (token.type === Token.StringLiteral || token.type === Token.NumericLiteral) {
5453
            if (strict && token.octal) {
5454
                throwErrorTolerant(token, Messages.StrictOctalLiteral);
5455
            }
5456
            return markerApply(marker, delegate.createLiteral(token));
5457
        }
5458
5459
        if (token.type === Token.Punctuator && token.value === '[') {
5460
            // For computed properties we should skip the [ and ], and
5461
            // capture in marker only the assignment expression itself.
5462
            marker = markerCreate();
5463
            propertyKey = parseAssignmentExpression();
5464
            result = markerApply(marker, propertyKey);
5465
            expect(']');
5466
            return result;
5467
        }
5468
5469
        return markerApply(marker, delegate.createIdentifier(token.value));
5470
    }
5471
5472
    function parseObjectProperty() {
5473
        var token, key, id, param, computed,
5474
            marker = markerCreate(), returnType, typeParameters;
5475
5476
        token = lookahead;
5477
        computed = (token.value === '[' && token.type === Token.Punctuator);
5478
5479
        if (token.type === Token.Identifier || computed || matchAsync()) {
5480
            id = parseObjectPropertyKey();
5481
5482
            if (match(':')) {
5483
                lex();
5484
5485
                return markerApply(
5486
                    marker,
5487
                    delegate.createProperty(
5488
                        'init',
5489
                        id,
5490
                        parseAssignmentExpression(),
5491
                        false,
5492
                        false,
5493
                        computed
5494
                    )
5495
                );
5496
            }
5497
5498
            if (match('(') || match('<')) {
5499
                if (match('<')) {
5500
                    typeParameters = parseTypeParameterDeclaration();
5501
                }
5502
                return markerApply(
5503
                    marker,
5504
                    delegate.createProperty(
5505
                        'init',
5506
                        id,
5507
                        parsePropertyMethodFunction({
5508
                            generator: false,
5509
                            async: false,
5510
                            typeParameters: typeParameters
0 ignored issues
show
Bug introduced by
The variable typeParameters does not seem to be initialized in case match("<") on line 5499 is false. Are you sure this can never be the case?
Loading history...
5511
                        }),
5512
                        true,
5513
                        false,
5514
                        computed
5515
                    )
5516
                );
5517
            }
5518
5519
            // Property Assignment: Getter and Setter.
5520
5521
            if (token.value === 'get') {
5522
                computed = (lookahead.value === '[');
5523
                key = parseObjectPropertyKey();
5524
5525
                expect('(');
5526
                expect(')');
5527
                if (match(':')) {
5528
                    returnType = parseTypeAnnotation();
5529
                }
5530
5531
                return markerApply(
5532
                    marker,
5533
                    delegate.createProperty(
5534
                        'get',
5535
                        key,
5536
                        parsePropertyFunction({
5537
                            generator: false,
5538
                            async: false,
5539
                            returnType: returnType
0 ignored issues
show
Bug introduced by
The variable returnType does not seem to be initialized in case match(":") on line 5527 is false. Are you sure this can never be the case?
Loading history...
5540
                        }),
5541
                        false,
5542
                        false,
5543
                        computed
5544
                    )
5545
                );
5546
            }
5547
5548
            if (token.value === 'set') {
5549
                computed = (lookahead.value === '[');
5550
                key = parseObjectPropertyKey();
5551
5552
                expect('(');
5553
                token = lookahead;
5554
                param = [ parseTypeAnnotatableIdentifier() ];
5555
                expect(')');
5556
                if (match(':')) {
5557
                    returnType = parseTypeAnnotation();
5558
                }
5559
5560
                return markerApply(
5561
                    marker,
5562
                    delegate.createProperty(
5563
                        'set',
5564
                        key,
5565
                        parsePropertyFunction({
5566
                            params: param,
5567
                            generator: false,
5568
                            async: false,
5569
                            name: token,
5570
                            returnType: returnType
5571
                        }),
5572
                        false,
5573
                        false,
5574
                        computed
5575
                    )
5576
                );
5577
            }
5578
5579
            if (token.value === 'async') {
5580
                computed = (lookahead.value === '[');
5581
                key = parseObjectPropertyKey();
5582
5583
                if (match('<')) {
5584
                    typeParameters = parseTypeParameterDeclaration();
5585
                }
5586
5587
                return markerApply(
5588
                    marker,
5589
                    delegate.createProperty(
5590
                        'init',
5591
                        key,
5592
                        parsePropertyMethodFunction({
5593
                            generator: false,
5594
                            async: true,
5595
                            typeParameters: typeParameters
5596
                        }),
5597
                        true,
5598
                        false,
5599
                        computed
5600
                    )
5601
                );
5602
            }
5603
5604
            if (computed) {
5605
                // Computed properties can only be used with full notation.
5606
                throwUnexpected(lookahead);
5607
            }
5608
5609
            return markerApply(
5610
                marker,
5611
                delegate.createProperty('init', id, id, false, true, false)
5612
            );
5613
        }
5614
5615
        if (token.type === Token.EOF || token.type === Token.Punctuator) {
5616
            if (!match('*')) {
5617
                throwUnexpected(token);
5618
            }
5619
            lex();
5620
5621
            computed = (lookahead.type === Token.Punctuator && lookahead.value === '[');
5622
5623
            id = parseObjectPropertyKey();
5624
5625
            if (match('<')) {
5626
                typeParameters = parseTypeParameterDeclaration();
5627
            }
5628
5629
            if (!match('(')) {
5630
                throwUnexpected(lex());
5631
            }
5632
5633
            return markerApply(marker, delegate.createProperty(
5634
                'init',
5635
                id,
5636
                parsePropertyMethodFunction({
5637
                    generator: true,
5638
                    typeParameters: typeParameters
5639
                }),
5640
                true,
5641
                false,
5642
                computed
5643
            ));
5644
        }
5645
        key = parseObjectPropertyKey();
5646
        if (match(':')) {
5647
            lex();
5648
            return markerApply(marker, delegate.createProperty('init', key, parseAssignmentExpression(), false, false, false));
5649
        }
5650
        if (match('(') || match('<')) {
5651
            if (match('<')) {
5652
                typeParameters = parseTypeParameterDeclaration();
5653
            }
5654
            return markerApply(marker, delegate.createProperty(
5655
                'init',
5656
                key,
5657
                parsePropertyMethodFunction({
5658
                    generator: false,
5659
                    typeParameters: typeParameters
5660
                }),
5661
                true,
5662
                false,
5663
                false
5664
            ));
5665
        }
5666
        throwUnexpected(lex());
0 ignored issues
show
Best Practice introduced by
There is no return statement in this branch, but you do return something in other branches. Did you maybe miss it? If you do not want to return anything, consider adding return undefined; explicitly.
Loading history...
5667
    }
5668
5669
    function parseObjectSpreadProperty() {
5670
        var marker = markerCreate();
5671
        expect('...');
5672
        return markerApply(marker, delegate.createSpreadProperty(parseAssignmentExpression()));
5673
    }
5674
5675
    function getFieldName(key) {
5676
        var toString = String;
0 ignored issues
show
Comprehensibility Best Practice introduced by
You seem to be aliasing the built-in name String as toString. This makes your code very difficult to follow, consider using the built-in name directly.
Loading history...
5677
        if (key.type === Syntax.Identifier) {
5678
            return key.name;
5679
        }
5680
        return toString(key.value);
5681
    }
5682
5683
    function parseObjectInitialiser() {
5684
        var properties = [], property, name, kind, storedKind, map = new StringMap(),
5685
            marker = markerCreate(), toString = String;
0 ignored issues
show
Comprehensibility Best Practice introduced by
You seem to be aliasing the built-in name String as toString. This makes your code very difficult to follow, consider using the built-in name directly.
Loading history...
5686
5687
        expect('{');
5688
5689
        while (!match('}')) {
5690
            if (match('...')) {
5691
                property = parseObjectSpreadProperty();
5692
            } else {
5693
                property = parseObjectProperty();
5694
5695
                if (property.key.type === Syntax.Identifier) {
5696
                    name = property.key.name;
5697
                } else {
5698
                    name = toString(property.key.value);
5699
                }
5700
                kind = (property.kind === 'init') ? PropertyKind.Data : (property.kind === 'get') ? PropertyKind.Get : PropertyKind.Set;
5701
5702
                if (map.has(name)) {
5703
                    storedKind = map.get(name);
5704
                    if (storedKind === PropertyKind.Data) {
5705
                        if (strict && kind === PropertyKind.Data) {
5706
                            throwErrorTolerant({}, Messages.StrictDuplicateProperty);
5707
                        } else if (kind !== PropertyKind.Data) {
5708
                            throwErrorTolerant({}, Messages.AccessorDataProperty);
5709
                        }
5710
                    } else {
5711
                        if (kind === PropertyKind.Data) {
5712
                            throwErrorTolerant({}, Messages.AccessorDataProperty);
5713
                        } else if (storedKind & kind) {
0 ignored issues
show
introduced by
You have used a bitwise operator & in a condition. Did you maybe want to use the logical operator &&
Loading history...
5714
                            throwErrorTolerant({}, Messages.AccessorGetSet);
5715
                        }
5716
                    }
5717
                    map.set(name, storedKind | kind);
5718
                } else {
5719
                    map.set(name, kind);
5720
                }
5721
            }
5722
5723
            properties.push(property);
5724
5725
            if (!match('}')) {
5726
                expect(',');
5727
            }
5728
        }
5729
5730
        expect('}');
5731
5732
        return markerApply(marker, delegate.createObjectExpression(properties));
5733
    }
5734
5735
    function parseTemplateElement(option) {
5736
        var marker = markerCreate(),
5737
            token = scanTemplateElement(option);
5738
        if (strict && token.octal) {
5739
            throwError(token, Messages.StrictOctalLiteral);
5740
        }
5741
        return markerApply(marker, delegate.createTemplateElement({ raw: token.value.raw, cooked: token.value.cooked }, token.tail));
5742
    }
5743
5744
    function parseTemplateLiteral() {
5745
        var quasi, quasis, expressions, marker = markerCreate();
5746
5747
        quasi = parseTemplateElement({ head: true });
5748
        quasis = [ quasi ];
5749
        expressions = [];
5750
5751
        while (!quasi.tail) {
5752
            expressions.push(parseExpression());
5753
            quasi = parseTemplateElement({ head: false });
5754
            quasis.push(quasi);
5755
        }
5756
5757
        return markerApply(marker, delegate.createTemplateLiteral(quasis, expressions));
5758
    }
5759
5760
    // 11.1.6 The Grouping Operator
5761
5762
    function parseGroupExpression() {
5763
        var expr, marker, typeAnnotation;
5764
5765
        expect('(');
5766
5767
        ++state.parenthesizedCount;
5768
5769
        marker = markerCreate();
5770
5771
        expr = parseExpression();
5772
5773
        if (match(':')) {
5774
            typeAnnotation = parseTypeAnnotation();
5775
            expr = markerApply(marker, delegate.createTypeCast(
5776
                expr,
5777
                typeAnnotation
5778
            ));
5779
        }
5780
5781
        expect(')');
5782
5783
        return expr;
5784
    }
5785
5786
    function matchAsyncFuncExprOrDecl() {
5787
        var token;
5788
5789
        if (matchAsync()) {
5790
            token = lookahead2();
5791
            if (token.type === Token.Keyword && token.value === 'function') {
5792
                return true;
5793
            }
5794
        }
5795
5796
        return false;
5797
    }
5798
5799
    // 11.1 Primary Expressions
5800
5801
    function parsePrimaryExpression() {
5802
        var marker, type, token, expr;
5803
5804
        type = lookahead.type;
5805
5806
        if (type === Token.Identifier) {
5807
            marker = markerCreate();
5808
            return markerApply(marker, delegate.createIdentifier(lex().value));
5809
        }
5810
5811
        if (type === Token.StringLiteral || type === Token.NumericLiteral) {
5812
            if (strict && lookahead.octal) {
5813
                throwErrorTolerant(lookahead, Messages.StrictOctalLiteral);
5814
            }
5815
            marker = markerCreate();
5816
            return markerApply(marker, delegate.createLiteral(lex()));
5817
        }
5818
5819
        if (type === Token.Keyword) {
5820
            if (matchKeyword('this')) {
5821
                marker = markerCreate();
5822
                lex();
5823
                return markerApply(marker, delegate.createThisExpression());
5824
            }
5825
5826
            if (matchKeyword('function')) {
5827
                return parseFunctionExpression();
5828
            }
5829
5830
            if (matchKeyword('class')) {
5831
                return parseClassExpression();
5832
            }
5833
5834
            if (matchKeyword('super')) {
5835
                marker = markerCreate();
5836
                lex();
5837
                return markerApply(marker, delegate.createIdentifier('super'));
5838
            }
5839
        }
5840
5841
        if (type === Token.BooleanLiteral) {
5842
            marker = markerCreate();
5843
            token = lex();
5844
            token.value = (token.value === 'true');
5845
            return markerApply(marker, delegate.createLiteral(token));
5846
        }
5847
5848
        if (type === Token.NullLiteral) {
5849
            marker = markerCreate();
5850
            token = lex();
5851
            token.value = null;
5852
            return markerApply(marker, delegate.createLiteral(token));
5853
        }
5854
5855
        if (match('[')) {
5856
            return parseArrayInitialiser();
5857
        }
5858
5859
        if (match('{')) {
5860
            return parseObjectInitialiser();
5861
        }
5862
5863
        if (match('(')) {
5864
            return parseGroupExpression();
5865
        }
5866
5867
        if (match('/') || match('/=')) {
5868
            marker = markerCreate();
5869
            expr = delegate.createLiteral(scanRegExp());
5870
            peek();
5871
            return markerApply(marker, expr);
5872
        }
5873
5874
        if (type === Token.Template) {
5875
            return parseTemplateLiteral();
5876
        }
5877
5878
        if (match('<')) {
5879
            return parseJSXElement();
5880
        }
5881
5882
        throwUnexpected(lex());
0 ignored issues
show
Best Practice introduced by
There is no return statement in this branch, but you do return something in other branches. Did you maybe miss it? If you do not want to return anything, consider adding return undefined; explicitly.
Loading history...
5883
    }
5884
5885
    // 11.2 Left-Hand-Side Expressions
5886
5887
    function parseArguments() {
5888
        var args = [], arg;
5889
5890
        expect('(');
5891
5892
        if (!match(')')) {
5893
            while (index < length) {
5894
                arg = parseSpreadOrAssignmentExpression();
5895
                args.push(arg);
5896
5897
                if (match(')')) {
5898
                    break;
5899
                } else if (arg.type === Syntax.SpreadElement) {
5900
                    throwError({}, Messages.ElementAfterSpreadElement);
5901
                }
5902
5903
                expect(',');
5904
            }
5905
        }
5906
5907
        expect(')');
5908
5909
        return args;
5910
    }
5911
5912
    function parseSpreadOrAssignmentExpression() {
5913
        if (match('...')) {
5914
            var marker = markerCreate();
5915
            lex();
5916
            return markerApply(marker, delegate.createSpreadElement(parseAssignmentExpression()));
5917
        }
5918
        return parseAssignmentExpression();
5919
    }
5920
5921
    function parseNonComputedProperty() {
5922
        var marker = markerCreate(),
5923
            token = lex();
5924
5925
        if (!isIdentifierName(token)) {
5926
            throwUnexpected(token);
5927
        }
5928
5929
        return markerApply(marker, delegate.createIdentifier(token.value));
5930
    }
5931
5932
    function parseNonComputedMember() {
5933
        expect('.');
5934
5935
        return parseNonComputedProperty();
5936
    }
5937
5938
    function parseComputedMember() {
5939
        var expr;
5940
5941
        expect('[');
5942
5943
        expr = parseExpression();
5944
5945
        expect(']');
5946
5947
        return expr;
5948
    }
5949
5950
    function parseNewExpression() {
5951
        var callee, args, marker = markerCreate();
5952
5953
        expectKeyword('new');
5954
        callee = parseLeftHandSideExpression();
5955
        args = match('(') ? parseArguments() : [];
5956
5957
        return markerApply(marker, delegate.createNewExpression(callee, args));
5958
    }
5959
5960
    function parseLeftHandSideExpressionAllowCall() {
5961
        var expr, args, marker = markerCreate();
5962
5963
        expr = matchKeyword('new') ? parseNewExpression() : parsePrimaryExpression();
5964
5965
        while (match('.') || match('[') || match('(') || lookahead.type === Token.Template) {
5966
            if (match('(')) {
5967
                args = parseArguments();
5968
                expr = markerApply(marker, delegate.createCallExpression(expr, args));
5969
            } else if (match('[')) {
5970
                expr = markerApply(marker, delegate.createMemberExpression('[', expr, parseComputedMember()));
5971
            } else if (match('.')) {
5972
                expr = markerApply(marker, delegate.createMemberExpression('.', expr, parseNonComputedMember()));
5973
            } else {
5974
                expr = markerApply(marker, delegate.createTaggedTemplateExpression(expr, parseTemplateLiteral()));
5975
            }
5976
        }
5977
5978
        return expr;
5979
    }
5980
5981
    function parseLeftHandSideExpression() {
5982
        var expr, marker = markerCreate();
5983
5984
        expr = matchKeyword('new') ? parseNewExpression() : parsePrimaryExpression();
5985
5986
        while (match('.') || match('[') || lookahead.type === Token.Template) {
5987
            if (match('[')) {
5988
                expr = markerApply(marker, delegate.createMemberExpression('[', expr, parseComputedMember()));
5989
            } else if (match('.')) {
5990
                expr = markerApply(marker, delegate.createMemberExpression('.', expr, parseNonComputedMember()));
5991
            } else {
5992
                expr = markerApply(marker, delegate.createTaggedTemplateExpression(expr, parseTemplateLiteral()));
5993
            }
5994
        }
5995
5996
        return expr;
5997
    }
5998
5999
    // 11.3 Postfix Expressions
6000
6001
    function parsePostfixExpression() {
6002
        var marker = markerCreate(),
6003
            expr = parseLeftHandSideExpressionAllowCall(),
6004
            token;
6005
6006
        if (lookahead.type !== Token.Punctuator) {
6007
            return expr;
6008
        }
6009
6010
        if ((match('++') || match('--')) && !peekLineTerminator()) {
6011
            // 11.3.1, 11.3.2
6012
            if (strict && expr.type === Syntax.Identifier && isRestrictedWord(expr.name)) {
6013
                throwErrorTolerant({}, Messages.StrictLHSPostfix);
6014
            }
6015
6016
            if (!isLeftHandSide(expr)) {
6017
                throwError({}, Messages.InvalidLHSInAssignment);
6018
            }
6019
6020
            token = lex();
6021
            expr = markerApply(marker, delegate.createPostfixExpression(token.value, expr));
6022
        }
6023
6024
        return expr;
6025
    }
6026
6027
    // 11.4 Unary Operators
6028
6029
    function parseUnaryExpression() {
6030
        var marker, token, expr;
6031
6032
        if (lookahead.type !== Token.Punctuator && lookahead.type !== Token.Keyword) {
6033
            return parsePostfixExpression();
6034
        }
6035
6036
        if (match('++') || match('--')) {
6037
            marker = markerCreate();
6038
            token = lex();
6039
            expr = parseUnaryExpression();
6040
            // 11.4.4, 11.4.5
6041
            if (strict && expr.type === Syntax.Identifier && isRestrictedWord(expr.name)) {
6042
                throwErrorTolerant({}, Messages.StrictLHSPrefix);
6043
            }
6044
6045
            if (!isLeftHandSide(expr)) {
6046
                throwError({}, Messages.InvalidLHSInAssignment);
6047
            }
6048
6049
            return markerApply(marker, delegate.createUnaryExpression(token.value, expr));
6050
        }
6051
6052
        if (match('+') || match('-') || match('~') || match('!')) {
6053
            marker = markerCreate();
6054
            token = lex();
6055
            expr = parseUnaryExpression();
6056
            return markerApply(marker, delegate.createUnaryExpression(token.value, expr));
6057
        }
6058
6059
        if (matchKeyword('delete') || matchKeyword('void') || matchKeyword('typeof')) {
6060
            marker = markerCreate();
6061
            token = lex();
6062
            expr = parseUnaryExpression();
6063
            expr = markerApply(marker, delegate.createUnaryExpression(token.value, expr));
6064
            if (strict && expr.operator === 'delete' && expr.argument.type === Syntax.Identifier) {
6065
                throwErrorTolerant({}, Messages.StrictDelete);
6066
            }
6067
            return expr;
6068
        }
6069
6070
        return parsePostfixExpression();
6071
    }
6072
6073
    function binaryPrecedence(token, allowIn) {
6074
        var prec = 0;
6075
6076
        if (token.type !== Token.Punctuator && token.type !== Token.Keyword) {
6077
            return 0;
6078
        }
6079
6080
        switch (token.value) {
6081
        case '||':
6082
            prec = 1;
6083
            break;
6084
6085
        case '&&':
6086
            prec = 2;
6087
            break;
6088
6089
        case '|':
6090
            prec = 3;
6091
            break;
6092
6093
        case '^':
6094
            prec = 4;
6095
            break;
6096
6097
        case '&':
6098
            prec = 5;
6099
            break;
6100
6101
        case '==':
6102
        case '!=':
6103
        case '===':
6104
        case '!==':
6105
            prec = 6;
6106
            break;
6107
6108
        case '<':
6109
        case '>':
6110
        case '<=':
6111
        case '>=':
6112
        case 'instanceof':
6113
            prec = 7;
6114
            break;
6115
6116
        case 'in':
6117
            prec = allowIn ? 7 : 0;
6118
            break;
6119
6120
        case '<<':
6121
        case '>>':
6122
        case '>>>':
6123
            prec = 8;
6124
            break;
6125
6126
        case '+':
6127
        case '-':
6128
            prec = 9;
6129
            break;
6130
6131
        case '*':
6132
        case '/':
6133
        case '%':
6134
            prec = 11;
6135
            break;
6136
6137
        default:
6138
            break;
6139
        }
6140
6141
        return prec;
6142
    }
6143
6144
    // 11.5 Multiplicative Operators
6145
    // 11.6 Additive Operators
6146
    // 11.7 Bitwise Shift Operators
6147
    // 11.8 Relational Operators
6148
    // 11.9 Equality Operators
6149
    // 11.10 Binary Bitwise Operators
6150
    // 11.11 Binary Logical Operators
6151
6152
    function parseBinaryExpression() {
6153
        var expr, token, prec, previousAllowIn, stack, right, operator, left, i,
6154
            marker, markers;
6155
6156
        previousAllowIn = state.allowIn;
6157
        state.allowIn = true;
6158
6159
        marker = markerCreate();
6160
        left = parseUnaryExpression();
6161
6162
        token = lookahead;
6163
        prec = binaryPrecedence(token, previousAllowIn);
6164
        if (prec === 0) {
6165
            return left;
6166
        }
6167
        token.prec = prec;
6168
        lex();
6169
6170
        markers = [marker, markerCreate()];
6171
        right = parseUnaryExpression();
6172
6173
        stack = [left, token, right];
6174
6175
        while ((prec = binaryPrecedence(lookahead, previousAllowIn)) > 0) {
6176
6177
            // Reduce: make a binary expression from the three topmost entries.
6178
            while ((stack.length > 2) && (prec <= stack[stack.length - 2].prec)) {
6179
                right = stack.pop();
6180
                operator = stack.pop().value;
6181
                left = stack.pop();
6182
                expr = delegate.createBinaryExpression(operator, left, right);
6183
                markers.pop();
6184
                marker = markers.pop();
6185
                markerApply(marker, expr);
6186
                stack.push(expr);
6187
                markers.push(marker);
6188
            }
6189
6190
            // Shift.
6191
            token = lex();
6192
            token.prec = prec;
6193
            stack.push(token);
6194
            markers.push(markerCreate());
6195
            expr = parseUnaryExpression();
6196
            stack.push(expr);
6197
        }
6198
6199
        state.allowIn = previousAllowIn;
6200
6201
        // Final reduce to clean-up the stack.
6202
        i = stack.length - 1;
6203
        expr = stack[i];
6204
        markers.pop();
6205
        while (i > 1) {
6206
            expr = delegate.createBinaryExpression(stack[i - 1].value, stack[i - 2], expr);
6207
            i -= 2;
6208
            marker = markers.pop();
6209
            markerApply(marker, expr);
6210
        }
6211
6212
        return expr;
6213
    }
6214
6215
6216
    // 11.12 Conditional Operator
6217
6218
    function parseConditionalExpression() {
6219
        var expr, previousAllowIn, consequent, alternate, marker = markerCreate();
6220
        expr = parseBinaryExpression();
6221
6222
        if (match('?')) {
6223
            lex();
6224
            previousAllowIn = state.allowIn;
6225
            state.allowIn = true;
6226
            consequent = parseAssignmentExpression();
6227
            state.allowIn = previousAllowIn;
6228
            expect(':');
6229
            alternate = parseAssignmentExpression();
6230
6231
            expr = markerApply(marker, delegate.createConditionalExpression(expr, consequent, alternate));
6232
        }
6233
6234
        return expr;
6235
    }
6236
6237
    // 11.13 Assignment Operators
6238
6239
    // 12.14.5 AssignmentPattern
6240
6241
    function reinterpretAsAssignmentBindingPattern(expr) {
6242
        var i, len, property, element;
6243
6244
        if (expr.type === Syntax.ObjectExpression) {
6245
            expr.type = Syntax.ObjectPattern;
6246
            for (i = 0, len = expr.properties.length; i < len; i += 1) {
6247
                property = expr.properties[i];
6248
                if (property.type === Syntax.SpreadProperty) {
6249
                    if (i < len - 1) {
6250
                        throwError({}, Messages.PropertyAfterSpreadProperty);
6251
                    }
6252
                    reinterpretAsAssignmentBindingPattern(property.argument);
6253
                } else {
6254
                    if (property.kind !== 'init') {
6255
                        throwError({}, Messages.InvalidLHSInAssignment);
6256
                    }
6257
                    reinterpretAsAssignmentBindingPattern(property.value);
6258
                }
6259
            }
6260
        } else if (expr.type === Syntax.ArrayExpression) {
6261
            expr.type = Syntax.ArrayPattern;
6262
            for (i = 0, len = expr.elements.length; i < len; i += 1) {
6263
                element = expr.elements[i];
6264
                /* istanbul ignore else */
6265
                if (element) {
6266
                    reinterpretAsAssignmentBindingPattern(element);
6267
                }
6268
            }
6269
        } else if (expr.type === Syntax.Identifier) {
6270
            if (isRestrictedWord(expr.name)) {
6271
                throwError({}, Messages.InvalidLHSInAssignment);
6272
            }
6273
        } else if (expr.type === Syntax.SpreadElement) {
6274
            reinterpretAsAssignmentBindingPattern(expr.argument);
6275
            if (expr.argument.type === Syntax.ObjectPattern) {
6276
                throwError({}, Messages.ObjectPatternAsSpread);
6277
            }
6278
        } else {
6279
            /* istanbul ignore else */
6280
            if (expr.type !== Syntax.MemberExpression && expr.type !== Syntax.CallExpression && expr.type !== Syntax.NewExpression) {
6281
                throwError({}, Messages.InvalidLHSInAssignment);
6282
            }
6283
        }
6284
    }
6285
6286
    // 13.2.3 BindingPattern
6287
6288
    function reinterpretAsDestructuredParameter(options, expr) {
6289
        var i, len, property, element;
6290
6291
        if (expr.type === Syntax.ObjectExpression) {
6292
            expr.type = Syntax.ObjectPattern;
6293
            for (i = 0, len = expr.properties.length; i < len; i += 1) {
6294
                property = expr.properties[i];
6295
                if (property.type === Syntax.SpreadProperty) {
6296
                    if (i < len - 1) {
6297
                        throwError({}, Messages.PropertyAfterSpreadProperty);
6298
                    }
6299
                    reinterpretAsDestructuredParameter(options, property.argument);
6300
                } else {
6301
                    if (property.kind !== 'init') {
6302
                        throwError({}, Messages.InvalidLHSInFormalsList);
6303
                    }
6304
                    reinterpretAsDestructuredParameter(options, property.value);
6305
                }
6306
            }
6307
        } else if (expr.type === Syntax.ArrayExpression) {
6308
            expr.type = Syntax.ArrayPattern;
6309
            for (i = 0, len = expr.elements.length; i < len; i += 1) {
6310
                element = expr.elements[i];
6311
                if (element) {
6312
                    reinterpretAsDestructuredParameter(options, element);
6313
                }
6314
            }
6315
        } else if (expr.type === Syntax.Identifier) {
6316
            validateParam(options, expr, expr.name);
6317
        } else if (expr.type === Syntax.SpreadElement) {
6318
            // BindingRestElement only allows BindingIdentifier
6319
            if (expr.argument.type !== Syntax.Identifier) {
6320
                throwError({}, Messages.InvalidLHSInFormalsList);
6321
            }
6322
            validateParam(options, expr.argument, expr.argument.name);
6323
        } else {
6324
            throwError({}, Messages.InvalidLHSInFormalsList);
6325
        }
6326
    }
6327
6328
    function reinterpretAsCoverFormalsList(expressions) {
6329
        var i, len, param, params, defaults, defaultCount, options, rest;
6330
6331
        params = [];
6332
        defaults = [];
6333
        defaultCount = 0;
6334
        rest = null;
6335
        options = {
6336
            paramSet: new StringMap()
6337
        };
6338
6339
        for (i = 0, len = expressions.length; i < len; i += 1) {
6340
            param = expressions[i];
6341
            if (param.type === Syntax.Identifier) {
6342
                params.push(param);
6343
                defaults.push(null);
6344
                validateParam(options, param, param.name);
6345
            } else if (param.type === Syntax.ObjectExpression || param.type === Syntax.ArrayExpression) {
6346
                reinterpretAsDestructuredParameter(options, param);
6347
                params.push(param);
6348
                defaults.push(null);
6349
            } else if (param.type === Syntax.SpreadElement) {
6350
                assert(i === len - 1, 'It is guaranteed that SpreadElement is last element by parseExpression');
6351
                if (param.argument.type !== Syntax.Identifier) {
6352
                    throwError({}, Messages.InvalidLHSInFormalsList);
6353
                }
6354
                reinterpretAsDestructuredParameter(options, param.argument);
6355
                rest = param.argument;
6356
            } else if (param.type === Syntax.AssignmentExpression) {
6357
                params.push(param.left);
6358
                defaults.push(param.right);
6359
                ++defaultCount;
6360
                validateParam(options, param.left, param.left.name);
6361
            } else {
6362
                return null;
6363
            }
6364
        }
6365
6366
        if (options.message === Messages.StrictParamDupe) {
6367
            throwError(
6368
                strict ? options.stricted : options.firstRestricted,
6369
                options.message
6370
            );
6371
        }
6372
6373
        if (defaultCount === 0) {
6374
            defaults = [];
6375
        }
6376
6377
        return {
6378
            params: params,
6379
            defaults: defaults,
6380
            rest: rest,
6381
            stricted: options.stricted,
6382
            firstRestricted: options.firstRestricted,
6383
            message: options.message
6384
        };
6385
    }
6386
6387
    function parseArrowFunctionExpression(options, marker) {
6388
        var previousStrict, previousYieldAllowed, previousAwaitAllowed, body;
6389
6390
        expect('=>');
6391
6392
        previousStrict = strict;
6393
        previousYieldAllowed = state.yieldAllowed;
6394
        state.yieldAllowed = false;
6395
        previousAwaitAllowed = state.awaitAllowed;
6396
        state.awaitAllowed = !!options.async;
6397
        body = parseConciseBody();
6398
6399
        if (strict && options.firstRestricted) {
6400
            throwError(options.firstRestricted, options.message);
6401
        }
6402
        if (strict && options.stricted) {
6403
            throwErrorTolerant(options.stricted, options.message);
6404
        }
6405
6406
        strict = previousStrict;
6407
        state.yieldAllowed = previousYieldAllowed;
6408
        state.awaitAllowed = previousAwaitAllowed;
6409
6410
        return markerApply(marker, delegate.createArrowFunctionExpression(
6411
            options.params,
6412
            options.defaults,
6413
            body,
6414
            options.rest,
6415
            body.type !== Syntax.BlockStatement,
6416
            !!options.async
6417
        ));
6418
    }
6419
6420
    function parseAssignmentExpression() {
6421
        var marker, expr, token, params, oldParenthesizedCount,
6422
            startsWithParen = false, backtrackToken = lookahead,
6423
            possiblyAsync = false;
6424
6425
        if (matchYield()) {
6426
            return parseYieldExpression();
6427
        }
6428
6429
        if (matchAwait()) {
6430
            return parseAwaitExpression();
6431
        }
6432
6433
        oldParenthesizedCount = state.parenthesizedCount;
6434
6435
        marker = markerCreate();
6436
6437
        if (matchAsyncFuncExprOrDecl()) {
6438
            return parseFunctionExpression();
6439
        }
6440
6441
        if (matchAsync()) {
6442
            // We can't be completely sure that this 'async' token is
6443
            // actually a contextual keyword modifying a function
6444
            // expression, so we might have to un-lex() it later by
6445
            // calling rewind(backtrackToken).
6446
            possiblyAsync = true;
6447
            lex();
6448
        }
6449
6450
        if (match('(')) {
6451
            token = lookahead2();
6452
            if ((token.type === Token.Punctuator && token.value === ')') || token.value === '...') {
6453
                params = parseParams();
6454
                if (!match('=>')) {
6455
                    throwUnexpected(lex());
6456
                }
6457
                params.async = possiblyAsync;
6458
                return parseArrowFunctionExpression(params, marker);
6459
            }
6460
            startsWithParen = true;
6461
        }
6462
6463
        token = lookahead;
6464
6465
        // If the 'async' keyword is not followed by a '(' character or an
6466
        // identifier, then it can't be an arrow function modifier, and we
6467
        // should interpret it as a normal identifer.
6468
        if (possiblyAsync && !match('(') && token.type !== Token.Identifier) {
6469
            possiblyAsync = false;
6470
            rewind(backtrackToken);
6471
        }
6472
6473
        expr = parseConditionalExpression();
6474
6475
        if (match('=>') &&
6476
                (state.parenthesizedCount === oldParenthesizedCount ||
6477
                state.parenthesizedCount === (oldParenthesizedCount + 1))) {
6478
            if (expr.type === Syntax.Identifier) {
6479
                params = reinterpretAsCoverFormalsList([ expr ]);
6480
            } else if (expr.type === Syntax.AssignmentExpression ||
6481
                    expr.type === Syntax.ArrayExpression ||
6482
                    expr.type === Syntax.ObjectExpression) {
6483
                if (!startsWithParen) {
6484
                    throwUnexpected(lex());
6485
                }
6486
                params = reinterpretAsCoverFormalsList([ expr ]);
6487
            } else if (expr.type === Syntax.SequenceExpression) {
6488
                params = reinterpretAsCoverFormalsList(expr.expressions);
6489
            }
6490
            if (params) {
6491
                params.async = possiblyAsync;
6492
                return parseArrowFunctionExpression(params, marker);
6493
            }
6494
        }
6495
6496
        // If we haven't returned by now, then the 'async' keyword was not
6497
        // a function modifier, and we should rewind and interpret it as a
6498
        // normal identifier.
6499
        if (possiblyAsync) {
6500
            possiblyAsync = false;
0 ignored issues
show
Unused Code introduced by
The assignment to variable possiblyAsync seems to be never used. Consider removing it.
Loading history...
6501
            rewind(backtrackToken);
6502
            expr = parseConditionalExpression();
6503
        }
6504
6505
        if (matchAssign()) {
6506
            // 11.13.1
6507
            if (strict && expr.type === Syntax.Identifier && isRestrictedWord(expr.name)) {
6508
                throwErrorTolerant(token, Messages.StrictLHSAssignment);
6509
            }
6510
6511
            // ES.next draf 11.13 Runtime Semantics step 1
6512
            if (match('=') && (expr.type === Syntax.ObjectExpression || expr.type === Syntax.ArrayExpression)) {
6513
                reinterpretAsAssignmentBindingPattern(expr);
6514
            } else if (!isLeftHandSide(expr)) {
6515
                throwError({}, Messages.InvalidLHSInAssignment);
6516
            }
6517
6518
            expr = markerApply(marker, delegate.createAssignmentExpression(lex().value, expr, parseAssignmentExpression()));
6519
        }
6520
6521
        return expr;
6522
    }
6523
6524
    // 11.14 Comma Operator
6525
6526
    function parseExpression() {
6527
        var marker, expr, expressions, sequence, spreadFound;
6528
6529
        marker = markerCreate();
6530
        expr = parseAssignmentExpression();
6531
        expressions = [ expr ];
6532
6533
        if (match(',')) {
6534
            while (index < length) {
6535
                if (!match(',')) {
6536
                    break;
6537
                }
6538
6539
                lex();
6540
                expr = parseSpreadOrAssignmentExpression();
6541
                expressions.push(expr);
6542
6543
                if (expr.type === Syntax.SpreadElement) {
6544
                    spreadFound = true;
6545
                    if (!match(')')) {
6546
                        throwError({}, Messages.ElementAfterSpreadElement);
6547
                    }
6548
                    break;
6549
                }
6550
            }
6551
6552
            sequence = markerApply(marker, delegate.createSequenceExpression(expressions));
6553
        }
6554
6555
        if (spreadFound && lookahead2().value !== '=>') {
6556
            throwError({}, Messages.IllegalSpread);
6557
        }
6558
6559
        return sequence || expr;
6560
    }
6561
6562
    // 12.1 Block
6563
6564
    function parseStatementList() {
6565
        var list = [],
6566
            statement;
6567
6568
        while (index < length) {
6569
            if (match('}')) {
6570
                break;
6571
            }
6572
            statement = parseSourceElement();
6573
            if (typeof statement === 'undefined') {
6574
                break;
6575
            }
6576
            list.push(statement);
6577
        }
6578
6579
        return list;
6580
    }
6581
6582
    function parseBlock() {
6583
        var block, marker = markerCreate();
6584
6585
        expect('{');
6586
6587
        block = parseStatementList();
6588
6589
        expect('}');
6590
6591
        return markerApply(marker, delegate.createBlockStatement(block));
6592
    }
6593
6594
    // 12.2 Variable Statement
6595
6596
    function parseTypeParameterDeclaration() {
6597
        var marker = markerCreate(), paramTypes = [];
6598
6599
        expect('<');
6600
        while (!match('>')) {
6601
            paramTypes.push(parseTypeAnnotatableIdentifier());
6602
            if (!match('>')) {
6603
                expect(',');
6604
            }
6605
        }
6606
        expect('>');
6607
6608
        return markerApply(marker, delegate.createTypeParameterDeclaration(
6609
            paramTypes
6610
        ));
6611
    }
6612
6613
    function parseTypeParameterInstantiation() {
6614
        var marker = markerCreate(), oldInType = state.inType, paramTypes = [];
6615
6616
        state.inType = true;
6617
6618
        expect('<');
6619
        while (!match('>')) {
6620
            paramTypes.push(parseType());
6621
            if (!match('>')) {
6622
                expect(',');
6623
            }
6624
        }
6625
        expect('>');
6626
6627
        state.inType = oldInType;
6628
6629
        return markerApply(marker, delegate.createTypeParameterInstantiation(
6630
            paramTypes
6631
        ));
6632
    }
6633
6634
    function parseObjectTypeIndexer(marker, isStatic) {
6635
        var id, key, value;
6636
6637
        expect('[');
6638
        id = parseObjectPropertyKey();
6639
        expect(':');
6640
        key = parseType();
6641
        expect(']');
6642
        expect(':');
6643
        value = parseType();
6644
6645
        return markerApply(marker, delegate.createObjectTypeIndexer(
6646
            id,
6647
            key,
6648
            value,
6649
            isStatic
6650
        ));
6651
    }
6652
6653
    function parseObjectTypeMethodish(marker) {
6654
        var params = [], rest = null, returnType, typeParameters = null;
6655
        if (match('<')) {
6656
            typeParameters = parseTypeParameterDeclaration();
6657
        }
6658
6659
        expect('(');
6660
        while (lookahead.type === Token.Identifier) {
6661
            params.push(parseFunctionTypeParam());
6662
            if (!match(')')) {
6663
                expect(',');
6664
            }
6665
        }
6666
6667
        if (match('...')) {
6668
            lex();
6669
            rest = parseFunctionTypeParam();
6670
        }
6671
        expect(')');
6672
        expect(':');
6673
        returnType = parseType();
6674
6675
        return markerApply(marker, delegate.createFunctionTypeAnnotation(
6676
            params,
6677
            returnType,
6678
            rest,
6679
            typeParameters
6680
        ));
6681
    }
6682
6683
    function parseObjectTypeMethod(marker, isStatic, key) {
6684
        var optional = false, value;
6685
        value = parseObjectTypeMethodish(marker);
6686
6687
        return markerApply(marker, delegate.createObjectTypeProperty(
6688
            key,
6689
            value,
6690
            optional,
6691
            isStatic
6692
        ));
6693
    }
6694
6695
    function parseObjectTypeCallProperty(marker, isStatic) {
6696
        var valueMarker = markerCreate();
6697
        return markerApply(marker, delegate.createObjectTypeCallProperty(
6698
            parseObjectTypeMethodish(valueMarker),
6699
            isStatic
6700
        ));
6701
    }
6702
6703
    function parseObjectType(allowStatic) {
6704
        var callProperties = [], indexers = [], marker, optional = false,
6705
            properties = [], propertyKey, propertyTypeAnnotation,
6706
            token, isStatic, matchStatic;
6707
6708
        expect('{');
6709
6710
        while (!match('}')) {
6711
            marker = markerCreate();
6712
            matchStatic =
6713
                   strict
6714
                   ? matchKeyword('static')
6715
                   : matchContextualKeyword('static');
6716
6717
            if (allowStatic && matchStatic) {
6718
                token = lex();
6719
                isStatic = true;
6720
            }
6721
6722
            if (match('[')) {
6723
                indexers.push(parseObjectTypeIndexer(marker, isStatic));
0 ignored issues
show
Bug introduced by
The variable isStatic seems to not be initialized for all possible execution paths. Are you sure parseObjectTypeIndexer handles undefined variables?
Loading history...
6724
            } else if (match('(') || match('<')) {
6725
                callProperties.push(parseObjectTypeCallProperty(marker, allowStatic));
6726
            } else {
6727
                if (isStatic && match(':')) {
6728
                    propertyKey = markerApply(marker, delegate.createIdentifier(token));
0 ignored issues
show
Bug introduced by
The variable token seems to not be initialized for all possible execution paths. Are you sure createIdentifier handles undefined variables?
Loading history...
6729
                    throwErrorTolerant(token, Messages.StrictReservedWord);
6730
                } else {
6731
                    propertyKey = parseObjectPropertyKey();
6732
                }
6733
                if (match('<') || match('(')) {
6734
                    // This is a method property
6735
                    properties.push(parseObjectTypeMethod(marker, isStatic, propertyKey));
6736
                } else {
6737
                    if (match('?')) {
6738
                        lex();
6739
                        optional = true;
6740
                    }
6741
                    expect(':');
6742
                    propertyTypeAnnotation = parseType();
6743
                    properties.push(markerApply(marker, delegate.createObjectTypeProperty(
6744
                        propertyKey,
6745
                        propertyTypeAnnotation,
6746
                        optional,
6747
                        isStatic
6748
                    )));
6749
                }
6750
            }
6751
6752
            if (match(';')) {
6753
                lex();
6754
            } else if (!match('}')) {
6755
                throwUnexpected(lookahead);
6756
            }
6757
        }
6758
6759
        expect('}');
6760
6761
        return delegate.createObjectTypeAnnotation(
6762
            properties,
6763
            indexers,
6764
            callProperties
6765
        );
6766
    }
6767
6768
    function parseGenericType() {
6769
        var marker = markerCreate(),
6770
            typeParameters = null, typeIdentifier;
6771
6772
        typeIdentifier = parseVariableIdentifier();
6773
6774
        while (match('.')) {
6775
            expect('.');
6776
            typeIdentifier = markerApply(marker, delegate.createQualifiedTypeIdentifier(
6777
                typeIdentifier,
6778
                parseVariableIdentifier()
6779
            ));
6780
        }
6781
6782
        if (match('<')) {
6783
            typeParameters = parseTypeParameterInstantiation();
6784
        }
6785
6786
        return markerApply(marker, delegate.createGenericTypeAnnotation(
6787
            typeIdentifier,
6788
            typeParameters
6789
        ));
6790
    }
6791
6792
    function parseVoidType() {
6793
        var marker = markerCreate();
6794
        expectKeyword('void');
6795
        return markerApply(marker, delegate.createVoidTypeAnnotation());
6796
    }
6797
6798
    function parseTypeofType() {
6799
        var argument, marker = markerCreate();
6800
        expectKeyword('typeof');
6801
        argument = parsePrimaryType();
6802
        return markerApply(marker, delegate.createTypeofTypeAnnotation(
6803
            argument
6804
        ));
6805
    }
6806
6807
    function parseTupleType() {
6808
        var marker = markerCreate(), types = [];
6809
        expect('[');
6810
        // We allow trailing commas
6811
        while (index < length && !match(']')) {
6812
            types.push(parseType());
6813
            if (match(']')) {
6814
                break;
6815
            }
6816
            expect(',');
6817
        }
6818
        expect(']');
6819
        return markerApply(marker, delegate.createTupleTypeAnnotation(
6820
            types
6821
        ));
6822
    }
6823
6824
    function parseFunctionTypeParam() {
6825
        var marker = markerCreate(), name, optional = false, typeAnnotation;
6826
        name = parseVariableIdentifier();
6827
        if (match('?')) {
6828
            lex();
6829
            optional = true;
6830
        }
6831
        expect(':');
6832
        typeAnnotation = parseType();
6833
        return markerApply(marker, delegate.createFunctionTypeParam(
6834
            name,
6835
            typeAnnotation,
6836
            optional
6837
        ));
6838
    }
6839
6840
    function parseFunctionTypeParams() {
6841
        var ret = { params: [], rest: null };
6842
        while (lookahead.type === Token.Identifier) {
6843
            ret.params.push(parseFunctionTypeParam());
6844
            if (!match(')')) {
6845
                expect(',');
6846
            }
6847
        }
6848
6849
        if (match('...')) {
6850
            lex();
6851
            ret.rest = parseFunctionTypeParam();
6852
        }
6853
        return ret;
6854
    }
6855
6856
    // The parsing of types roughly parallels the parsing of expressions, and
6857
    // primary types are kind of like primary expressions...they're the
6858
    // primitives with which other types are constructed.
6859
    function parsePrimaryType() {
6860
        var params = null, returnType = null,
0 ignored issues
show
Unused Code introduced by
The assignment to returnType seems to be never used. If you intend to free memory here, this is not necessary since the variable leaves the scope anyway.
Loading history...
6861
            marker = markerCreate(), rest = null, tmp,
6862
            typeParameters, token, type, isGroupedType = false;
6863
6864
        switch (lookahead.type) {
0 ignored issues
show
Coding Style introduced by
As per coding-style, switch statements should have a default case.
Loading history...
6865
        case Token.Identifier:
0 ignored issues
show
Bug introduced by
The variable Token seems to be never declared. If this is a global, consider adding a /** global: Token */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
6866
            switch (lookahead.value) {
6867
            case 'any':
6868
                lex();
6869
                return markerApply(marker, delegate.createAnyTypeAnnotation());
6870
            case 'bool':  // fallthrough
6871
            case 'boolean':
6872
                lex();
6873
                return markerApply(marker, delegate.createBooleanTypeAnnotation());
6874
            case 'number':
6875
                lex();
6876
                return markerApply(marker, delegate.createNumberTypeAnnotation());
6877
            case 'string':
6878
                lex();
6879
                return markerApply(marker, delegate.createStringTypeAnnotation());
6880
            }
6881
            return markerApply(marker, parseGenericType());
6882
        case Token.Punctuator:
6883
            switch (lookahead.value) {
6884
            case '{':
6885
                return markerApply(marker, parseObjectType());
6886
            case '[':
6887
                return parseTupleType();
6888
            case '<':
6889
                typeParameters = parseTypeParameterDeclaration();
6890
                expect('(');
6891
                tmp = parseFunctionTypeParams();
6892
                params = tmp.params;
6893
                rest = tmp.rest;
6894
                expect(')');
6895
6896
                expect('=>');
6897
6898
                returnType = parseType();
6899
6900
                return markerApply(marker, delegate.createFunctionTypeAnnotation(
6901
                    params,
6902
                    returnType,
6903
                    rest,
6904
                    typeParameters
6905
                ));
6906
            case '(':
6907
                lex();
6908
                // Check to see if this is actually a grouped type
6909
                if (!match(')') && !match('...')) {
6910
                    if (lookahead.type === Token.Identifier) {
6911
                        token = lookahead2();
6912
                        isGroupedType = token.value !== '?' && token.value !== ':';
6913
                    } else {
6914
                        isGroupedType = true;
6915
                    }
6916
                }
6917
6918
                if (isGroupedType) {
6919
                    type = parseType();
6920
                    expect(')');
6921
6922
                    // If we see a => next then someone was probably confused about
6923
                    // function types, so we can provide a better error message
6924
                    if (match('=>')) {
6925
                        throwError({}, Messages.ConfusedAboutFunctionType);
6926
                    }
6927
6928
                    return type;
6929
                }
6930
6931
                tmp = parseFunctionTypeParams();
6932
                params = tmp.params;
6933
                rest = tmp.rest;
6934
6935
                expect(')');
6936
6937
                expect('=>');
6938
6939
                returnType = parseType();
6940
6941
                return markerApply(marker, delegate.createFunctionTypeAnnotation(
6942
                    params,
6943
                    returnType,
6944
                    rest,
6945
                    null /* typeParameters */
6946
                ));
6947
            }
6948
            break;
6949
        case Token.Keyword:
6950
            switch (lookahead.value) {
6951
            case 'void':
6952
                return markerApply(marker, parseVoidType());
6953
            case 'typeof':
6954
                return markerApply(marker, parseTypeofType());
6955
            }
6956
            break;
6957
        case Token.StringLiteral:
6958
            token = lex();
6959
            if (token.octal) {
6960
                throwError(token, Messages.StrictOctalLiteral);
6961
            }
6962
            return markerApply(marker, delegate.createStringLiteralTypeAnnotation(
6963
                token
6964
            ));
6965
        }
6966
6967
        throwUnexpected(lookahead);
0 ignored issues
show
Best Practice introduced by
There is no return statement in this branch, but you do return something in other branches. Did you maybe miss it? If you do not want to return anything, consider adding return undefined; explicitly.
Loading history...
6968
    }
6969
6970
    function parsePostfixType() {
6971
        var marker = markerCreate(), t = parsePrimaryType();
6972
        if (match('[')) {
6973
            expect('[');
6974
            expect(']');
6975
            return markerApply(marker, delegate.createArrayTypeAnnotation(t));
6976
        }
6977
        return t;
6978
    }
6979
6980
    function parsePrefixType() {
6981
        var marker = markerCreate();
6982
        if (match('?')) {
6983
            lex();
6984
            return markerApply(marker, delegate.createNullableTypeAnnotation(
6985
                parsePrefixType()
6986
            ));
6987
        }
6988
        return parsePostfixType();
6989
    }
6990
6991
6992
    function parseIntersectionType() {
6993
        var marker = markerCreate(), type, types;
6994
        type = parsePrefixType();
6995
        types = [type];
6996
        while (match('&')) {
6997
            lex();
6998
            types.push(parsePrefixType());
6999
        }
7000
7001
        return types.length === 1 ?
7002
                type :
7003
                markerApply(marker, delegate.createIntersectionTypeAnnotation(
7004
                    types
7005
                ));
7006
    }
7007
7008
    function parseUnionType() {
7009
        var marker = markerCreate(), type, types;
7010
        type = parseIntersectionType();
7011
        types = [type];
7012
        while (match('|')) {
7013
            lex();
7014
            types.push(parseIntersectionType());
7015
        }
7016
        return types.length === 1 ?
7017
                type :
7018
                markerApply(marker, delegate.createUnionTypeAnnotation(
7019
                    types
7020
                ));
7021
    }
7022
7023
    function parseType() {
7024
        var oldInType = state.inType, type;
7025
        state.inType = true;
7026
7027
        type = parseUnionType();
7028
7029
        state.inType = oldInType;
7030
        return type;
7031
    }
7032
7033
    function parseTypeAnnotation() {
7034
        var marker = markerCreate(), type;
7035
7036
        expect(':');
7037
        type = parseType();
7038
7039
        return markerApply(marker, delegate.createTypeAnnotation(type));
7040
    }
7041
7042
    function parseVariableIdentifier() {
7043
        var marker = markerCreate(),
7044
            token = lex();
7045
7046
        if (token.type !== Token.Identifier) {
7047
            throwUnexpected(token);
7048
        }
7049
7050
        return markerApply(marker, delegate.createIdentifier(token.value));
7051
    }
7052
7053
    function parseTypeAnnotatableIdentifier(requireTypeAnnotation, canBeOptionalParam) {
7054
        var marker = markerCreate(),
7055
            ident = parseVariableIdentifier(),
7056
            isOptionalParam = false;
7057
7058
        if (canBeOptionalParam && match('?')) {
7059
            expect('?');
7060
            isOptionalParam = true;
7061
        }
7062
7063
        if (requireTypeAnnotation || match(':')) {
7064
            ident.typeAnnotation = parseTypeAnnotation();
7065
            ident = markerApply(marker, ident);
7066
        }
7067
7068
        if (isOptionalParam) {
7069
            ident.optional = true;
7070
            ident = markerApply(marker, ident);
7071
        }
7072
7073
        return ident;
7074
    }
7075
7076
    function parseVariableDeclaration(kind) {
7077
        var id,
7078
            marker = markerCreate(),
7079
            init = null,
7080
            typeAnnotationMarker = markerCreate();
7081
        if (match('{')) {
7082
            id = parseObjectInitialiser();
7083
            reinterpretAsAssignmentBindingPattern(id);
7084
            if (match(':')) {
7085
                id.typeAnnotation = parseTypeAnnotation();
7086
                markerApply(typeAnnotationMarker, id);
7087
            }
7088
        } else if (match('[')) {
7089
            id = parseArrayInitialiser();
7090
            reinterpretAsAssignmentBindingPattern(id);
7091
            if (match(':')) {
7092
                id.typeAnnotation = parseTypeAnnotation();
7093
                markerApply(typeAnnotationMarker, id);
7094
            }
7095
        } else {
7096
            /* istanbul ignore next */
7097
            id = state.allowKeyword ? parseNonComputedProperty() : parseTypeAnnotatableIdentifier();
7098
            // 12.2.1
7099
            if (strict && isRestrictedWord(id.name)) {
7100
                throwErrorTolerant({}, Messages.StrictVarName);
7101
            }
7102
        }
7103
7104
        if (kind === 'const') {
7105
            if (!match('=')) {
7106
                throwError({}, Messages.NoUninitializedConst);
7107
            }
7108
            expect('=');
7109
            init = parseAssignmentExpression();
7110
        } else if (match('=')) {
7111
            lex();
7112
            init = parseAssignmentExpression();
7113
        }
7114
7115
        return markerApply(marker, delegate.createVariableDeclarator(id, init));
7116
    }
7117
7118
    function parseVariableDeclarationList(kind) {
7119
        var list = [];
7120
7121
        do {
7122
            list.push(parseVariableDeclaration(kind));
7123
            if (!match(',')) {
7124
                break;
7125
            }
7126
            lex();
7127
        } while (index < length);
7128
7129
        return list;
7130
    }
7131
7132
    function parseVariableStatement() {
7133
        var declarations, marker = markerCreate();
7134
7135
        expectKeyword('var');
7136
7137
        declarations = parseVariableDeclarationList();
7138
7139
        consumeSemicolon();
7140
7141
        return markerApply(marker, delegate.createVariableDeclaration(declarations, 'var'));
7142
    }
7143
7144
    // kind may be `const` or `let`
7145
    // Both are experimental and not in the specification yet.
7146
    // see http://wiki.ecmascript.org/doku.php?id=harmony:const
7147
    // and http://wiki.ecmascript.org/doku.php?id=harmony:let
7148
    function parseConstLetDeclaration(kind) {
7149
        var declarations, marker = markerCreate();
7150
7151
        expectKeyword(kind);
7152
7153
        declarations = parseVariableDeclarationList(kind);
7154
7155
        consumeSemicolon();
7156
7157
        return markerApply(marker, delegate.createVariableDeclaration(declarations, kind));
7158
    }
7159
7160
    // people.mozilla.org/~jorendorff/es6-draft.html
7161
7162
    function parseModuleSpecifier() {
7163
        var marker = markerCreate(),
7164
            specifier;
7165
7166
        if (lookahead.type !== Token.StringLiteral) {
7167
            throwError({}, Messages.InvalidModuleSpecifier);
7168
        }
7169
        specifier = delegate.createModuleSpecifier(lookahead);
7170
        lex();
7171
        return markerApply(marker, specifier);
7172
    }
7173
7174
    function parseExportBatchSpecifier() {
7175
        var marker = markerCreate();
7176
        expect('*');
7177
        return markerApply(marker, delegate.createExportBatchSpecifier());
7178
    }
7179
7180
    function parseExportSpecifier() {
7181
        var id, name = null, marker = markerCreate(), from;
0 ignored issues
show
Unused Code introduced by
The variable from seems to be never used. Consider removing it.
Loading history...
7182
        if (matchKeyword('default')) {
7183
            lex();
7184
            id = markerApply(marker, delegate.createIdentifier('default'));
7185
            // export {default} from "something";
7186
        } else {
7187
            id = parseVariableIdentifier();
7188
        }
7189
        if (matchContextualKeyword('as')) {
7190
            lex();
7191
            name = parseNonComputedProperty();
7192
        }
7193
7194
        return markerApply(marker, delegate.createExportSpecifier(id, name));
7195
    }
7196
7197
    function parseExportDeclaration() {
7198
        var declaration = null,
7199
            possibleIdentifierToken, sourceElement,
7200
            isExportFromIdentifier,
7201
            src = null, specifiers = [],
7202
            marker = markerCreate();
7203
7204
        expectKeyword('export');
7205
7206
        if (matchKeyword('default')) {
7207
            // covers:
7208
            // export default ...
7209
            lex();
7210
            if (matchKeyword('function') || matchKeyword('class')) {
7211
                possibleIdentifierToken = lookahead2();
7212
                if (isIdentifierName(possibleIdentifierToken)) {
7213
                    // covers:
7214
                    // export default function foo () {}
7215
                    // export default class foo {}
7216
                    sourceElement = parseSourceElement();
7217
                    return markerApply(marker, delegate.createExportDeclaration(true, sourceElement, [sourceElement.id], null));
7218
                }
7219
                // covers:
7220
                // export default function () {}
7221
                // export default class {}
7222
                switch (lookahead.value) {
0 ignored issues
show
Coding Style introduced by
As per coding-style, switch statements should have a default case.
Loading history...
7223
                case 'class':
7224
                    return markerApply(marker, delegate.createExportDeclaration(true, parseClassExpression(), [], null));
7225
                case 'function':
7226
                    return markerApply(marker, delegate.createExportDeclaration(true, parseFunctionExpression(), [], null));
7227
                }
7228
            }
7229
7230
            if (matchContextualKeyword('from')) {
7231
                throwError({}, Messages.UnexpectedToken, lookahead.value);
7232
            }
7233
7234
            // covers:
7235
            // export default {};
7236
            // export default [];
7237
            if (match('{')) {
7238
                declaration = parseObjectInitialiser();
7239
            } else if (match('[')) {
7240
                declaration = parseArrayInitialiser();
7241
            } else {
7242
                declaration = parseAssignmentExpression();
7243
            }
7244
            consumeSemicolon();
7245
            return markerApply(marker, delegate.createExportDeclaration(true, declaration, [], null));
7246
        }
7247
7248
        // non-default export
7249
        if (lookahead.type === Token.Keyword || matchContextualKeyword('type')) {
7250
            // covers:
7251
            // export var f = 1;
7252
            switch (lookahead.value) {
0 ignored issues
show
Coding Style introduced by
As per coding-style, switch statements should have a default case.
Loading history...
7253
            case 'type':
7254
            case 'let':
7255
            case 'const':
7256
            case 'var':
7257
            case 'class':
7258
            case 'function':
7259
                return markerApply(marker, delegate.createExportDeclaration(false, parseSourceElement(), specifiers, null));
7260
            }
7261
        }
7262
7263
        if (match('*')) {
7264
            // covers:
7265
            // export * from "foo";
7266
            specifiers.push(parseExportBatchSpecifier());
7267
7268
            if (!matchContextualKeyword('from')) {
7269
                throwError({}, lookahead.value ?
7270
                        Messages.UnexpectedToken : Messages.MissingFromClause, lookahead.value);
7271
            }
7272
            lex();
7273
            src = parseModuleSpecifier();
7274
            consumeSemicolon();
7275
7276
            return markerApply(marker, delegate.createExportDeclaration(false, null, specifiers, src));
7277
        }
7278
7279
        expect('{');
7280
        if (!match('}')) {
7281
            do {
7282
                isExportFromIdentifier = isExportFromIdentifier || matchKeyword('default');
7283
                specifiers.push(parseExportSpecifier());
7284
            } while (match(',') && lex());
7285
        }
7286
        expect('}');
7287
7288
        if (matchContextualKeyword('from')) {
7289
            // covering:
7290
            // export {default} from "foo";
7291
            // export {foo} from "foo";
7292
            lex();
7293
            src = parseModuleSpecifier();
7294
            consumeSemicolon();
7295
        } else if (isExportFromIdentifier) {
7296
            // covering:
7297
            // export {default}; // missing fromClause
7298
            throwError({}, lookahead.value ?
7299
                    Messages.UnexpectedToken : Messages.MissingFromClause, lookahead.value);
7300
        } else {
7301
            // cover
7302
            // export {foo};
7303
            consumeSemicolon();
7304
        }
7305
        return markerApply(marker, delegate.createExportDeclaration(false, declaration, specifiers, src));
7306
    }
7307
7308
7309
    function parseImportSpecifier() {
7310
        // import {<foo as bar>} ...;
7311
        var id, name = null, marker = markerCreate();
7312
7313
        id = parseNonComputedProperty();
7314
        if (matchContextualKeyword('as')) {
7315
            lex();
7316
            name = parseVariableIdentifier();
7317
        }
7318
7319
        return markerApply(marker, delegate.createImportSpecifier(id, name));
7320
    }
7321
7322
    function parseNamedImports() {
7323
        var specifiers = [];
7324
        // {foo, bar as bas}
7325
        expect('{');
7326
        if (!match('}')) {
7327
            do {
7328
                specifiers.push(parseImportSpecifier());
7329
            } while (match(',') && lex());
7330
        }
7331
        expect('}');
7332
        return specifiers;
7333
    }
7334
7335
    function parseImportDefaultSpecifier() {
7336
        // import <foo> ...;
7337
        var id, marker = markerCreate();
7338
7339
        id = parseNonComputedProperty();
7340
7341
        return markerApply(marker, delegate.createImportDefaultSpecifier(id));
7342
    }
7343
7344
    function parseImportNamespaceSpecifier() {
7345
        // import <* as foo> ...;
7346
        var id, marker = markerCreate();
7347
7348
        expect('*');
7349
        if (!matchContextualKeyword('as')) {
7350
            throwError({}, Messages.NoAsAfterImportNamespace);
7351
        }
7352
        lex();
7353
        id = parseNonComputedProperty();
7354
7355
        return markerApply(marker, delegate.createImportNamespaceSpecifier(id));
7356
    }
7357
7358
    function parseImportDeclaration() {
7359
        var specifiers, src, marker = markerCreate(), isType = false, token2;
7360
7361
        expectKeyword('import');
7362
7363
        if (matchContextualKeyword('type')) {
7364
            token2 = lookahead2();
7365
            if ((token2.type === Token.Identifier && token2.value !== 'from') ||
7366
                    (token2.type === Token.Punctuator &&
7367
                        (token2.value === '{' || token2.value === '*'))) {
7368
                isType = true;
7369
                lex();
7370
            }
7371
        }
7372
7373
        specifiers = [];
7374
7375
        if (lookahead.type === Token.StringLiteral) {
7376
            // covers:
7377
            // import "foo";
7378
            src = parseModuleSpecifier();
7379
            consumeSemicolon();
7380
            return markerApply(marker, delegate.createImportDeclaration(specifiers, src, isType));
7381
        }
7382
7383
        if (!matchKeyword('default') && isIdentifierName(lookahead)) {
7384
            // covers:
7385
            // import foo
7386
            // import foo, ...
7387
            specifiers.push(parseImportDefaultSpecifier());
7388
            if (match(',')) {
7389
                lex();
7390
            }
7391
        }
7392
        if (match('*')) {
7393
            // covers:
7394
            // import foo, * as foo
7395
            // import * as foo
7396
            specifiers.push(parseImportNamespaceSpecifier());
7397
        } else if (match('{')) {
7398
            // covers:
7399
            // import foo, {bar}
7400
            // import {bar}
7401
            specifiers = specifiers.concat(parseNamedImports());
7402
        }
7403
7404
        if (!matchContextualKeyword('from')) {
7405
            throwError({}, lookahead.value ?
7406
                    Messages.UnexpectedToken : Messages.MissingFromClause, lookahead.value);
7407
        }
7408
        lex();
7409
        src = parseModuleSpecifier();
7410
        consumeSemicolon();
7411
7412
        return markerApply(marker, delegate.createImportDeclaration(specifiers, src, isType));
7413
    }
7414
7415
    // 12.3 Empty Statement
7416
7417
    function parseEmptyStatement() {
7418
        var marker = markerCreate();
7419
        expect(';');
7420
        return markerApply(marker, delegate.createEmptyStatement());
7421
    }
7422
7423
    // 12.4 Expression Statement
7424
7425
    function parseExpressionStatement() {
7426
        var marker = markerCreate(), expr = parseExpression();
7427
        consumeSemicolon();
7428
        return markerApply(marker, delegate.createExpressionStatement(expr));
7429
    }
7430
7431
    // 12.5 If statement
7432
7433
    function parseIfStatement() {
7434
        var test, consequent, alternate, marker = markerCreate();
7435
7436
        expectKeyword('if');
7437
7438
        expect('(');
7439
7440
        test = parseExpression();
7441
7442
        expect(')');
7443
7444
        consequent = parseStatement();
7445
7446
        if (matchKeyword('else')) {
7447
            lex();
7448
            alternate = parseStatement();
7449
        } else {
7450
            alternate = null;
7451
        }
7452
7453
        return markerApply(marker, delegate.createIfStatement(test, consequent, alternate));
7454
    }
7455
7456
    // 12.6 Iteration Statements
7457
7458
    function parseDoWhileStatement() {
7459
        var body, test, oldInIteration, marker = markerCreate();
7460
7461
        expectKeyword('do');
7462
7463
        oldInIteration = state.inIteration;
7464
        state.inIteration = true;
7465
7466
        body = parseStatement();
7467
7468
        state.inIteration = oldInIteration;
7469
7470
        expectKeyword('while');
7471
7472
        expect('(');
7473
7474
        test = parseExpression();
7475
7476
        expect(')');
7477
7478
        if (match(';')) {
7479
            lex();
7480
        }
7481
7482
        return markerApply(marker, delegate.createDoWhileStatement(body, test));
7483
    }
7484
7485
    function parseWhileStatement() {
7486
        var test, body, oldInIteration, marker = markerCreate();
7487
7488
        expectKeyword('while');
7489
7490
        expect('(');
7491
7492
        test = parseExpression();
7493
7494
        expect(')');
7495
7496
        oldInIteration = state.inIteration;
7497
        state.inIteration = true;
7498
7499
        body = parseStatement();
7500
7501
        state.inIteration = oldInIteration;
7502
7503
        return markerApply(marker, delegate.createWhileStatement(test, body));
7504
    }
7505
7506
    function parseForVariableDeclaration() {
7507
        var marker = markerCreate(),
7508
            token = lex(),
7509
            declarations = parseVariableDeclarationList();
7510
7511
        return markerApply(marker, delegate.createVariableDeclaration(declarations, token.value));
7512
    }
7513
7514
    function parseForStatement(opts) {
7515
        var init, test, update, left, right, body, operator, oldInIteration,
7516
            marker = markerCreate();
7517
        init = test = update = null;
7518
        expectKeyword('for');
7519
7520
        // http://wiki.ecmascript.org/doku.php?id=proposals:iterators_and_generators&s=each
7521
        if (matchContextualKeyword('each')) {
7522
            throwError({}, Messages.EachNotAllowed);
7523
        }
7524
7525
        expect('(');
7526
7527
        if (match(';')) {
7528
            lex();
7529
        } else {
7530
            if (matchKeyword('var') || matchKeyword('let') || matchKeyword('const')) {
7531
                state.allowIn = false;
7532
                init = parseForVariableDeclaration();
7533
                state.allowIn = true;
7534
7535
                if (init.declarations.length === 1) {
7536
                    if (matchKeyword('in') || matchContextualKeyword('of')) {
7537
                        operator = lookahead;
7538
                        if (!((operator.value === 'in' || init.kind !== 'var') && init.declarations[0].init)) {
7539
                            lex();
7540
                            left = init;
7541
                            right = parseExpression();
7542
                            init = null;
7543
                        }
7544
                    }
7545
                }
7546
            } else {
7547
                state.allowIn = false;
7548
                init = parseExpression();
7549
                state.allowIn = true;
7550
7551
                if (matchContextualKeyword('of')) {
7552
                    operator = lex();
7553
                    left = init;
7554
                    right = parseExpression();
7555
                    init = null;
7556
                } else if (matchKeyword('in')) {
7557
                    // LeftHandSideExpression
7558
                    if (!isAssignableLeftHandSide(init)) {
7559
                        throwError({}, Messages.InvalidLHSInForIn);
7560
                    }
7561
                    operator = lex();
7562
                    left = init;
7563
                    right = parseExpression();
7564
                    init = null;
7565
                }
7566
            }
7567
7568
            if (typeof left === 'undefined') {
0 ignored issues
show
Bug introduced by
The variable left seems to not be initialized for all possible execution paths.
Loading history...
7569
                expect(';');
7570
            }
7571
        }
7572
7573
        if (typeof left === 'undefined') {
7574
7575
            if (!match(';')) {
7576
                test = parseExpression();
7577
            }
7578
            expect(';');
7579
7580
            if (!match(')')) {
7581
                update = parseExpression();
7582
            }
7583
        }
7584
7585
        expect(')');
7586
7587
        oldInIteration = state.inIteration;
7588
        state.inIteration = true;
7589
7590
        if (!(opts !== undefined && opts.ignoreBody)) {
7591
            body = parseStatement();
7592
        }
7593
7594
        state.inIteration = oldInIteration;
7595
7596
        if (typeof left === 'undefined') {
7597
            return markerApply(marker, delegate.createForStatement(init, test, update, body));
0 ignored issues
show
Bug introduced by
The variable body does not seem to be initialized in case !(opts !== undefined && opts.ignoreBody) on line 7590 is false. Are you sure the function createForStatement handles undefined variables?
Loading history...
7598
        }
7599
7600
        if (operator.value === 'in') {
0 ignored issues
show
Bug introduced by
The variable operator seems to not be initialized for all possible execution paths.
Loading history...
7601
            return markerApply(marker, delegate.createForInStatement(left, right, body));
0 ignored issues
show
Bug introduced by
The variable right seems to not be initialized for all possible execution paths. Are you sure createForInStatement handles undefined variables?
Loading history...
7602
        }
7603
        return markerApply(marker, delegate.createForOfStatement(left, right, body));
7604
    }
7605
7606
    // 12.7 The continue statement
7607
7608
    function parseContinueStatement() {
7609
        var label = null, marker = markerCreate();
7610
7611
        expectKeyword('continue');
7612
7613
        // Optimize the most common form: 'continue;'.
7614
        if (source.charCodeAt(index) === 59) {
7615
            lex();
7616
7617
            if (!state.inIteration) {
7618
                throwError({}, Messages.IllegalContinue);
7619
            }
7620
7621
            return markerApply(marker, delegate.createContinueStatement(null));
7622
        }
7623
7624
        if (peekLineTerminator()) {
7625
            if (!state.inIteration) {
7626
                throwError({}, Messages.IllegalContinue);
7627
            }
7628
7629
            return markerApply(marker, delegate.createContinueStatement(null));
7630
        }
7631
7632
        if (lookahead.type === Token.Identifier) {
7633
            label = parseVariableIdentifier();
7634
7635
            if (!state.labelSet.has(label.name)) {
7636
                throwError({}, Messages.UnknownLabel, label.name);
7637
            }
7638
        }
7639
7640
        consumeSemicolon();
7641
7642
        if (label === null && !state.inIteration) {
7643
            throwError({}, Messages.IllegalContinue);
7644
        }
7645
7646
        return markerApply(marker, delegate.createContinueStatement(label));
7647
    }
7648
7649
    // 12.8 The break statement
7650
7651
    function parseBreakStatement() {
7652
        var label = null, marker = markerCreate();
7653
7654
        expectKeyword('break');
7655
7656
        // Catch the very common case first: immediately a semicolon (char #59).
7657
        if (source.charCodeAt(index) === 59) {
7658
            lex();
7659
7660
            if (!(state.inIteration || state.inSwitch)) {
7661
                throwError({}, Messages.IllegalBreak);
7662
            }
7663
7664
            return markerApply(marker, delegate.createBreakStatement(null));
7665
        }
7666
7667
        if (peekLineTerminator()) {
7668
            if (!(state.inIteration || state.inSwitch)) {
7669
                throwError({}, Messages.IllegalBreak);
7670
            }
7671
7672
            return markerApply(marker, delegate.createBreakStatement(null));
7673
        }
7674
7675
        if (lookahead.type === Token.Identifier) {
7676
            label = parseVariableIdentifier();
7677
7678
            if (!state.labelSet.has(label.name)) {
7679
                throwError({}, Messages.UnknownLabel, label.name);
7680
            }
7681
        }
7682
7683
        consumeSemicolon();
7684
7685
        if (label === null && !(state.inIteration || state.inSwitch)) {
7686
            throwError({}, Messages.IllegalBreak);
7687
        }
7688
7689
        return markerApply(marker, delegate.createBreakStatement(label));
7690
    }
7691
7692
    // 12.9 The return statement
7693
7694
    function parseReturnStatement() {
7695
        var argument = null, marker = markerCreate();
7696
7697
        expectKeyword('return');
7698
7699
        if (!state.inFunctionBody) {
7700
            throwErrorTolerant({}, Messages.IllegalReturn);
7701
        }
7702
7703
        // 'return' followed by a space and an identifier is very common.
7704
        if (source.charCodeAt(index) === 32) {
7705
            if (isIdentifierStart(source.charCodeAt(index + 1))) {
7706
                argument = parseExpression();
7707
                consumeSemicolon();
7708
                return markerApply(marker, delegate.createReturnStatement(argument));
7709
            }
7710
        }
7711
7712
        if (peekLineTerminator()) {
7713
            return markerApply(marker, delegate.createReturnStatement(null));
7714
        }
7715
7716
        if (!match(';')) {
7717
            if (!match('}') && lookahead.type !== Token.EOF) {
7718
                argument = parseExpression();
7719
            }
7720
        }
7721
7722
        consumeSemicolon();
7723
7724
        return markerApply(marker, delegate.createReturnStatement(argument));
7725
    }
7726
7727
    // 12.10 The with statement
7728
7729
    function parseWithStatement() {
7730
        var object, body, marker = markerCreate();
7731
7732
        if (strict) {
7733
            throwErrorTolerant({}, Messages.StrictModeWith);
7734
        }
7735
7736
        expectKeyword('with');
7737
7738
        expect('(');
7739
7740
        object = parseExpression();
7741
7742
        expect(')');
7743
7744
        body = parseStatement();
7745
7746
        return markerApply(marker, delegate.createWithStatement(object, body));
7747
    }
7748
7749
    // 12.10 The swith statement
7750
7751
    function parseSwitchCase() {
7752
        var test,
7753
            consequent = [],
7754
            sourceElement,
7755
            marker = markerCreate();
7756
7757
        if (matchKeyword('default')) {
7758
            lex();
7759
            test = null;
7760
        } else {
7761
            expectKeyword('case');
7762
            test = parseExpression();
7763
        }
7764
        expect(':');
7765
7766
        while (index < length) {
7767
            if (match('}') || matchKeyword('default') || matchKeyword('case')) {
7768
                break;
7769
            }
7770
            sourceElement = parseSourceElement();
7771
            if (typeof sourceElement === 'undefined') {
7772
                break;
7773
            }
7774
            consequent.push(sourceElement);
7775
        }
7776
7777
        return markerApply(marker, delegate.createSwitchCase(test, consequent));
7778
    }
7779
7780
    function parseSwitchStatement() {
7781
        var discriminant, cases, clause, oldInSwitch, defaultFound, marker = markerCreate();
7782
7783
        expectKeyword('switch');
7784
7785
        expect('(');
7786
7787
        discriminant = parseExpression();
7788
7789
        expect(')');
7790
7791
        expect('{');
7792
7793
        cases = [];
7794
7795
        if (match('}')) {
7796
            lex();
7797
            return markerApply(marker, delegate.createSwitchStatement(discriminant, cases));
7798
        }
7799
7800
        oldInSwitch = state.inSwitch;
7801
        state.inSwitch = true;
7802
        defaultFound = false;
7803
7804
        while (index < length) {
7805
            if (match('}')) {
7806
                break;
7807
            }
7808
            clause = parseSwitchCase();
7809
            if (clause.test === null) {
7810
                if (defaultFound) {
7811
                    throwError({}, Messages.MultipleDefaultsInSwitch);
7812
                }
7813
                defaultFound = true;
7814
            }
7815
            cases.push(clause);
7816
        }
7817
7818
        state.inSwitch = oldInSwitch;
7819
7820
        expect('}');
7821
7822
        return markerApply(marker, delegate.createSwitchStatement(discriminant, cases));
7823
    }
7824
7825
    // 12.13 The throw statement
7826
7827
    function parseThrowStatement() {
7828
        var argument, marker = markerCreate();
7829
7830
        expectKeyword('throw');
7831
7832
        if (peekLineTerminator()) {
7833
            throwError({}, Messages.NewlineAfterThrow);
7834
        }
7835
7836
        argument = parseExpression();
7837
7838
        consumeSemicolon();
7839
7840
        return markerApply(marker, delegate.createThrowStatement(argument));
7841
    }
7842
7843
    // 12.14 The try statement
7844
7845
    function parseCatchClause() {
7846
        var param, body, marker = markerCreate();
7847
7848
        expectKeyword('catch');
7849
7850
        expect('(');
7851
        if (match(')')) {
7852
            throwUnexpected(lookahead);
7853
        }
7854
7855
        param = parseExpression();
7856
        // 12.14.1
7857
        if (strict && param.type === Syntax.Identifier && isRestrictedWord(param.name)) {
7858
            throwErrorTolerant({}, Messages.StrictCatchVariable);
7859
        }
7860
7861
        expect(')');
7862
        body = parseBlock();
7863
        return markerApply(marker, delegate.createCatchClause(param, body));
7864
    }
7865
7866
    function parseTryStatement() {
7867
        var block, handlers = [], finalizer = null, marker = markerCreate();
7868
7869
        expectKeyword('try');
7870
7871
        block = parseBlock();
7872
7873
        if (matchKeyword('catch')) {
7874
            handlers.push(parseCatchClause());
7875
        }
7876
7877
        if (matchKeyword('finally')) {
7878
            lex();
7879
            finalizer = parseBlock();
7880
        }
7881
7882
        if (handlers.length === 0 && !finalizer) {
7883
            throwError({}, Messages.NoCatchOrFinally);
7884
        }
7885
7886
        return markerApply(marker, delegate.createTryStatement(block, [], handlers, finalizer));
7887
    }
7888
7889
    // 12.15 The debugger statement
7890
7891
    function parseDebuggerStatement() {
7892
        var marker = markerCreate();
7893
        expectKeyword('debugger');
7894
7895
        consumeSemicolon();
7896
7897
        return markerApply(marker, delegate.createDebuggerStatement());
7898
    }
7899
7900
    // 12 Statements
7901
7902
    function parseStatement() {
7903
        var type = lookahead.type,
7904
            marker,
7905
            expr,
7906
            labeledBody;
7907
7908
        if (type === Token.EOF) {
7909
            throwUnexpected(lookahead);
7910
        }
7911
7912
        if (type === Token.Punctuator) {
7913
            switch (lookahead.value) {
7914
            case ';':
7915
                return parseEmptyStatement();
7916
            case '{':
7917
                return parseBlock();
7918
            case '(':
7919
                return parseExpressionStatement();
7920
            default:
7921
                break;
7922
            }
7923
        }
7924
7925
        if (type === Token.Keyword) {
7926
            switch (lookahead.value) {
7927
            case 'break':
7928
                return parseBreakStatement();
7929
            case 'continue':
7930
                return parseContinueStatement();
7931
            case 'debugger':
7932
                return parseDebuggerStatement();
7933
            case 'do':
7934
                return parseDoWhileStatement();
7935
            case 'for':
7936
                return parseForStatement();
7937
            case 'function':
7938
                return parseFunctionDeclaration();
7939
            case 'class':
7940
                return parseClassDeclaration();
7941
            case 'if':
7942
                return parseIfStatement();
7943
            case 'return':
7944
                return parseReturnStatement();
7945
            case 'switch':
7946
                return parseSwitchStatement();
7947
            case 'throw':
7948
                return parseThrowStatement();
7949
            case 'try':
7950
                return parseTryStatement();
7951
            case 'var':
7952
                return parseVariableStatement();
7953
            case 'while':
7954
                return parseWhileStatement();
7955
            case 'with':
7956
                return parseWithStatement();
7957
            default:
7958
                break;
7959
            }
7960
        }
7961
7962
        if (matchAsyncFuncExprOrDecl()) {
7963
            return parseFunctionDeclaration();
7964
        }
7965
7966
        marker = markerCreate();
7967
        expr = parseExpression();
7968
7969
        // 12.12 Labelled Statements
7970
        if ((expr.type === Syntax.Identifier) && match(':')) {
7971
            lex();
7972
7973
            if (state.labelSet.has(expr.name)) {
7974
                throwError({}, Messages.Redeclaration, 'Label', expr.name);
7975
            }
7976
7977
            state.labelSet.set(expr.name, true);
7978
            labeledBody = parseStatement();
7979
            state.labelSet["delete"](expr.name);
7980
            return markerApply(marker, delegate.createLabeledStatement(expr, labeledBody));
7981
        }
7982
7983
        consumeSemicolon();
7984
7985
        return markerApply(marker, delegate.createExpressionStatement(expr));
7986
    }
7987
7988
    // 13 Function Definition
7989
7990
    function parseConciseBody() {
7991
        if (match('{')) {
7992
            return parseFunctionSourceElements();
7993
        }
7994
        return parseAssignmentExpression();
7995
    }
7996
7997
    function parseFunctionSourceElements() {
7998
        var sourceElement, sourceElements = [], token, directive, firstRestricted,
7999
            oldLabelSet, oldInIteration, oldInSwitch, oldInFunctionBody, oldParenthesizedCount,
8000
            marker = markerCreate();
8001
8002
        expect('{');
8003
8004
        while (index < length) {
8005
            if (lookahead.type !== Token.StringLiteral) {
8006
                break;
8007
            }
8008
            token = lookahead;
8009
8010
            sourceElement = parseSourceElement();
8011
            sourceElements.push(sourceElement);
8012
            if (sourceElement.expression.type !== Syntax.Literal) {
8013
                // this is not directive
8014
                break;
8015
            }
8016
            directive = source.slice(token.range[0] + 1, token.range[1] - 1);
8017
            if (directive === 'use ' + 'strict') {
8018
                strict = true;
8019
                if (firstRestricted) {
8020
                    throwErrorTolerant(firstRestricted, Messages.StrictOctalLiteral);
8021
                }
8022
            } else {
8023
                if (!firstRestricted && token.octal) {
8024
                    firstRestricted = token;
8025
                }
8026
            }
8027
        }
8028
8029
        oldLabelSet = state.labelSet;
8030
        oldInIteration = state.inIteration;
8031
        oldInSwitch = state.inSwitch;
8032
        oldInFunctionBody = state.inFunctionBody;
8033
        oldParenthesizedCount = state.parenthesizedCount;
8034
8035
        state.labelSet = new StringMap();
8036
        state.inIteration = false;
8037
        state.inSwitch = false;
8038
        state.inFunctionBody = true;
8039
        state.parenthesizedCount = 0;
8040
8041
        while (index < length) {
8042
            if (match('}')) {
8043
                break;
8044
            }
8045
            sourceElement = parseSourceElement();
8046
            if (typeof sourceElement === 'undefined') {
8047
                break;
8048
            }
8049
            sourceElements.push(sourceElement);
8050
        }
8051
8052
        expect('}');
8053
8054
        state.labelSet = oldLabelSet;
8055
        state.inIteration = oldInIteration;
8056
        state.inSwitch = oldInSwitch;
8057
        state.inFunctionBody = oldInFunctionBody;
8058
        state.parenthesizedCount = oldParenthesizedCount;
8059
8060
        return markerApply(marker, delegate.createBlockStatement(sourceElements));
8061
    }
8062
8063
    function validateParam(options, param, name) {
8064
        if (strict) {
8065
            if (isRestrictedWord(name)) {
8066
                options.stricted = param;
8067
                options.message = Messages.StrictParamName;
8068
            }
8069
            if (options.paramSet.has(name)) {
8070
                options.stricted = param;
8071
                options.message = Messages.StrictParamDupe;
8072
            }
8073
        } else if (!options.firstRestricted) {
8074
            if (isRestrictedWord(name)) {
8075
                options.firstRestricted = param;
8076
                options.message = Messages.StrictParamName;
8077
            } else if (isStrictModeReservedWord(name)) {
8078
                options.firstRestricted = param;
8079
                options.message = Messages.StrictReservedWord;
8080
            } else if (options.paramSet.has(name)) {
8081
                options.firstRestricted = param;
8082
                options.message = Messages.StrictParamDupe;
8083
            }
8084
        }
8085
        options.paramSet.set(name, true);
8086
    }
8087
8088
    function parseParam(options) {
8089
        var marker, token, rest, param, def;
8090
8091
        token = lookahead;
8092
        if (token.value === '...') {
8093
            token = lex();
8094
            rest = true;
8095
        }
8096
8097
        if (match('[')) {
8098
            marker = markerCreate();
8099
            param = parseArrayInitialiser();
8100
            reinterpretAsDestructuredParameter(options, param);
8101
            if (match(':')) {
8102
                param.typeAnnotation = parseTypeAnnotation();
8103
                markerApply(marker, param);
8104
            }
8105
        } else if (match('{')) {
8106
            marker = markerCreate();
8107
            if (rest) {
8108
                throwError({}, Messages.ObjectPatternAsRestParameter);
8109
            }
8110
            param = parseObjectInitialiser();
8111
            reinterpretAsDestructuredParameter(options, param);
8112
            if (match(':')) {
8113
                param.typeAnnotation = parseTypeAnnotation();
8114
                markerApply(marker, param);
8115
            }
8116
        } else {
8117
            param =
8118
                rest
8119
                ? parseTypeAnnotatableIdentifier(
8120
                    false, /* requireTypeAnnotation */
8121
                    false /* canBeOptionalParam */
8122
                )
8123
                : parseTypeAnnotatableIdentifier(
8124
                    false, /* requireTypeAnnotation */
8125
                    true /* canBeOptionalParam */
8126
                );
8127
8128
            validateParam(options, token, token.value);
8129
        }
8130
8131
        if (match('=')) {
8132
            if (rest) {
8133
                throwErrorTolerant(lookahead, Messages.DefaultRestParameter);
8134
            }
8135
            lex();
8136
            def = parseAssignmentExpression();
8137
            ++options.defaultCount;
8138
        }
8139
8140
        if (rest) {
8141
            if (!match(')')) {
8142
                throwError({}, Messages.ParameterAfterRestParameter);
8143
            }
8144
            options.rest = param;
8145
            return false;
8146
        }
8147
8148
        options.params.push(param);
8149
        options.defaults.push(def);
0 ignored issues
show
Bug introduced by
The variable def does not seem to be initialized in case match("=") on line 8131 is false. Are you sure the function push handles undefined variables?
Loading history...
8150
        return !match(')');
8151
    }
8152
8153
    function parseParams(firstRestricted) {
8154
        var options, marker = markerCreate();
8155
8156
        options = {
8157
            params: [],
8158
            defaultCount: 0,
8159
            defaults: [],
8160
            rest: null,
8161
            firstRestricted: firstRestricted
8162
        };
8163
8164
        expect('(');
8165
8166
        if (!match(')')) {
8167
            options.paramSet = new StringMap();
8168
            while (index < length) {
8169
                if (!parseParam(options)) {
8170
                    break;
8171
                }
8172
                expect(',');
8173
            }
8174
        }
8175
8176
        expect(')');
8177
8178
        if (options.defaultCount === 0) {
8179
            options.defaults = [];
8180
        }
8181
8182
        if (match(':')) {
8183
            options.returnType = parseTypeAnnotation();
8184
        }
8185
8186
        return markerApply(marker, options);
8187
    }
8188
8189
    function parseFunctionDeclaration() {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
8190
        var id, body, token, tmp, firstRestricted, message, generator, isAsync,
8191
            previousStrict, previousYieldAllowed, previousAwaitAllowed,
8192
            marker = markerCreate(), typeParameters;
8193
8194
        isAsync = false;
8195
        if (matchAsync()) {
8196
            lex();
8197
            isAsync = true;
8198
        }
8199
8200
        expectKeyword('function');
8201
8202
        generator = false;
8203
        if (match('*')) {
8204
            lex();
8205
            generator = true;
8206
        }
8207
8208
        token = lookahead;
8209
8210
        id = parseVariableIdentifier();
8211
8212
        if (match('<')) {
8213
            typeParameters = parseTypeParameterDeclaration();
8214
        }
8215
8216
        if (strict) {
8217
            if (isRestrictedWord(token.value)) {
8218
                throwErrorTolerant(token, Messages.StrictFunctionName);
8219
            }
8220
        } else {
8221
            if (isRestrictedWord(token.value)) {
8222
                firstRestricted = token;
8223
                message = Messages.StrictFunctionName;
8224
            } else if (isStrictModeReservedWord(token.value)) {
8225
                firstRestricted = token;
8226
                message = Messages.StrictReservedWord;
8227
            }
8228
        }
8229
8230
        tmp = parseParams(firstRestricted);
0 ignored issues
show
Bug introduced by
The variable firstRestricted seems to not be initialized for all possible execution paths. Are you sure parseParams handles undefined variables?
Loading history...
8231
        firstRestricted = tmp.firstRestricted;
8232
        if (tmp.message) {
8233
            message = tmp.message;
8234
        }
8235
8236
        previousStrict = strict;
0 ignored issues
show
Bug introduced by
The variable strict seems to not be initialized for all possible execution paths.
Loading history...
8237
        previousYieldAllowed = state.yieldAllowed;
8238
        state.yieldAllowed = generator;
8239
        previousAwaitAllowed = state.awaitAllowed;
8240
        state.awaitAllowed = isAsync;
8241
8242
        body = parseFunctionSourceElements();
8243
8244
        if (strict && firstRestricted) {
8245
            throwError(firstRestricted, message);
0 ignored issues
show
Bug introduced by
The variable message seems to not be initialized for all possible execution paths. Are you sure throwError handles undefined variables?
Loading history...
8246
        }
8247
        if (strict && tmp.stricted) {
8248
            throwErrorTolerant(tmp.stricted, message);
8249
        }
8250
        strict = previousStrict;
8251
        state.yieldAllowed = previousYieldAllowed;
8252
        state.awaitAllowed = previousAwaitAllowed;
8253
8254
        return markerApply(
8255
            marker,
8256
            delegate.createFunctionDeclaration(
8257
                id,
8258
                tmp.params,
8259
                tmp.defaults,
8260
                body,
8261
                tmp.rest,
8262
                generator,
8263
                false,
8264
                isAsync,
8265
                tmp.returnType,
8266
                typeParameters
0 ignored issues
show
Bug introduced by
The variable typeParameters does not seem to be initialized in case match("<") on line 8212 is false. Are you sure the function createFunctionDeclaration handles undefined variables?
Loading history...
8267
            )
8268
        );
8269
    }
8270
8271
    function parseFunctionExpression() {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
8272
        var token, id = null, firstRestricted, message, tmp, body, generator, isAsync,
8273
            previousStrict, previousYieldAllowed, previousAwaitAllowed,
8274
            marker = markerCreate(), typeParameters;
8275
8276
        isAsync = false;
8277
        if (matchAsync()) {
8278
            lex();
8279
            isAsync = true;
8280
        }
8281
8282
        expectKeyword('function');
8283
8284
        generator = false;
8285
8286
        if (match('*')) {
8287
            lex();
8288
            generator = true;
8289
        }
8290
8291
        if (!match('(')) {
8292
            if (!match('<')) {
8293
                token = lookahead;
8294
                id = parseVariableIdentifier();
8295
8296
                if (strict) {
8297
                    if (isRestrictedWord(token.value)) {
8298
                        throwErrorTolerant(token, Messages.StrictFunctionName);
8299
                    }
8300
                } else {
8301
                    if (isRestrictedWord(token.value)) {
8302
                        firstRestricted = token;
8303
                        message = Messages.StrictFunctionName;
8304
                    } else if (isStrictModeReservedWord(token.value)) {
8305
                        firstRestricted = token;
8306
                        message = Messages.StrictReservedWord;
8307
                    }
8308
                }
8309
            }
8310
8311
            if (match('<')) {
8312
                typeParameters = parseTypeParameterDeclaration();
8313
            }
8314
        }
8315
8316
        tmp = parseParams(firstRestricted);
0 ignored issues
show
Bug introduced by
The variable firstRestricted seems to not be initialized for all possible execution paths. Are you sure parseParams handles undefined variables?
Loading history...
8317
        firstRestricted = tmp.firstRestricted;
8318
        if (tmp.message) {
8319
            message = tmp.message;
8320
        }
8321
8322
        previousStrict = strict;
0 ignored issues
show
Bug introduced by
The variable strict seems to not be initialized for all possible execution paths.
Loading history...
8323
        previousYieldAllowed = state.yieldAllowed;
8324
        state.yieldAllowed = generator;
8325
        previousAwaitAllowed = state.awaitAllowed;
8326
        state.awaitAllowed = isAsync;
8327
8328
        body = parseFunctionSourceElements();
8329
8330
        if (strict && firstRestricted) {
8331
            throwError(firstRestricted, message);
0 ignored issues
show
Bug introduced by
The variable message seems to not be initialized for all possible execution paths. Are you sure throwError handles undefined variables?
Loading history...
8332
        }
8333
        if (strict && tmp.stricted) {
8334
            throwErrorTolerant(tmp.stricted, message);
8335
        }
8336
        strict = previousStrict;
8337
        state.yieldAllowed = previousYieldAllowed;
8338
        state.awaitAllowed = previousAwaitAllowed;
8339
8340
        return markerApply(
8341
            marker,
8342
            delegate.createFunctionExpression(
8343
                id,
8344
                tmp.params,
8345
                tmp.defaults,
8346
                body,
8347
                tmp.rest,
8348
                generator,
8349
                false,
8350
                isAsync,
8351
                tmp.returnType,
8352
                typeParameters
0 ignored issues
show
Bug introduced by
The variable typeParameters seems to not be initialized for all possible execution paths. Are you sure createFunctionExpression handles undefined variables?
Loading history...
8353
            )
8354
        );
8355
    }
8356
8357
    function parseYieldExpression() {
8358
        var delegateFlag, expr, marker = markerCreate();
8359
8360
        expectKeyword('yield', !strict);
8361
8362
        delegateFlag = false;
8363
        if (match('*')) {
8364
            lex();
8365
            delegateFlag = true;
8366
        }
8367
8368
        expr = parseAssignmentExpression();
8369
8370
        return markerApply(marker, delegate.createYieldExpression(expr, delegateFlag));
8371
    }
8372
8373
    function parseAwaitExpression() {
8374
        var expr, marker = markerCreate();
8375
        expectContextualKeyword('await');
8376
        expr = parseAssignmentExpression();
8377
        return markerApply(marker, delegate.createAwaitExpression(expr));
8378
    }
8379
8380
    // 14 Functions and classes
8381
8382
    // 14.1 Functions is defined above (13 in ES5)
8383
    // 14.2 Arrow Functions Definitions is defined in (7.3 assignments)
8384
8385
    // 14.3 Method Definitions
8386
    // 14.3.7
8387
    function specialMethod(methodDefinition) {
8388
        return methodDefinition.kind === 'get' ||
8389
               methodDefinition.kind === 'set' ||
8390
               methodDefinition.value.generator;
8391
    }
8392
8393
    function parseMethodDefinition(key, isStatic, generator, computed) {
8394
        var token, param, propType,
8395
            isAsync, typeParameters, tokenValue, returnType;
8396
8397
        propType = isStatic ? ClassPropertyType["static"] : ClassPropertyType.prototype;
8398
8399
        if (generator) {
8400
            return delegate.createMethodDefinition(
8401
                propType,
8402
                '',
8403
                key,
8404
                parsePropertyMethodFunction({ generator: true }),
8405
                computed
8406
            );
8407
        }
8408
8409
        tokenValue = key.type === 'Identifier' && key.name;
8410
8411
        if (tokenValue === 'get' && !match('(')) {
8412
            key = parseObjectPropertyKey();
8413
8414
            expect('(');
8415
            expect(')');
8416
            if (match(':')) {
8417
                returnType = parseTypeAnnotation();
8418
            }
8419
            return delegate.createMethodDefinition(
8420
                propType,
8421
                'get',
8422
                key,
8423
                parsePropertyFunction({ generator: false, returnType: returnType }),
0 ignored issues
show
Bug introduced by
The variable returnType does not seem to be initialized in case match(":") on line 8416 is false. Are you sure this can never be the case?
Loading history...
8424
                computed
8425
            );
8426
        }
8427
        if (tokenValue === 'set' && !match('(')) {
8428
            key = parseObjectPropertyKey();
8429
8430
            expect('(');
8431
            token = lookahead;
8432
            param = [ parseTypeAnnotatableIdentifier() ];
8433
            expect(')');
8434
            if (match(':')) {
8435
                returnType = parseTypeAnnotation();
8436
            }
8437
            return delegate.createMethodDefinition(
8438
                propType,
8439
                'set',
8440
                key,
8441
                parsePropertyFunction({
8442
                    params: param,
8443
                    generator: false,
8444
                    name: token,
8445
                    returnType: returnType
8446
                }),
8447
                computed
8448
            );
8449
        }
8450
8451
        if (match('<')) {
8452
            typeParameters = parseTypeParameterDeclaration();
8453
        }
8454
8455
        isAsync = tokenValue === 'async' && !match('(');
8456
        if (isAsync) {
8457
            key = parseObjectPropertyKey();
8458
        }
8459
8460
        return delegate.createMethodDefinition(
8461
            propType,
8462
            '',
8463
            key,
8464
            parsePropertyMethodFunction({
8465
                generator: false,
8466
                async: isAsync,
8467
                typeParameters: typeParameters
0 ignored issues
show
Bug introduced by
The variable typeParameters does not seem to be initialized in case match("<") on line 8451 is false. Are you sure this can never be the case?
Loading history...
8468
            }),
8469
            computed
8470
        );
8471
    }
8472
8473
    function parseClassProperty(key, computed, isStatic) {
8474
        var typeAnnotation;
8475
8476
        typeAnnotation = parseTypeAnnotation();
8477
        expect(';');
8478
8479
        return delegate.createClassProperty(
8480
            key,
8481
            typeAnnotation,
8482
            computed,
8483
            isStatic
8484
        );
8485
    }
8486
8487
    function parseClassElement() {
8488
        var computed = false, generator = false, key, marker = markerCreate(),
8489
            isStatic = false, possiblyOpenBracketToken;
8490
        if (match(';')) {
8491
            lex();
8492
            return undefined;
8493
        }
8494
8495
        if (lookahead.value === 'static') {
8496
            lex();
8497
            isStatic = true;
8498
        }
8499
8500
        if (match('*')) {
8501
            lex();
8502
            generator = true;
8503
        }
8504
8505
        possiblyOpenBracketToken = lookahead;
8506
        if (matchContextualKeyword('get') || matchContextualKeyword('set')) {
8507
            possiblyOpenBracketToken = lookahead2();
8508
        }
8509
8510
        if (possiblyOpenBracketToken.type === Token.Punctuator
8511
                && possiblyOpenBracketToken.value === '[') {
8512
            computed = true;
8513
        }
8514
8515
        key = parseObjectPropertyKey();
8516
8517
        if (!generator && lookahead.value === ':') {
8518
            return markerApply(marker, parseClassProperty(key, computed, isStatic));
8519
        }
8520
8521
        return markerApply(marker, parseMethodDefinition(
8522
            key,
8523
            isStatic,
8524
            generator,
8525
            computed
8526
        ));
8527
    }
8528
8529
    function parseClassBody() {
8530
        var classElement, classElements = [], existingProps = {},
8531
            marker = markerCreate(), propName, propType;
8532
8533
        existingProps[ClassPropertyType["static"]] = new StringMap();
8534
        existingProps[ClassPropertyType.prototype] = new StringMap();
8535
8536
        expect('{');
8537
8538
        while (index < length) {
8539
            if (match('}')) {
8540
                break;
8541
            }
8542
            classElement = parseClassElement(existingProps);
0 ignored issues
show
Bug introduced by
The call to parseClassElement seems to have too many arguments starting with existingProps.
Loading history...
8543
8544
            if (typeof classElement !== 'undefined') {
8545
                classElements.push(classElement);
8546
8547
                propName = !classElement.computed && getFieldName(classElement.key);
8548
                if (propName !== false) {
8549
                    propType = classElement["static"] ?
8550
                                ClassPropertyType["static"] :
8551
                                ClassPropertyType.prototype;
8552
8553
                    if (classElement.type === Syntax.MethodDefinition) {
8554
                        if (propName === 'constructor' && !classElement["static"]) {
8555
                            if (specialMethod(classElement)) {
8556
                                throwError(classElement, Messages.IllegalClassConstructorProperty);
8557
                            }
8558
                            if (existingProps[ClassPropertyType.prototype].has('constructor')) {
8559
                                throwError(classElement.key, Messages.IllegalDuplicateClassProperty);
8560
                            }
8561
                        }
8562
                        existingProps[propType].set(propName, true);
8563
                    }
8564
                }
8565
            }
8566
        }
8567
8568
        expect('}');
8569
8570
        return markerApply(marker, delegate.createClassBody(classElements));
8571
    }
8572
8573
    function parseClassImplements() {
8574
        var id, implemented = [], marker, typeParameters;
8575
        if (strict) {
8576
            expectKeyword('implements');
8577
        } else {
8578
            expectContextualKeyword('implements');
8579
        }
8580
        while (index < length) {
8581
            marker = markerCreate();
8582
            id = parseVariableIdentifier();
8583
            if (match('<')) {
8584
                typeParameters = parseTypeParameterInstantiation();
8585
            } else {
8586
                typeParameters = null;
8587
            }
8588
            implemented.push(markerApply(marker, delegate.createClassImplements(
8589
                id,
8590
                typeParameters
8591
            )));
8592
            if (!match(',')) {
8593
                break;
8594
            }
8595
            expect(',');
8596
        }
8597
        return implemented;
8598
    }
8599
8600
    function parseClassExpression() {
8601
        var id, implemented, previousYieldAllowed, superClass = null,
8602
            superTypeParameters, marker = markerCreate(), typeParameters,
8603
            matchImplements;
8604
8605
        expectKeyword('class');
8606
8607
        matchImplements =
8608
                strict
8609
                ? matchKeyword('implements')
8610
                : matchContextualKeyword('implements');
8611
8612
        if (!matchKeyword('extends') && !matchImplements && !match('{')) {
8613
            id = parseVariableIdentifier();
8614
        }
8615
8616
        if (match('<')) {
8617
            typeParameters = parseTypeParameterDeclaration();
8618
        }
8619
8620
        if (matchKeyword('extends')) {
8621
            expectKeyword('extends');
8622
            previousYieldAllowed = state.yieldAllowed;
8623
            state.yieldAllowed = false;
8624
            superClass = parseLeftHandSideExpressionAllowCall();
8625
            if (match('<')) {
8626
                superTypeParameters = parseTypeParameterInstantiation();
8627
            }
8628
            state.yieldAllowed = previousYieldAllowed;
8629
        }
8630
8631
        if (strict ? matchKeyword('implements') : matchContextualKeyword('implements')) {
8632
            implemented = parseClassImplements();
8633
        }
8634
8635
        return markerApply(marker, delegate.createClassExpression(
8636
            id,
0 ignored issues
show
Bug introduced by
The variable id does not seem to be initialized in case !matchKeyword("extends")...plements && !match("{") on line 8612 is false. Are you sure the function createClassExpression handles undefined variables?
Loading history...
8637
            superClass,
8638
            parseClassBody(),
8639
            typeParameters,
0 ignored issues
show
Bug introduced by
The variable typeParameters does not seem to be initialized in case match("<") on line 8616 is false. Are you sure the function createClassExpression handles undefined variables?
Loading history...
8640
            superTypeParameters,
0 ignored issues
show
Bug introduced by
The variable superTypeParameters seems to not be initialized for all possible execution paths. Are you sure createClassExpression handles undefined variables?
Loading history...
8641
            implemented
0 ignored issues
show
Bug introduced by
The variable implemented does not seem to be initialized in case strict ? matchKeyword("i...alKeyword("implements") on line 8631 is false. Are you sure the function createClassExpression handles undefined variables?
Loading history...
8642
        ));
8643
    }
8644
8645
    function parseClassDeclaration() {
8646
        var id, implemented, previousYieldAllowed, superClass = null,
8647
            superTypeParameters, marker = markerCreate(), typeParameters;
8648
8649
        expectKeyword('class');
8650
8651
        id = parseVariableIdentifier();
8652
8653
        if (match('<')) {
8654
            typeParameters = parseTypeParameterDeclaration();
8655
        }
8656
8657
        if (matchKeyword('extends')) {
8658
            expectKeyword('extends');
8659
            previousYieldAllowed = state.yieldAllowed;
8660
            state.yieldAllowed = false;
8661
            superClass = parseLeftHandSideExpressionAllowCall();
8662
            if (match('<')) {
8663
                superTypeParameters = parseTypeParameterInstantiation();
8664
            }
8665
            state.yieldAllowed = previousYieldAllowed;
8666
        }
8667
8668
        if (strict ? matchKeyword('implements') : matchContextualKeyword('implements')) {
8669
            implemented = parseClassImplements();
8670
        }
8671
8672
        return markerApply(marker, delegate.createClassDeclaration(
8673
            id,
8674
            superClass,
8675
            parseClassBody(),
8676
            typeParameters,
0 ignored issues
show
Bug introduced by
The variable typeParameters does not seem to be initialized in case match("<") on line 8653 is false. Are you sure the function createClassDeclaration handles undefined variables?
Loading history...
8677
            superTypeParameters,
0 ignored issues
show
Bug introduced by
The variable superTypeParameters seems to not be initialized for all possible execution paths. Are you sure createClassDeclaration handles undefined variables?
Loading history...
8678
            implemented
0 ignored issues
show
Bug introduced by
The variable implemented does not seem to be initialized in case strict ? matchKeyword("i...alKeyword("implements") on line 8668 is false. Are you sure the function createClassDeclaration handles undefined variables?
Loading history...
8679
        ));
8680
    }
8681
8682
    // 15 Program
8683
8684
    function parseSourceElement() {
8685
        var token;
8686
        if (lookahead.type === Token.Keyword) {
8687
            switch (lookahead.value) {
8688
            case 'const':
8689
            case 'let':
8690
                return parseConstLetDeclaration(lookahead.value);
8691
            case 'function':
8692
                return parseFunctionDeclaration();
8693
            case 'export':
8694
                throwErrorTolerant({}, Messages.IllegalExportDeclaration);
8695
                return parseExportDeclaration();
8696
            case 'import':
8697
                throwErrorTolerant({}, Messages.IllegalImportDeclaration);
8698
                return parseImportDeclaration();
8699
            case 'interface':
8700
                if (lookahead2().type === Token.Identifier) {
8701
                    return parseInterface();
8702
                }
8703
                return parseStatement();
8704
            default:
8705
                return parseStatement();
8706
            }
8707
        }
8708
8709
        if (matchContextualKeyword('type')
8710
                && lookahead2().type === Token.Identifier) {
8711
            return parseTypeAlias();
8712
        }
8713
8714
        if (matchContextualKeyword('interface')
8715
                && lookahead2().type === Token.Identifier) {
8716
            return parseInterface();
8717
        }
8718
8719
        if (matchContextualKeyword('declare')) {
8720
            token = lookahead2();
8721
            if (token.type === Token.Keyword) {
8722
                switch (token.value) {
0 ignored issues
show
Coding Style introduced by
As per coding-style, switch statements should have a default case.
Loading history...
8723
                case 'class':
8724
                    return parseDeclareClass();
8725
                case 'function':
8726
                    return parseDeclareFunction();
8727
                case 'var':
8728
                    return parseDeclareVariable();
8729
                }
8730
            } else if (token.type === Token.Identifier
8731
                    && token.value === 'module') {
8732
                return parseDeclareModule();
8733
            }
8734
        }
8735
8736
        if (lookahead.type !== Token.EOF) {
0 ignored issues
show
Complexity Best Practice introduced by
There is no return statement if lookahead.type !== Token.EOF is false. Are you sure this is correct? If so, consider adding return; explicitly.

This check looks for functions where a return statement is found in some execution paths, but not in all.

Consider this little piece of code

function isBig(a) {
    if (a > 5000) {
        return "yes";
    }
}

console.log(isBig(5001)); //returns yes
console.log(isBig(42)); //returns undefined

The function isBig will only return a specific value when its parameter is bigger than 5000. In any other case, it will implicitly return undefined.

This behaviour may not be what you had intended. In any case, you can add a return undefined to the other execution path to make the return value explicit.

Loading history...
8737
            return parseStatement();
8738
        }
8739
    }
8740
8741
    function parseProgramElement() {
8742
        var isModule = extra.sourceType === 'module' || extra.sourceType === 'nonStrictModule';
8743
8744
        if (isModule && lookahead.type === Token.Keyword) {
8745
            switch (lookahead.value) {
0 ignored issues
show
Coding Style introduced by
As per coding-style, switch statements should have a default case.
Loading history...
8746
            case 'export':
8747
                return parseExportDeclaration();
8748
            case 'import':
8749
                return parseImportDeclaration();
8750
            }
8751
        }
8752
8753
        return parseSourceElement();
8754
    }
8755
8756
    function parseProgramElements() {
8757
        var sourceElement, sourceElements = [], token, directive, firstRestricted;
8758
8759
        while (index < length) {
8760
            token = lookahead;
8761
            if (token.type !== Token.StringLiteral) {
8762
                break;
8763
            }
8764
8765
            sourceElement = parseProgramElement();
8766
            sourceElements.push(sourceElement);
8767
            if (sourceElement.expression.type !== Syntax.Literal) {
8768
                // this is not directive
8769
                break;
8770
            }
8771
            directive = source.slice(token.range[0] + 1, token.range[1] - 1);
8772
            if (directive === 'use ' + 'strict') {
8773
                strict = true;
8774
                if (firstRestricted) {
8775
                    throwErrorTolerant(firstRestricted, Messages.StrictOctalLiteral);
8776
                }
8777
            } else {
8778
                if (!firstRestricted && token.octal) {
8779
                    firstRestricted = token;
8780
                }
8781
            }
8782
        }
8783
8784
        while (index < length) {
8785
            sourceElement = parseProgramElement();
8786
            if (typeof sourceElement === 'undefined') {
8787
                break;
8788
            }
8789
            sourceElements.push(sourceElement);
8790
        }
8791
        return sourceElements;
8792
    }
8793
8794
    function parseProgram() {
8795
        var body, marker = markerCreate();
8796
        strict = extra.sourceType === 'module';
8797
        peek();
8798
        body = parseProgramElements();
8799
        return markerApply(marker, delegate.createProgram(body));
8800
    }
8801
8802
    // 16 JSX
8803
8804
    XHTMLEntities = {
8805
        quot: '\u0022',
8806
        amp: '&',
8807
        apos: '\u0027',
8808
        lt: '<',
8809
        gt: '>',
8810
        nbsp: '\u00A0',
8811
        iexcl: '\u00A1',
8812
        cent: '\u00A2',
8813
        pound: '\u00A3',
8814
        curren: '\u00A4',
8815
        yen: '\u00A5',
8816
        brvbar: '\u00A6',
8817
        sect: '\u00A7',
8818
        uml: '\u00A8',
8819
        copy: '\u00A9',
8820
        ordf: '\u00AA',
8821
        laquo: '\u00AB',
8822
        not: '\u00AC',
8823
        shy: '\u00AD',
8824
        reg: '\u00AE',
8825
        macr: '\u00AF',
8826
        deg: '\u00B0',
8827
        plusmn: '\u00B1',
8828
        sup2: '\u00B2',
8829
        sup3: '\u00B3',
8830
        acute: '\u00B4',
8831
        micro: '\u00B5',
8832
        para: '\u00B6',
8833
        middot: '\u00B7',
8834
        cedil: '\u00B8',
8835
        sup1: '\u00B9',
8836
        ordm: '\u00BA',
8837
        raquo: '\u00BB',
8838
        frac14: '\u00BC',
8839
        frac12: '\u00BD',
8840
        frac34: '\u00BE',
8841
        iquest: '\u00BF',
8842
        Agrave: '\u00C0',
8843
        Aacute: '\u00C1',
8844
        Acirc: '\u00C2',
8845
        Atilde: '\u00C3',
8846
        Auml: '\u00C4',
8847
        Aring: '\u00C5',
8848
        AElig: '\u00C6',
8849
        Ccedil: '\u00C7',
8850
        Egrave: '\u00C8',
8851
        Eacute: '\u00C9',
8852
        Ecirc: '\u00CA',
8853
        Euml: '\u00CB',
8854
        Igrave: '\u00CC',
8855
        Iacute: '\u00CD',
8856
        Icirc: '\u00CE',
8857
        Iuml: '\u00CF',
8858
        ETH: '\u00D0',
8859
        Ntilde: '\u00D1',
8860
        Ograve: '\u00D2',
8861
        Oacute: '\u00D3',
8862
        Ocirc: '\u00D4',
8863
        Otilde: '\u00D5',
8864
        Ouml: '\u00D6',
8865
        times: '\u00D7',
8866
        Oslash: '\u00D8',
8867
        Ugrave: '\u00D9',
8868
        Uacute: '\u00DA',
8869
        Ucirc: '\u00DB',
8870
        Uuml: '\u00DC',
8871
        Yacute: '\u00DD',
8872
        THORN: '\u00DE',
8873
        szlig: '\u00DF',
8874
        agrave: '\u00E0',
8875
        aacute: '\u00E1',
8876
        acirc: '\u00E2',
8877
        atilde: '\u00E3',
8878
        auml: '\u00E4',
8879
        aring: '\u00E5',
8880
        aelig: '\u00E6',
8881
        ccedil: '\u00E7',
8882
        egrave: '\u00E8',
8883
        eacute: '\u00E9',
8884
        ecirc: '\u00EA',
8885
        euml: '\u00EB',
8886
        igrave: '\u00EC',
8887
        iacute: '\u00ED',
8888
        icirc: '\u00EE',
8889
        iuml: '\u00EF',
8890
        eth: '\u00F0',
8891
        ntilde: '\u00F1',
8892
        ograve: '\u00F2',
8893
        oacute: '\u00F3',
8894
        ocirc: '\u00F4',
8895
        otilde: '\u00F5',
8896
        ouml: '\u00F6',
8897
        divide: '\u00F7',
8898
        oslash: '\u00F8',
8899
        ugrave: '\u00F9',
8900
        uacute: '\u00FA',
8901
        ucirc: '\u00FB',
8902
        uuml: '\u00FC',
8903
        yacute: '\u00FD',
8904
        thorn: '\u00FE',
8905
        yuml: '\u00FF',
8906
        OElig: '\u0152',
8907
        oelig: '\u0153',
8908
        Scaron: '\u0160',
8909
        scaron: '\u0161',
8910
        Yuml: '\u0178',
8911
        fnof: '\u0192',
8912
        circ: '\u02C6',
8913
        tilde: '\u02DC',
8914
        Alpha: '\u0391',
8915
        Beta: '\u0392',
8916
        Gamma: '\u0393',
8917
        Delta: '\u0394',
8918
        Epsilon: '\u0395',
8919
        Zeta: '\u0396',
8920
        Eta: '\u0397',
8921
        Theta: '\u0398',
8922
        Iota: '\u0399',
8923
        Kappa: '\u039A',
8924
        Lambda: '\u039B',
8925
        Mu: '\u039C',
8926
        Nu: '\u039D',
8927
        Xi: '\u039E',
8928
        Omicron: '\u039F',
8929
        Pi: '\u03A0',
8930
        Rho: '\u03A1',
8931
        Sigma: '\u03A3',
8932
        Tau: '\u03A4',
8933
        Upsilon: '\u03A5',
8934
        Phi: '\u03A6',
8935
        Chi: '\u03A7',
8936
        Psi: '\u03A8',
8937
        Omega: '\u03A9',
8938
        alpha: '\u03B1',
8939
        beta: '\u03B2',
8940
        gamma: '\u03B3',
8941
        delta: '\u03B4',
8942
        epsilon: '\u03B5',
8943
        zeta: '\u03B6',
8944
        eta: '\u03B7',
8945
        theta: '\u03B8',
8946
        iota: '\u03B9',
8947
        kappa: '\u03BA',
8948
        lambda: '\u03BB',
8949
        mu: '\u03BC',
8950
        nu: '\u03BD',
8951
        xi: '\u03BE',
8952
        omicron: '\u03BF',
8953
        pi: '\u03C0',
8954
        rho: '\u03C1',
8955
        sigmaf: '\u03C2',
8956
        sigma: '\u03C3',
8957
        tau: '\u03C4',
8958
        upsilon: '\u03C5',
8959
        phi: '\u03C6',
8960
        chi: '\u03C7',
8961
        psi: '\u03C8',
8962
        omega: '\u03C9',
8963
        thetasym: '\u03D1',
8964
        upsih: '\u03D2',
8965
        piv: '\u03D6',
8966
        ensp: '\u2002',
8967
        emsp: '\u2003',
8968
        thinsp: '\u2009',
8969
        zwnj: '\u200C',
8970
        zwj: '\u200D',
8971
        lrm: '\u200E',
8972
        rlm: '\u200F',
8973
        ndash: '\u2013',
8974
        mdash: '\u2014',
8975
        lsquo: '\u2018',
8976
        rsquo: '\u2019',
8977
        sbquo: '\u201A',
8978
        ldquo: '\u201C',
8979
        rdquo: '\u201D',
8980
        bdquo: '\u201E',
8981
        dagger: '\u2020',
8982
        Dagger: '\u2021',
8983
        bull: '\u2022',
8984
        hellip: '\u2026',
8985
        permil: '\u2030',
8986
        prime: '\u2032',
8987
        Prime: '\u2033',
8988
        lsaquo: '\u2039',
8989
        rsaquo: '\u203A',
8990
        oline: '\u203E',
8991
        frasl: '\u2044',
8992
        euro: '\u20AC',
8993
        image: '\u2111',
8994
        weierp: '\u2118',
8995
        real: '\u211C',
8996
        trade: '\u2122',
8997
        alefsym: '\u2135',
8998
        larr: '\u2190',
8999
        uarr: '\u2191',
9000
        rarr: '\u2192',
9001
        darr: '\u2193',
9002
        harr: '\u2194',
9003
        crarr: '\u21B5',
9004
        lArr: '\u21D0',
9005
        uArr: '\u21D1',
9006
        rArr: '\u21D2',
9007
        dArr: '\u21D3',
9008
        hArr: '\u21D4',
9009
        forall: '\u2200',
9010
        part: '\u2202',
9011
        exist: '\u2203',
9012
        empty: '\u2205',
9013
        nabla: '\u2207',
9014
        isin: '\u2208',
9015
        notin: '\u2209',
9016
        ni: '\u220B',
9017
        prod: '\u220F',
9018
        sum: '\u2211',
9019
        minus: '\u2212',
9020
        lowast: '\u2217',
9021
        radic: '\u221A',
9022
        prop: '\u221D',
9023
        infin: '\u221E',
9024
        ang: '\u2220',
9025
        and: '\u2227',
9026
        or: '\u2228',
9027
        cap: '\u2229',
9028
        cup: '\u222A',
9029
        'int': '\u222B',
9030
        there4: '\u2234',
9031
        sim: '\u223C',
9032
        cong: '\u2245',
9033
        asymp: '\u2248',
9034
        ne: '\u2260',
9035
        equiv: '\u2261',
9036
        le: '\u2264',
9037
        ge: '\u2265',
9038
        sub: '\u2282',
9039
        sup: '\u2283',
9040
        nsub: '\u2284',
9041
        sube: '\u2286',
9042
        supe: '\u2287',
9043
        oplus: '\u2295',
9044
        otimes: '\u2297',
9045
        perp: '\u22A5',
9046
        sdot: '\u22C5',
9047
        lceil: '\u2308',
9048
        rceil: '\u2309',
9049
        lfloor: '\u230A',
9050
        rfloor: '\u230B',
9051
        lang: '\u2329',
9052
        rang: '\u232A',
9053
        loz: '\u25CA',
9054
        spades: '\u2660',
9055
        clubs: '\u2663',
9056
        hearts: '\u2665',
9057
        diams: '\u2666'
9058
    };
9059
9060
    function getQualifiedJSXName(object) {
9061
        if (object.type === Syntax.JSXIdentifier) {
9062
            return object.name;
9063
        }
9064
        if (object.type === Syntax.JSXNamespacedName) {
9065
            return object.namespace.name + ':' + object.name.name;
9066
        }
9067
        /* istanbul ignore else */
9068
        if (object.type === Syntax.JSXMemberExpression) {
9069
            return (
9070
                getQualifiedJSXName(object.object) + '.' +
9071
                getQualifiedJSXName(object.property)
9072
            );
9073
        }
9074
        /* istanbul ignore next */
9075
        throwUnexpected(object);
0 ignored issues
show
Best Practice introduced by
There is no return statement in this branch, but you do return something in other branches. Did you maybe miss it? If you do not want to return anything, consider adding return undefined; explicitly.
Loading history...
9076
    }
9077
9078
    function isJSXIdentifierStart(ch) {
9079
        // exclude backslash (\)
9080
        return (ch !== 92) && isIdentifierStart(ch);
9081
    }
9082
9083
    function isJSXIdentifierPart(ch) {
9084
        // exclude backslash (\) and add hyphen (-)
9085
        return (ch !== 92) && (ch === 45 || isIdentifierPart(ch));
9086
    }
9087
9088
    function scanJSXIdentifier() {
9089
        var ch, start, value = '';
9090
9091
        start = index;
9092
        while (index < length) {
0 ignored issues
show
Comprehensibility Bug introduced by
The variable index does not seem to be initialized in case the while loop on line 9092 is not entered. Are you sure this can never be the case?
Loading history...
9093
            ch = source.charCodeAt(index);
9094
            if (!isJSXIdentifierPart(ch)) {
9095
                break;
9096
            }
9097
            value += source[index++];
9098
        }
9099
9100
        return {
9101
            type: Token.JSXIdentifier,
9102
            value: value,
9103
            lineNumber: lineNumber,
9104
            lineStart: lineStart,
9105
            range: [start, index]
9106
        };
9107
    }
9108
9109
    function scanJSXEntity() {
9110
        var ch, str = '', start = index, count = 0, code;
9111
        ch = source[index];
9112
        assert(ch === '&', 'Entity must start with an ampersand');
9113
        index++;
9114
        while (index < length && count++ < 10) {
0 ignored issues
show
Bug introduced by
The variable index is changed as part of the while loop for example by index++ on line 9115. Only the value of the last iteration will be visible in this function if it is called after the loop.
Loading history...
9115
            ch = source[index++];
9116
            if (ch === ';') {
9117
                break;
9118
            }
9119
            str += ch;
9120
        }
9121
9122
        // Well-formed entity (ending was found).
9123
        if (ch === ';') {
9124
            // Numeric entity.
9125
            if (str[0] === '#') {
9126
                if (str[1] === 'x') {
9127
                    code = +('0' + str.substr(1));
9128
                } else {
9129
                    // Removing leading zeros in order to avoid treating as octal in old browsers.
9130
                    code = +str.substr(1).replace(Regex.LeadingZeros, '');
9131
                }
9132
9133
                if (!isNaN(code)) {
9134
                    return String.fromCharCode(code);
9135
                }
9136
            /* istanbul ignore else */
9137
            } else if (XHTMLEntities[str]) {
9138
                return XHTMLEntities[str];
9139
            }
9140
        }
9141
9142
        // Treat non-entity sequences as regular text.
9143
        index = start + 1;
9144
        return '&';
9145
    }
9146
9147
    function scanJSXText(stopChars) {
9148
        var ch, str = '', start;
9149
        start = index;
9150
        while (index < length) {
0 ignored issues
show
Comprehensibility Bug introduced by
The variable index does not seem to be initialized in case the while loop on line 9150 is not entered. Are you sure this can never be the case?
Loading history...
9151
            ch = source[index];
9152
            if (stopChars.indexOf(ch) !== -1) {
9153
                break;
9154
            }
9155
            if (ch === '&') {
9156
                str += scanJSXEntity();
9157
            } else {
9158
                index++;
9159
                if (ch === '\r' && source[index] === '\n') {
0 ignored issues
show
Bug introduced by
The variable index is changed as part of the while loop for example by index++ on line 9158. Only the value of the last iteration will be visible in this function if it is called after the loop.
Loading history...
9160
                    str += ch;
9161
                    ch = source[index];
9162
                    index++;
9163
                }
9164
                if (isLineTerminator(ch.charCodeAt(0))) {
9165
                    ++lineNumber;
0 ignored issues
show
Bug introduced by
The variable lineNumber seems to not be initialized for all possible execution paths.
Loading history...
9166
                    lineStart = index;
9167
                }
9168
                str += ch;
9169
            }
9170
        }
9171
        return {
9172
            type: Token.JSXText,
9173
            value: str,
9174
            lineNumber: lineNumber,
9175
            lineStart: lineStart,
0 ignored issues
show
Bug introduced by
The variable lineStart seems to not be initialized for all possible execution paths.
Loading history...
9176
            range: [start, index]
9177
        };
9178
    }
9179
9180
    function scanJSXStringLiteral() {
9181
        var innerToken, quote, start;
9182
9183
        quote = source[index];
9184
        assert((quote === '\'' || quote === '"'),
9185
            'String literal must starts with a quote');
9186
9187
        start = index;
9188
        ++index;
9189
9190
        innerToken = scanJSXText([quote]);
9191
9192
        if (quote !== source[index]) {
9193
            throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
9194
        }
9195
9196
        ++index;
9197
9198
        innerToken.range = [start, index];
9199
9200
        return innerToken;
9201
    }
9202
9203
    /**
9204
     * Between JSX opening and closing tags (e.g. <foo>HERE</foo>), anything that
9205
     * is not another JSX tag and is not an expression wrapped by {} is text.
9206
     */
9207
    function advanceJSXChild() {
9208
        var ch = source.charCodeAt(index);
9209
9210
        // '<' 60, '>' 62, '{' 123, '}' 125
9211
        if (ch !== 60 && ch !== 62 && ch !== 123 && ch !== 125) {
9212
            return scanJSXText(['<', '>', '{', '}']);
9213
        }
9214
9215
        return scanPunctuator();
9216
    }
9217
9218
    function parseJSXIdentifier() {
9219
        var token, marker = markerCreate();
9220
9221
        if (lookahead.type !== Token.JSXIdentifier) {
9222
            throwUnexpected(lookahead);
9223
        }
9224
9225
        token = lex();
9226
        return markerApply(marker, delegate.createJSXIdentifier(token.value));
9227
    }
9228
9229
    function parseJSXNamespacedName() {
9230
        var namespace, name, marker = markerCreate();
9231
9232
        namespace = parseJSXIdentifier();
9233
        expect(':');
9234
        name = parseJSXIdentifier();
9235
9236
        return markerApply(marker, delegate.createJSXNamespacedName(namespace, name));
9237
    }
9238
9239
    function parseJSXMemberExpression() {
9240
        var marker = markerCreate(),
9241
            expr = parseJSXIdentifier();
9242
9243
        while (match('.')) {
9244
            lex();
9245
            expr = markerApply(marker, delegate.createJSXMemberExpression(expr, parseJSXIdentifier()));
9246
        }
9247
9248
        return expr;
9249
    }
9250
9251
    function parseJSXElementName() {
9252
        if (lookahead2().value === ':') {
9253
            return parseJSXNamespacedName();
9254
        }
9255
        if (lookahead2().value === '.') {
9256
            return parseJSXMemberExpression();
9257
        }
9258
9259
        return parseJSXIdentifier();
9260
    }
9261
9262
    function parseJSXAttributeName() {
9263
        if (lookahead2().value === ':') {
9264
            return parseJSXNamespacedName();
9265
        }
9266
9267
        return parseJSXIdentifier();
9268
    }
9269
9270
    function parseJSXAttributeValue() {
9271
        var value, marker;
9272
        if (match('{')) {
9273
            value = parseJSXExpressionContainer();
9274
            if (value.expression.type === Syntax.JSXEmptyExpression) {
9275
                throwError(
9276
                    value,
9277
                    'JSX attributes must only be assigned a non-empty ' +
9278
                        'expression'
9279
                );
9280
            }
9281
        } else if (match('<')) {
9282
            value = parseJSXElement();
9283
        } else if (lookahead.type === Token.JSXText) {
9284
            marker = markerCreate();
9285
            value = markerApply(marker, delegate.createLiteral(lex()));
9286
        } else {
9287
            throwError({}, Messages.InvalidJSXAttributeValue);
9288
        }
9289
        return value;
0 ignored issues
show
Bug introduced by
The variable value seems to not be initialized for all possible execution paths.
Loading history...
9290
    }
9291
9292
    function parseJSXEmptyExpression() {
9293
        var marker = markerCreatePreserveWhitespace();
9294
        while (source.charAt(index) !== '}') {
0 ignored issues
show
introduced by
The variable index does not seem to be initialized in case the while loop on line 9294 is not entered. Are you sure the function charAt handles undefined variables?
Loading history...
9295
            index++;
9296
        }
9297
        return markerApply(marker, delegate.createJSXEmptyExpression());
9298
    }
9299
9300
    function parseJSXExpressionContainer() {
9301
        var expression, origInJSXChild, origInJSXTag, marker = markerCreate();
9302
9303
        origInJSXChild = state.inJSXChild;
9304
        origInJSXTag = state.inJSXTag;
9305
        state.inJSXChild = false;
9306
        state.inJSXTag = false;
9307
9308
        expect('{');
9309
9310
        if (match('}')) {
9311
            expression = parseJSXEmptyExpression();
9312
        } else {
9313
            expression = parseExpression();
9314
        }
9315
9316
        state.inJSXChild = origInJSXChild;
9317
        state.inJSXTag = origInJSXTag;
9318
9319
        expect('}');
9320
9321
        return markerApply(marker, delegate.createJSXExpressionContainer(expression));
9322
    }
9323
9324
    function parseJSXSpreadAttribute() {
9325
        var expression, origInJSXChild, origInJSXTag, marker = markerCreate();
9326
9327
        origInJSXChild = state.inJSXChild;
9328
        origInJSXTag = state.inJSXTag;
9329
        state.inJSXChild = false;
9330
        state.inJSXTag = false;
9331
9332
        expect('{');
9333
        expect('...');
9334
9335
        expression = parseAssignmentExpression();
9336
9337
        state.inJSXChild = origInJSXChild;
9338
        state.inJSXTag = origInJSXTag;
9339
9340
        expect('}');
9341
9342
        return markerApply(marker, delegate.createJSXSpreadAttribute(expression));
9343
    }
9344
9345
    function parseJSXAttribute() {
9346
        var name, marker;
9347
9348
        if (match('{')) {
9349
            return parseJSXSpreadAttribute();
9350
        }
9351
9352
        marker = markerCreate();
9353
9354
        name = parseJSXAttributeName();
9355
9356
        // HTML empty attribute
9357
        if (match('=')) {
9358
            lex();
9359
            return markerApply(marker, delegate.createJSXAttribute(name, parseJSXAttributeValue()));
9360
        }
9361
9362
        return markerApply(marker, delegate.createJSXAttribute(name));
9363
    }
9364
9365
    function parseJSXChild() {
9366
        var token, marker;
9367
        if (match('{')) {
9368
            token = parseJSXExpressionContainer();
9369
        } else if (lookahead.type === Token.JSXText) {
9370
            marker = markerCreatePreserveWhitespace();
9371
            token = markerApply(marker, delegate.createLiteral(lex()));
9372
        } else if (match('<')) {
9373
            token = parseJSXElement();
9374
        } else {
9375
            throwUnexpected(lookahead);
9376
        }
9377
        return token;
0 ignored issues
show
Bug introduced by
The variable token seems to not be initialized for all possible execution paths.
Loading history...
9378
    }
9379
9380
    function parseJSXClosingElement() {
9381
        var name, origInJSXChild, origInJSXTag, marker = markerCreate();
9382
        origInJSXChild = state.inJSXChild;
9383
        origInJSXTag = state.inJSXTag;
9384
        state.inJSXChild = false;
9385
        state.inJSXTag = true;
9386
        expect('<');
9387
        expect('/');
9388
        name = parseJSXElementName();
9389
        // Because advance() (called by lex() called by expect()) expects there
9390
        // to be a valid token after >, it needs to know whether to look for a
9391
        // standard JS token or an JSX text node
9392
        state.inJSXChild = origInJSXChild;
9393
        state.inJSXTag = origInJSXTag;
9394
        expect('>');
9395
        return markerApply(marker, delegate.createJSXClosingElement(name));
9396
    }
9397
9398
    function parseJSXOpeningElement() {
9399
        var name, attributes = [], selfClosing = false, origInJSXChild, origInJSXTag, marker = markerCreate();
9400
9401
        origInJSXChild = state.inJSXChild;
9402
        origInJSXTag = state.inJSXTag;
9403
        state.inJSXChild = false;
9404
        state.inJSXTag = true;
9405
9406
        expect('<');
9407
9408
        name = parseJSXElementName();
9409
9410
        while (index < length &&
9411
                lookahead.value !== '/' &&
9412
                lookahead.value !== '>') {
9413
            attributes.push(parseJSXAttribute());
9414
        }
9415
9416
        state.inJSXTag = origInJSXTag;
9417
9418
        if (lookahead.value === '/') {
9419
            expect('/');
9420
            // Because advance() (called by lex() called by expect()) expects
9421
            // there to be a valid token after >, it needs to know whether to
9422
            // look for a standard JS token or an JSX text node
9423
            state.inJSXChild = origInJSXChild;
9424
            expect('>');
9425
            selfClosing = true;
9426
        } else {
9427
            state.inJSXChild = true;
9428
            expect('>');
9429
        }
9430
        return markerApply(marker, delegate.createJSXOpeningElement(name, attributes, selfClosing));
9431
    }
9432
9433
    function parseJSXElement() {
9434
        var openingElement, closingElement = null, children = [], origInJSXChild, origInJSXTag, marker = markerCreate();
9435
9436
        origInJSXChild = state.inJSXChild;
9437
        origInJSXTag = state.inJSXTag;
9438
        openingElement = parseJSXOpeningElement();
9439
9440
        if (!openingElement.selfClosing) {
9441
            while (index < length) {
9442
                state.inJSXChild = false; // Call lookahead2() with inJSXChild = false because </ should not be considered in the child
9443
                if (lookahead.value === '<' && lookahead2().value === '/') {
9444
                    break;
9445
                }
9446
                state.inJSXChild = true;
9447
                children.push(parseJSXChild());
9448
            }
9449
            state.inJSXChild = origInJSXChild;
9450
            state.inJSXTag = origInJSXTag;
9451
            closingElement = parseJSXClosingElement();
9452
            if (getQualifiedJSXName(closingElement.name) !== getQualifiedJSXName(openingElement.name)) {
9453
                throwError({}, Messages.ExpectedJSXClosingTag, getQualifiedJSXName(openingElement.name));
9454
            }
9455
        }
9456
9457
        // When (erroneously) writing two adjacent tags like
9458
        //
9459
        //     var x = <div>one</div><div>two</div>;
9460
        //
9461
        // the default error message is a bit incomprehensible. Since it's
9462
        // rarely (never?) useful to write a less-than sign after an JSX
9463
        // element, we disallow it here in the parser in order to provide a
9464
        // better error message. (In the rare case that the less-than operator
9465
        // was intended, the left tag can be wrapped in parentheses.)
9466
        if (!origInJSXChild && match('<')) {
9467
            throwError(lookahead, Messages.AdjacentJSXElements);
9468
        }
9469
9470
        return markerApply(marker, delegate.createJSXElement(openingElement, closingElement, children));
9471
    }
9472
9473
    function parseTypeAlias() {
9474
        var id, marker = markerCreate(), typeParameters = null, right;
9475
        expectContextualKeyword('type');
9476
        id = parseVariableIdentifier();
9477
        if (match('<')) {
9478
            typeParameters = parseTypeParameterDeclaration();
9479
        }
9480
        expect('=');
9481
        right = parseType();
9482
        consumeSemicolon();
9483
        return markerApply(marker, delegate.createTypeAlias(id, typeParameters, right));
9484
    }
9485
9486
    function parseInterfaceExtends() {
9487
        var marker = markerCreate(), id, typeParameters = null;
9488
9489
        id = parseVariableIdentifier();
9490
        if (match('<')) {
9491
            typeParameters = parseTypeParameterInstantiation();
9492
        }
9493
9494
        return markerApply(marker, delegate.createInterfaceExtends(
9495
            id,
9496
            typeParameters
9497
        ));
9498
    }
9499
9500
    function parseInterfaceish(marker, allowStatic) {
9501
        var body, bodyMarker, extended = [], id,
9502
            typeParameters = null;
9503
9504
        id = parseVariableIdentifier();
9505
        if (match('<')) {
9506
            typeParameters = parseTypeParameterDeclaration();
9507
        }
9508
9509
        if (matchKeyword('extends')) {
9510
            expectKeyword('extends');
9511
9512
            while (index < length) {
9513
                extended.push(parseInterfaceExtends());
9514
                if (!match(',')) {
9515
                    break;
9516
                }
9517
                expect(',');
9518
            }
9519
        }
9520
9521
        bodyMarker = markerCreate();
9522
        body = markerApply(bodyMarker, parseObjectType(allowStatic));
9523
9524
        return markerApply(marker, delegate.createInterface(
9525
            id,
9526
            typeParameters,
9527
            body,
9528
            extended
9529
        ));
9530
    }
9531
9532
    function parseInterface() {
9533
        var marker = markerCreate();
9534
9535
        if (strict) {
9536
            expectKeyword('interface');
9537
        } else {
9538
            expectContextualKeyword('interface');
9539
        }
9540
9541
        return parseInterfaceish(marker, /* allowStatic */false);
9542
    }
9543
9544
    function parseDeclareClass() {
9545
        var marker = markerCreate(), ret;
9546
        expectContextualKeyword('declare');
9547
        expectKeyword('class');
9548
9549
        ret = parseInterfaceish(marker, /* allowStatic */true);
9550
        ret.type = Syntax.DeclareClass;
9551
        return ret;
9552
    }
9553
9554
    function parseDeclareFunction() {
9555
        var id, idMarker,
9556
            marker = markerCreate(), params, returnType, rest, tmp,
9557
            typeParameters = null, value, valueMarker;
9558
9559
        expectContextualKeyword('declare');
9560
        expectKeyword('function');
9561
        idMarker = markerCreate();
9562
        id = parseVariableIdentifier();
9563
9564
        valueMarker = markerCreate();
9565
        if (match('<')) {
9566
            typeParameters = parseTypeParameterDeclaration();
9567
        }
9568
        expect('(');
9569
        tmp = parseFunctionTypeParams();
9570
        params = tmp.params;
9571
        rest = tmp.rest;
9572
        expect(')');
9573
9574
        expect(':');
9575
        returnType = parseType();
9576
9577
        value = markerApply(valueMarker, delegate.createFunctionTypeAnnotation(
9578
            params,
9579
            returnType,
9580
            rest,
9581
            typeParameters
9582
        ));
9583
9584
        id.typeAnnotation = markerApply(valueMarker, delegate.createTypeAnnotation(
9585
            value
9586
        ));
9587
        markerApply(idMarker, id);
9588
9589
        consumeSemicolon();
9590
9591
        return markerApply(marker, delegate.createDeclareFunction(
9592
            id
9593
        ));
9594
    }
9595
9596
    function parseDeclareVariable() {
9597
        var id, marker = markerCreate();
9598
        expectContextualKeyword('declare');
9599
        expectKeyword('var');
9600
        id = parseTypeAnnotatableIdentifier();
9601
9602
        consumeSemicolon();
9603
9604
        return markerApply(marker, delegate.createDeclareVariable(
9605
            id
9606
        ));
9607
    }
9608
9609
    function parseDeclareModule() {
9610
        var body = [], bodyMarker, id, idMarker, marker = markerCreate(), token;
9611
        expectContextualKeyword('declare');
9612
        expectContextualKeyword('module');
9613
9614
        if (lookahead.type === Token.StringLiteral) {
9615
            if (strict && lookahead.octal) {
9616
                throwErrorTolerant(lookahead, Messages.StrictOctalLiteral);
9617
            }
9618
            idMarker = markerCreate();
9619
            id = markerApply(idMarker, delegate.createLiteral(lex()));
9620
        } else {
9621
            id = parseVariableIdentifier();
9622
        }
9623
9624
        bodyMarker = markerCreate();
9625
        expect('{');
9626
        while (index < length && !match('}')) {
9627
            token = lookahead2();
9628
            switch (token.value) {
9629
            case 'class':
9630
                body.push(parseDeclareClass());
9631
                break;
9632
            case 'function':
9633
                body.push(parseDeclareFunction());
9634
                break;
9635
            case 'var':
9636
                body.push(parseDeclareVariable());
9637
                break;
9638
            default:
9639
                throwUnexpected(lookahead);
9640
            }
9641
        }
9642
        expect('}');
9643
9644
        return markerApply(marker, delegate.createDeclareModule(
9645
            id,
9646
            markerApply(bodyMarker, delegate.createBlockStatement(body))
9647
        ));
9648
    }
9649
9650
    function collectToken() {
9651
        var loc, token, range, value, entry;
9652
9653
        /* istanbul ignore else */
9654
        if (!state.inJSXChild) {
9655
            skipComment();
9656
        }
9657
9658
        loc = {
9659
            start: {
9660
                line: lineNumber,
9661
                column: index - lineStart
9662
            }
9663
        };
9664
9665
        token = extra.advance();
9666
        loc.end = {
9667
            line: lineNumber,
9668
            column: index - lineStart
9669
        };
9670
9671
        if (token.type !== Token.EOF) {
9672
            range = [token.range[0], token.range[1]];
9673
            value = source.slice(token.range[0], token.range[1]);
9674
            entry = {
9675
                type: TokenName[token.type],
9676
                value: value,
9677
                range: range,
9678
                loc: loc
9679
            };
9680
            if (token.regex) {
9681
                entry.regex = {
9682
                    pattern: token.regex.pattern,
9683
                    flags: token.regex.flags
9684
                };
9685
            }
9686
            extra.tokens.push(entry);
9687
        }
9688
9689
        return token;
9690
    }
9691
9692
    function collectRegex() {
9693
        var pos, loc, regex, token;
9694
9695
        skipComment();
9696
9697
        pos = index;
9698
        loc = {
9699
            start: {
9700
                line: lineNumber,
9701
                column: index - lineStart
9702
            }
9703
        };
9704
9705
        regex = extra.scanRegExp();
9706
        loc.end = {
9707
            line: lineNumber,
9708
            column: index - lineStart
9709
        };
9710
9711
        if (!extra.tokenize) {
9712
            /* istanbul ignore next */
9713
            // Pop the previous token, which is likely '/' or '/='
9714
            if (extra.tokens.length > 0) {
9715
                token = extra.tokens[extra.tokens.length - 1];
9716
                if (token.range[0] === pos && token.type === 'Punctuator') {
9717
                    if (token.value === '/' || token.value === '/=') {
9718
                        extra.tokens.pop();
9719
                    }
9720
                }
9721
            }
9722
9723
            extra.tokens.push({
9724
                type: 'RegularExpression',
9725
                value: regex.literal,
9726
                regex: regex.regex,
9727
                range: [pos, index],
9728
                loc: loc
9729
            });
9730
        }
9731
9732
        return regex;
9733
    }
9734
9735
    function filterTokenLocation() {
9736
        var i, entry, token, tokens = [];
9737
9738
        for (i = 0; i < extra.tokens.length; ++i) {
9739
            entry = extra.tokens[i];
9740
            token = {
9741
                type: entry.type,
9742
                value: entry.value
9743
            };
9744
            if (entry.regex) {
9745
                token.regex = {
9746
                    pattern: entry.regex.pattern,
9747
                    flags: entry.regex.flags
9748
                };
9749
            }
9750
            if (extra.range) {
9751
                token.range = entry.range;
9752
            }
9753
            if (extra.loc) {
9754
                token.loc = entry.loc;
9755
            }
9756
            tokens.push(token);
9757
        }
9758
9759
        extra.tokens = tokens;
9760
    }
9761
9762
    function patch() {
9763
        if (typeof extra.tokens !== 'undefined') {
9764
            extra.advance = advance;
9765
            extra.scanRegExp = scanRegExp;
9766
9767
            advance = collectToken;
0 ignored issues
show
Comprehensibility introduced by
It seems like you are trying to overwrite a function name here. advance is already defined in line 3972 as a function. While this will work, it can be very confusing.
Loading history...
9768
            scanRegExp = collectRegex;
0 ignored issues
show
Comprehensibility introduced by
It seems like you are trying to overwrite a function name here. scanRegExp is already defined in line 3869 as a function. While this will work, it can be very confusing.
Loading history...
9769
        }
9770
    }
9771
9772
    function unpatch() {
9773
        if (typeof extra.scanRegExp === 'function') {
9774
            advance = extra.advance;
0 ignored issues
show
Comprehensibility introduced by
It seems like you are trying to overwrite a function name here. advance is already defined in line 3972 as a function. While this will work, it can be very confusing.
Loading history...
9775
            scanRegExp = extra.scanRegExp;
0 ignored issues
show
Comprehensibility introduced by
It seems like you are trying to overwrite a function name here. scanRegExp is already defined in line 3869 as a function. While this will work, it can be very confusing.
Loading history...
9776
        }
9777
    }
9778
9779
    // This is used to modify the delegate.
9780
9781
    function extend(object, properties) {
9782
        var entry, result = {};
9783
9784
        for (entry in object) {
9785
            /* istanbul ignore else */
9786
            if (object.hasOwnProperty(entry)) {
9787
                result[entry] = object[entry];
9788
            }
9789
        }
9790
9791
        for (entry in properties) {
9792
            /* istanbul ignore else */
9793
            if (properties.hasOwnProperty(entry)) {
9794
                result[entry] = properties[entry];
9795
            }
9796
        }
9797
9798
        return result;
9799
    }
9800
9801
    function tokenize(code, options) {
9802
        var toString,
9803
            token,
9804
            tokens;
9805
9806
        toString = String;
0 ignored issues
show
Comprehensibility Best Practice introduced by
You seem to be aliasing the built-in name String as toString. This makes your code very difficult to follow, consider using the built-in name directly.
Loading history...
9807
        if (typeof code !== 'string' && !(code instanceof String)) {
9808
            code = toString(code);
9809
        }
9810
9811
        delegate = SyntaxTreeDelegate;
9812
        source = code;
9813
        index = 0;
9814
        lineNumber = (source.length > 0) ? 1 : 0;
9815
        lineStart = 0;
9816
        length = source.length;
9817
        lookahead = null;
9818
        state = {
9819
            allowKeyword: true,
9820
            allowIn: true,
9821
            labelSet: new StringMap(),
9822
            inFunctionBody: false,
9823
            inIteration: false,
9824
            inSwitch: false,
9825
            lastCommentStart: -1
9826
        };
9827
9828
        extra = {};
9829
9830
        // Options matching.
9831
        options = options || {};
9832
9833
        // Of course we collect tokens here.
9834
        options.tokens = true;
9835
        extra.tokens = [];
9836
        extra.tokenize = true;
9837
        // The following two fields are necessary to compute the Regex tokens.
9838
        extra.openParenToken = -1;
9839
        extra.openCurlyToken = -1;
9840
9841
        extra.range = (typeof options.range === 'boolean') && options.range;
9842
        extra.loc = (typeof options.loc === 'boolean') && options.loc;
9843
9844
        if (typeof options.comment === 'boolean' && options.comment) {
9845
            extra.comments = [];
9846
        }
9847
        if (typeof options.tolerant === 'boolean' && options.tolerant) {
9848
            extra.errors = [];
9849
        }
9850
9851
        patch();
9852
9853
        try {
9854
            peek();
9855
            if (lookahead.type === Token.EOF) {
9856
                return extra.tokens;
9857
            }
9858
9859
            token = lex();
0 ignored issues
show
Unused Code introduced by
The variable token seems to be never used. Consider removing it.
Loading history...
9860
            while (lookahead.type !== Token.EOF) {
9861
                try {
9862
                    token = lex();
9863
                } catch (lexError) {
9864
                    token = lookahead;
9865
                    if (extra.errors) {
9866
                        extra.errors.push(lexError);
9867
                        // We have to break on the first error
9868
                        // to avoid infinite loops.
9869
                        break;
9870
                    } else {
9871
                        throw lexError;
9872
                    }
9873
                }
9874
            }
9875
9876
            filterTokenLocation();
9877
            tokens = extra.tokens;
9878
            if (typeof extra.comments !== 'undefined') {
9879
                tokens.comments = extra.comments;
9880
            }
9881
            if (typeof extra.errors !== 'undefined') {
9882
                tokens.errors = extra.errors;
9883
            }
9884
        } catch (e) {
9885
            throw e;
9886
        } finally {
9887
            unpatch();
9888
            extra = {};
0 ignored issues
show
Best Practice introduced by
There is no return statement in this branch, but you do return something in other branches. Did you maybe miss it? If you do not want to return anything, consider adding return undefined; explicitly.
Loading history...
9889
        }
9890
        return tokens;
0 ignored issues
show
Bug introduced by
The variable tokens seems to not be initialized for all possible execution paths.
Loading history...
9891
    }
9892
9893
    function parse(code, options) {
9894
        var program, toString;
9895
9896
        toString = String;
0 ignored issues
show
Comprehensibility Best Practice introduced by
You seem to be aliasing the built-in name String as toString. This makes your code very difficult to follow, consider using the built-in name directly.
Loading history...
9897
        if (typeof code !== 'string' && !(code instanceof String)) {
9898
            code = toString(code);
9899
        }
9900
9901
        delegate = SyntaxTreeDelegate;
9902
        source = code;
9903
        index = 0;
9904
        lineNumber = (source.length > 0) ? 1 : 0;
9905
        lineStart = 0;
9906
        length = source.length;
9907
        lookahead = null;
9908
        state = {
9909
            allowKeyword: false,
9910
            allowIn: true,
9911
            labelSet: new StringMap(),
9912
            parenthesizedCount: 0,
9913
            inFunctionBody: false,
9914
            inIteration: false,
9915
            inSwitch: false,
9916
            inJSXChild: false,
9917
            inJSXTag: false,
9918
            inType: false,
9919
            lastCommentStart: -1,
9920
            yieldAllowed: false,
9921
            awaitAllowed: false
9922
        };
9923
9924
        extra = {};
9925
        if (typeof options !== 'undefined') {
9926
            extra.range = (typeof options.range === 'boolean') && options.range;
9927
            extra.loc = (typeof options.loc === 'boolean') && options.loc;
9928
            extra.attachComment = (typeof options.attachComment === 'boolean') && options.attachComment;
9929
9930
            if (extra.loc && options.source !== null && options.source !== undefined) {
9931
                delegate = extend(delegate, {
9932
                    'postProcess': function (node) {
9933
                        node.loc.source = toString(options.source);
9934
                        return node;
9935
                    }
9936
                });
9937
            }
9938
9939
            extra.sourceType = options.sourceType;
9940
            if (typeof options.tokens === 'boolean' && options.tokens) {
9941
                extra.tokens = [];
9942
            }
9943
            if (typeof options.comment === 'boolean' && options.comment) {
9944
                extra.comments = [];
9945
            }
9946
            if (typeof options.tolerant === 'boolean' && options.tolerant) {
9947
                extra.errors = [];
9948
            }
9949
            if (extra.attachComment) {
9950
                extra.range = true;
9951
                extra.comments = [];
9952
                extra.bottomRightStack = [];
9953
                extra.trailingComments = [];
9954
                extra.leadingComments = [];
9955
            }
9956
        }
9957
9958
        patch();
9959
        try {
9960
            program = parseProgram();
9961
            if (typeof extra.comments !== 'undefined') {
9962
                program.comments = extra.comments;
9963
            }
9964
            if (typeof extra.tokens !== 'undefined') {
9965
                filterTokenLocation();
9966
                program.tokens = extra.tokens;
9967
            }
9968
            if (typeof extra.errors !== 'undefined') {
9969
                program.errors = extra.errors;
9970
            }
9971
        } catch (e) {
9972
            throw e;
9973
        } finally {
9974
            unpatch();
9975
            extra = {};
9976
        }
9977
9978
        return program;
9979
    }
9980
9981
    // Sync with *.json manifests.
9982
    exports.version = '13001.1001.0-dev-harmony-fb';
9983
9984
    exports.tokenize = tokenize;
9985
9986
    exports.parse = parse;
9987
9988
    // Deep copy.
9989
   /* istanbul ignore next */
9990
    exports.Syntax = (function () {
9991
        var name, types = {};
9992
9993
        if (typeof Object.create === 'function') {
9994
            types = Object.create(null);
9995
        }
9996
9997
        for (name in Syntax) {
9998
            if (Syntax.hasOwnProperty(name)) {
9999
                types[name] = Syntax[name];
10000
            }
10001
        }
10002
10003
        if (typeof Object.freeze === 'function') {
10004
            Object.freeze(types);
10005
        }
10006
10007
        return types;
10008
    }());
10009
10010
}));
10011
/* vim: set sw=4 ts=4 et tw=80 : */
10012
10013
},{}],10:[function(_dereq_,module,exports){
10014
var Base62 = (function (my) {
10015
  my.chars = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"]
10016
10017
  my.encode = function(i){
10018
    if (i === 0) {return '0'}
10019
    var s = ''
10020
    while (i > 0) {
10021
      s = this.chars[i % 62] + s
10022
      i = Math.floor(i/62)
10023
    }
10024
    return s
10025
  };
10026
  my.decode = function(a,b,c,d){
10027
    for (
10028
      b = c = (
10029
        a === (/\W|_|^$/.test(a += "") || a)
10030
      ) - 1;
10031
      d = a.charCodeAt(c++);
10032
    )
10033
    b = b * 62 + d - [, 48, 29, 87][d >> 5];
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
introduced by
There are two consecutive commas which insert an implicit undefined value. If this is indeed intended, consider adding undefined explicitly like so , undefined,.
Loading history...
10034
    return b
10035
  };
10036
10037
  return my;
10038
}({}));
10039
10040
module.exports = Base62
10041
},{}],11:[function(_dereq_,module,exports){
10042
/*
10043
 * Copyright 2009-2011 Mozilla Foundation and contributors
10044
 * Licensed under the New BSD license. See LICENSE.txt or:
10045
 * http://opensource.org/licenses/BSD-3-Clause
10046
 */
10047
exports.SourceMapGenerator = _dereq_('./source-map/source-map-generator').SourceMapGenerator;
10048
exports.SourceMapConsumer = _dereq_('./source-map/source-map-consumer').SourceMapConsumer;
10049
exports.SourceNode = _dereq_('./source-map/source-node').SourceNode;
10050
10051
},{"./source-map/source-map-consumer":16,"./source-map/source-map-generator":17,"./source-map/source-node":18}],12:[function(_dereq_,module,exports){
0 ignored issues
show
Unused Code introduced by
The parameter exports is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
10052
/* -*- Mode: js; js-indent-level: 2; -*- */
10053
/*
10054
 * Copyright 2011 Mozilla Foundation and contributors
10055
 * Licensed under the New BSD license. See LICENSE or:
10056
 * http://opensource.org/licenses/BSD-3-Clause
10057
 */
10058
if (typeof define !== 'function') {
0 ignored issues
show
Bug introduced by
The variable define seems to be never initialized.
Loading history...
10059
    var define = _dereq_('amdefine')(module, _dereq_);
10060
}
10061
define(function (_dereq_, exports, module) {
0 ignored issues
show
Unused Code introduced by
The parameter module is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
10062
10063
  var util = _dereq_('./util');
10064
10065
  /**
10066
   * A data structure which is a combination of an array and a set. Adding a new
10067
   * member is O(1), testing for membership is O(1), and finding the index of an
10068
   * element is O(1). Removing elements from the set is not supported. Only
10069
   * strings are supported for membership.
10070
   */
10071
  function ArraySet() {
10072
    this._array = [];
10073
    this._set = {};
10074
  }
10075
10076
  /**
10077
   * Static method for creating ArraySet instances from an existing array.
10078
   */
10079
  ArraySet.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) {
10080
    var set = new ArraySet();
10081
    for (var i = 0, len = aArray.length; i < len; i++) {
10082
      set.add(aArray[i], aAllowDuplicates);
10083
    }
10084
    return set;
10085
  };
10086
10087
  /**
10088
   * Add the given string to this set.
10089
   *
10090
   * @param String aStr
0 ignored issues
show
Documentation introduced by
The parameter String does not exist. Did you maybe forget to remove this comment?
Loading history...
10091
   */
10092
  ArraySet.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) {
10093
    var isDuplicate = this.has(aStr);
10094
    var idx = this._array.length;
10095
    if (!isDuplicate || aAllowDuplicates) {
10096
      this._array.push(aStr);
10097
    }
10098
    if (!isDuplicate) {
10099
      this._set[util.toSetString(aStr)] = idx;
10100
    }
10101
  };
10102
10103
  /**
10104
   * Is the given string a member of this set?
10105
   *
10106
   * @param String aStr
0 ignored issues
show
Documentation introduced by
The parameter String does not exist. Did you maybe forget to remove this comment?
Loading history...
10107
   */
10108
  ArraySet.prototype.has = function ArraySet_has(aStr) {
10109
    return Object.prototype.hasOwnProperty.call(this._set,
10110
                                                util.toSetString(aStr));
10111
  };
10112
10113
  /**
10114
   * What is the index of the given string in the array?
10115
   *
10116
   * @param String aStr
0 ignored issues
show
Documentation introduced by
The parameter String does not exist. Did you maybe forget to remove this comment?
Loading history...
10117
   */
10118
  ArraySet.prototype.indexOf = function ArraySet_indexOf(aStr) {
10119
    if (this.has(aStr)) {
10120
      return this._set[util.toSetString(aStr)];
10121
    }
10122
    throw new Error('"' + aStr + '" is not in the set.');
10123
  };
10124
10125
  /**
10126
   * What is the element at the given index?
10127
   *
10128
   * @param Number aIdx
0 ignored issues
show
Documentation introduced by
The parameter Number does not exist. Did you maybe forget to remove this comment?
Loading history...
10129
   */
10130
  ArraySet.prototype.at = function ArraySet_at(aIdx) {
10131
    if (aIdx >= 0 && aIdx < this._array.length) {
10132
      return this._array[aIdx];
10133
    }
10134
    throw new Error('No element indexed by ' + aIdx);
10135
  };
10136
10137
  /**
10138
   * Returns the array representation of this set (which has the proper indices
10139
   * indicated by indexOf). Note that this is a copy of the internal array used
10140
   * for storing the members so that no one can mess with internal state.
10141
   */
10142
  ArraySet.prototype.toArray = function ArraySet_toArray() {
10143
    return this._array.slice();
10144
  };
10145
10146
  exports.ArraySet = ArraySet;
10147
10148
});
10149
10150
},{"./util":19,"amdefine":20}],13:[function(_dereq_,module,exports){
0 ignored issues
show
Unused Code introduced by
The parameter exports is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
10151
/* -*- Mode: js; js-indent-level: 2; -*- */
10152
/*
10153
 * Copyright 2011 Mozilla Foundation and contributors
10154
 * Licensed under the New BSD license. See LICENSE or:
10155
 * http://opensource.org/licenses/BSD-3-Clause
10156
 *
10157
 * Based on the Base 64 VLQ implementation in Closure Compiler:
10158
 * https://code.google.com/p/closure-compiler/source/browse/trunk/src/com/google/debugging/sourcemap/Base64VLQ.java
10159
 *
10160
 * Copyright 2011 The Closure Compiler Authors. All rights reserved.
10161
 * Redistribution and use in source and binary forms, with or without
10162
 * modification, are permitted provided that the following conditions are
10163
 * met:
10164
 *
10165
 *  * Redistributions of source code must retain the above copyright
10166
 *    notice, this list of conditions and the following disclaimer.
10167
 *  * Redistributions in binary form must reproduce the above
10168
 *    copyright notice, this list of conditions and the following
10169
 *    disclaimer in the documentation and/or other materials provided
10170
 *    with the distribution.
10171
 *  * Neither the name of Google Inc. nor the names of its
10172
 *    contributors may be used to endorse or promote products derived
10173
 *    from this software without specific prior written permission.
10174
 *
10175
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
10176
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
10177
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
10178
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
10179
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
10180
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
10181
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
10182
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
10183
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
10184
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
10185
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
10186
 */
10187
if (typeof define !== 'function') {
0 ignored issues
show
Bug introduced by
The variable define seems to be never initialized.
Loading history...
10188
    var define = _dereq_('amdefine')(module, _dereq_);
10189
}
10190
define(function (_dereq_, exports, module) {
0 ignored issues
show
Unused Code introduced by
The parameter module is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
10191
10192
  var base64 = _dereq_('./base64');
10193
10194
  // A single base 64 digit can contain 6 bits of data. For the base 64 variable
10195
  // length quantities we use in the source map spec, the first bit is the sign,
10196
  // the next four bits are the actual value, and the 6th bit is the
10197
  // continuation bit. The continuation bit tells us whether there are more
10198
  // digits in this value following this digit.
10199
  //
10200
  //   Continuation
10201
  //   |    Sign
10202
  //   |    |
10203
  //   V    V
10204
  //   101011
10205
10206
  var VLQ_BASE_SHIFT = 5;
10207
10208
  // binary: 100000
10209
  var VLQ_BASE = 1 << VLQ_BASE_SHIFT;
10210
10211
  // binary: 011111
10212
  var VLQ_BASE_MASK = VLQ_BASE - 1;
10213
10214
  // binary: 100000
10215
  var VLQ_CONTINUATION_BIT = VLQ_BASE;
10216
10217
  /**
10218
   * Converts from a two-complement value to a value where the sign bit is
10219
   * is placed in the least significant bit.  For example, as decimals:
10220
   *   1 becomes 2 (10 binary), -1 becomes 3 (11 binary)
10221
   *   2 becomes 4 (100 binary), -2 becomes 5 (101 binary)
10222
   */
10223
  function toVLQSigned(aValue) {
10224
    return aValue < 0
10225
      ? ((-aValue) << 1) + 1
10226
      : (aValue << 1) + 0;
10227
  }
10228
10229
  /**
10230
   * Converts to a two-complement value from a value where the sign bit is
10231
   * is placed in the least significant bit.  For example, as decimals:
10232
   *   2 (10 binary) becomes 1, 3 (11 binary) becomes -1
10233
   *   4 (100 binary) becomes 2, 5 (101 binary) becomes -2
10234
   */
10235
  function fromVLQSigned(aValue) {
10236
    var isNegative = (aValue & 1) === 1;
10237
    var shifted = aValue >> 1;
10238
    return isNegative
10239
      ? -shifted
10240
      : shifted;
10241
  }
10242
10243
  /**
10244
   * Returns the base 64 VLQ encoded value.
10245
   */
10246
  exports.encode = function base64VLQ_encode(aValue) {
10247
    var encoded = "";
10248
    var digit;
10249
10250
    var vlq = toVLQSigned(aValue);
10251
10252
    do {
10253
      digit = vlq & VLQ_BASE_MASK;
10254
      vlq >>>= VLQ_BASE_SHIFT;
10255
      if (vlq > 0) {
10256
        // There are still more digits in this value, so we must make sure the
10257
        // continuation bit is marked.
10258
        digit |= VLQ_CONTINUATION_BIT;
10259
      }
10260
      encoded += base64.encode(digit);
10261
    } while (vlq > 0);
10262
10263
    return encoded;
10264
  };
10265
10266
  /**
10267
   * Decodes the next base 64 VLQ value from the given string and returns the
10268
   * value and the rest of the string.
10269
   */
10270
  exports.decode = function base64VLQ_decode(aStr) {
10271
    var i = 0;
10272
    var strLen = aStr.length;
10273
    var result = 0;
10274
    var shift = 0;
10275
    var continuation, digit;
10276
10277
    do {
10278
      if (i >= strLen) {
10279
        throw new Error("Expected more digits in base 64 VLQ value.");
10280
      }
10281
      digit = base64.decode(aStr.charAt(i++));
10282
      continuation = !!(digit & VLQ_CONTINUATION_BIT);
10283
      digit &= VLQ_BASE_MASK;
10284
      result = result + (digit << shift);
10285
      shift += VLQ_BASE_SHIFT;
10286
    } while (continuation);
10287
10288
    return {
10289
      value: fromVLQSigned(result),
10290
      rest: aStr.slice(i)
10291
    };
10292
  };
10293
10294
});
10295
10296
},{"./base64":14,"amdefine":20}],14:[function(_dereq_,module,exports){
0 ignored issues
show
Unused Code introduced by
The parameter exports is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
10297
/* -*- Mode: js; js-indent-level: 2; -*- */
10298
/*
10299
 * Copyright 2011 Mozilla Foundation and contributors
10300
 * Licensed under the New BSD license. See LICENSE or:
10301
 * http://opensource.org/licenses/BSD-3-Clause
10302
 */
10303
if (typeof define !== 'function') {
0 ignored issues
show
Bug introduced by
The variable define seems to be never initialized.
Loading history...
10304
    var define = _dereq_('amdefine')(module, _dereq_);
10305
}
10306
define(function (_dereq_, exports, module) {
0 ignored issues
show
Unused Code introduced by
The parameter module is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
10307
10308
  var charToIntMap = {};
10309
  var intToCharMap = {};
10310
10311
  'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
10312
    .split('')
10313
    .forEach(function (ch, index) {
10314
      charToIntMap[ch] = index;
10315
      intToCharMap[index] = ch;
10316
    });
10317
10318
  /**
10319
   * Encode an integer in the range of 0 to 63 to a single base 64 digit.
10320
   */
10321
  exports.encode = function base64_encode(aNumber) {
10322
    if (aNumber in intToCharMap) {
10323
      return intToCharMap[aNumber];
10324
    }
10325
    throw new TypeError("Must be between 0 and 63: " + aNumber);
10326
  };
10327
10328
  /**
10329
   * Decode a single base 64 digit to an integer.
10330
   */
10331
  exports.decode = function base64_decode(aChar) {
10332
    if (aChar in charToIntMap) {
10333
      return charToIntMap[aChar];
10334
    }
10335
    throw new TypeError("Not a valid base 64 digit: " + aChar);
10336
  };
10337
10338
});
10339
10340
},{"amdefine":20}],15:[function(_dereq_,module,exports){
0 ignored issues
show
Unused Code introduced by
The parameter exports is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
10341
/* -*- Mode: js; js-indent-level: 2; -*- */
10342
/*
10343
 * Copyright 2011 Mozilla Foundation and contributors
10344
 * Licensed under the New BSD license. See LICENSE or:
10345
 * http://opensource.org/licenses/BSD-3-Clause
10346
 */
10347
if (typeof define !== 'function') {
0 ignored issues
show
Bug introduced by
The variable define seems to be never initialized.
Loading history...
10348
    var define = _dereq_('amdefine')(module, _dereq_);
10349
}
10350
define(function (_dereq_, exports, module) {
0 ignored issues
show
Unused Code introduced by
The parameter module is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
10351
10352
  /**
10353
   * Recursive implementation of binary search.
10354
   *
10355
   * @param aLow Indices here and lower do not contain the needle.
10356
   * @param aHigh Indices here and higher do not contain the needle.
10357
   * @param aNeedle The element being searched for.
10358
   * @param aHaystack The non-empty array being searched.
10359
   * @param aCompare Function which takes two elements and returns -1, 0, or 1.
10360
   */
10361
  function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare) {
10362
    // This function terminates when one of the following is true:
10363
    //
10364
    //   1. We find the exact element we are looking for.
10365
    //
10366
    //   2. We did not find the exact element, but we can return the next
10367
    //      closest element that is less than that element.
10368
    //
10369
    //   3. We did not find the exact element, and there is no next-closest
10370
    //      element which is less than the one we are searching for, so we
10371
    //      return null.
10372
    var mid = Math.floor((aHigh - aLow) / 2) + aLow;
10373
    var cmp = aCompare(aNeedle, aHaystack[mid], true);
10374
    if (cmp === 0) {
10375
      // Found the element we are looking for.
10376
      return aHaystack[mid];
10377
    }
10378
    else if (cmp > 0) {
10379
      // aHaystack[mid] is greater than our needle.
10380
      if (aHigh - mid > 1) {
10381
        // The element is in the upper half.
10382
        return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare);
10383
      }
10384
      // We did not find an exact match, return the next closest one
10385
      // (termination case 2).
10386
      return aHaystack[mid];
10387
    }
10388
    else {
10389
      // aHaystack[mid] is less than our needle.
10390
      if (mid - aLow > 1) {
10391
        // The element is in the lower half.
10392
        return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare);
10393
      }
10394
      // The exact needle element was not found in this haystack. Determine if
10395
      // we are in termination case (2) or (3) and return the appropriate thing.
10396
      return aLow < 0
10397
        ? null
10398
        : aHaystack[aLow];
10399
    }
10400
  }
10401
10402
  /**
10403
   * This is an implementation of binary search which will always try and return
10404
   * the next lowest value checked if there is no exact hit. This is because
10405
   * mappings between original and generated line/col pairs are single points,
10406
   * and there is an implicit region between each of them, so a miss just means
10407
   * that you aren't on the very start of a region.
10408
   *
10409
   * @param aNeedle The element you are looking for.
10410
   * @param aHaystack The array that is being searched.
10411
   * @param aCompare A function which takes the needle and an element in the
10412
   *     array and returns -1, 0, or 1 depending on whether the needle is less
10413
   *     than, equal to, or greater than the element, respectively.
10414
   */
10415
  exports.search = function search(aNeedle, aHaystack, aCompare) {
10416
    return aHaystack.length > 0
10417
      ? recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack, aCompare)
10418
      : null;
10419
  };
10420
10421
});
10422
10423
},{"amdefine":20}],16:[function(_dereq_,module,exports){
0 ignored issues
show
Unused Code introduced by
The parameter exports is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
10424
/* -*- Mode: js; js-indent-level: 2; -*- */
10425
/*
10426
 * Copyright 2011 Mozilla Foundation and contributors
10427
 * Licensed under the New BSD license. See LICENSE or:
10428
 * http://opensource.org/licenses/BSD-3-Clause
10429
 */
10430
if (typeof define !== 'function') {
0 ignored issues
show
Bug introduced by
The variable define seems to be never initialized.
Loading history...
10431
    var define = _dereq_('amdefine')(module, _dereq_);
10432
}
10433
define(function (_dereq_, exports, module) {
0 ignored issues
show
Unused Code introduced by
The parameter module is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
10434
10435
  var util = _dereq_('./util');
10436
  var binarySearch = _dereq_('./binary-search');
10437
  var ArraySet = _dereq_('./array-set').ArraySet;
10438
  var base64VLQ = _dereq_('./base64-vlq');
10439
10440
  /**
10441
   * A SourceMapConsumer instance represents a parsed source map which we can
10442
   * query for information about the original file positions by giving it a file
10443
   * position in the generated source.
10444
   *
10445
   * The only parameter is the raw source map (either as a JSON string, or
10446
   * already parsed to an object). According to the spec, source maps have the
10447
   * following attributes:
10448
   *
10449
   *   - version: Which version of the source map spec this map is following.
10450
   *   - sources: An array of URLs to the original source files.
10451
   *   - names: An array of identifiers which can be referrenced by individual mappings.
10452
   *   - sourceRoot: Optional. The URL root from which all sources are relative.
10453
   *   - sourcesContent: Optional. An array of contents of the original source files.
10454
   *   - mappings: A string of base64 VLQs which contain the actual mappings.
10455
   *   - file: The generated file this source map is associated with.
10456
   *
10457
   * Here is an example source map, taken from the source map spec[0]:
10458
   *
10459
   *     {
10460
   *       version : 3,
10461
   *       file: "out.js",
10462
   *       sourceRoot : "",
10463
   *       sources: ["foo.js", "bar.js"],
10464
   *       names: ["src", "maps", "are", "fun"],
10465
   *       mappings: "AA,AB;;ABCDE;"
10466
   *     }
10467
   *
10468
   * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?pli=1#
10469
   */
10470
  function SourceMapConsumer(aSourceMap) {
10471
    var sourceMap = aSourceMap;
10472
    if (typeof aSourceMap === 'string') {
10473
      sourceMap = JSON.parse(aSourceMap.replace(/^\)\]\}'/, ''));
10474
    }
10475
10476
    var version = util.getArg(sourceMap, 'version');
10477
    var sources = util.getArg(sourceMap, 'sources');
10478
    // Sass 3.3 leaves out the 'names' array, so we deviate from the spec (which
10479
    // requires the array) to play nice here.
10480
    var names = util.getArg(sourceMap, 'names', []);
10481
    var sourceRoot = util.getArg(sourceMap, 'sourceRoot', null);
10482
    var sourcesContent = util.getArg(sourceMap, 'sourcesContent', null);
10483
    var mappings = util.getArg(sourceMap, 'mappings');
10484
    var file = util.getArg(sourceMap, 'file', null);
10485
10486
    // Once again, Sass deviates from the spec and supplies the version as a
10487
    // string rather than a number, so we use loose equality checking here.
10488
    if (version != this._version) {
10489
      throw new Error('Unsupported version: ' + version);
10490
    }
10491
10492
    // Pass `true` below to allow duplicate names and sources. While source maps
10493
    // are intended to be compressed and deduplicated, the TypeScript compiler
10494
    // sometimes generates source maps with duplicates in them. See Github issue
10495
    // #72 and bugzil.la/889492.
10496
    this._names = ArraySet.fromArray(names, true);
10497
    this._sources = ArraySet.fromArray(sources, true);
10498
10499
    this.sourceRoot = sourceRoot;
10500
    this.sourcesContent = sourcesContent;
10501
    this._mappings = mappings;
10502
    this.file = file;
10503
  }
10504
10505
  /**
10506
   * Create a SourceMapConsumer from a SourceMapGenerator.
10507
   *
10508
   * @param SourceMapGenerator aSourceMap
10509
   *        The source map that will be consumed.
10510
   * @returns SourceMapConsumer
10511
   */
10512
  SourceMapConsumer.fromSourceMap =
10513
    function SourceMapConsumer_fromSourceMap(aSourceMap) {
10514
      var smc = Object.create(SourceMapConsumer.prototype);
10515
10516
      smc._names = ArraySet.fromArray(aSourceMap._names.toArray(), true);
10517
      smc._sources = ArraySet.fromArray(aSourceMap._sources.toArray(), true);
10518
      smc.sourceRoot = aSourceMap._sourceRoot;
10519
      smc.sourcesContent = aSourceMap._generateSourcesContent(smc._sources.toArray(),
10520
                                                              smc.sourceRoot);
10521
      smc.file = aSourceMap._file;
10522
10523
      smc.__generatedMappings = aSourceMap._mappings.slice()
10524
        .sort(util.compareByGeneratedPositions);
10525
      smc.__originalMappings = aSourceMap._mappings.slice()
10526
        .sort(util.compareByOriginalPositions);
10527
10528
      return smc;
10529
    };
10530
10531
  /**
10532
   * The version of the source mapping spec that we are consuming.
10533
   */
10534
  SourceMapConsumer.prototype._version = 3;
10535
10536
  /**
10537
   * The list of original sources.
10538
   */
10539
  Object.defineProperty(SourceMapConsumer.prototype, 'sources', {
10540
    get: function () {
10541
      return this._sources.toArray().map(function (s) {
10542
        return this.sourceRoot ? util.join(this.sourceRoot, s) : s;
10543
      }, this);
10544
    }
10545
  });
10546
10547
  // `__generatedMappings` and `__originalMappings` are arrays that hold the
10548
  // parsed mapping coordinates from the source map's "mappings" attribute. They
10549
  // are lazily instantiated, accessed via the `_generatedMappings` and
10550
  // `_originalMappings` getters respectively, and we only parse the mappings
10551
  // and create these arrays once queried for a source location. We jump through
10552
  // these hoops because there can be many thousands of mappings, and parsing
10553
  // them is expensive, so we only want to do it if we must.
10554
  //
10555
  // Each object in the arrays is of the form:
10556
  //
10557
  //     {
10558
  //       generatedLine: The line number in the generated code,
10559
  //       generatedColumn: The column number in the generated code,
10560
  //       source: The path to the original source file that generated this
10561
  //               chunk of code,
10562
  //       originalLine: The line number in the original source that
10563
  //                     corresponds to this chunk of generated code,
10564
  //       originalColumn: The column number in the original source that
10565
  //                       corresponds to this chunk of generated code,
10566
  //       name: The name of the original symbol which generated this chunk of
10567
  //             code.
10568
  //     }
10569
  //
10570
  // All properties except for `generatedLine` and `generatedColumn` can be
10571
  // `null`.
10572
  //
10573
  // `_generatedMappings` is ordered by the generated positions.
10574
  //
10575
  // `_originalMappings` is ordered by the original positions.
10576
10577
  SourceMapConsumer.prototype.__generatedMappings = null;
10578
  Object.defineProperty(SourceMapConsumer.prototype, '_generatedMappings', {
10579
    get: function () {
10580
      if (!this.__generatedMappings) {
10581
        this.__generatedMappings = [];
10582
        this.__originalMappings = [];
10583
        this._parseMappings(this._mappings, this.sourceRoot);
10584
      }
10585
10586
      return this.__generatedMappings;
10587
    }
10588
  });
10589
10590
  SourceMapConsumer.prototype.__originalMappings = null;
10591
  Object.defineProperty(SourceMapConsumer.prototype, '_originalMappings', {
10592
    get: function () {
10593
      if (!this.__originalMappings) {
10594
        this.__generatedMappings = [];
10595
        this.__originalMappings = [];
10596
        this._parseMappings(this._mappings, this.sourceRoot);
10597
      }
10598
10599
      return this.__originalMappings;
10600
    }
10601
  });
10602
10603
  /**
10604
   * Parse the mappings in a string in to a data structure which we can easily
10605
   * query (the ordered arrays in the `this.__generatedMappings` and
10606
   * `this.__originalMappings` properties).
10607
   */
10608
  SourceMapConsumer.prototype._parseMappings =
10609
    function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {
0 ignored issues
show
Unused Code introduced by
The parameter aSourceRoot is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
10610
      var generatedLine = 1;
10611
      var previousGeneratedColumn = 0;
10612
      var previousOriginalLine = 0;
10613
      var previousOriginalColumn = 0;
10614
      var previousSource = 0;
10615
      var previousName = 0;
10616
      var mappingSeparator = /^[,;]/;
10617
      var str = aStr;
10618
      var mapping;
10619
      var temp;
10620
10621
      while (str.length > 0) {
10622
        if (str.charAt(0) === ';') {
10623
          generatedLine++;
10624
          str = str.slice(1);
10625
          previousGeneratedColumn = 0;
10626
        }
10627
        else if (str.charAt(0) === ',') {
10628
          str = str.slice(1);
10629
        }
10630
        else {
10631
          mapping = {};
10632
          mapping.generatedLine = generatedLine;
10633
10634
          // Generated column.
10635
          temp = base64VLQ.decode(str);
10636
          mapping.generatedColumn = previousGeneratedColumn + temp.value;
10637
          previousGeneratedColumn = mapping.generatedColumn;
10638
          str = temp.rest;
10639
10640
          if (str.length > 0 && !mappingSeparator.test(str.charAt(0))) {
10641
            // Original source.
10642
            temp = base64VLQ.decode(str);
10643
            mapping.source = this._sources.at(previousSource + temp.value);
10644
            previousSource += temp.value;
10645
            str = temp.rest;
10646
            if (str.length === 0 || mappingSeparator.test(str.charAt(0))) {
10647
              throw new Error('Found a source, but no line and column');
10648
            }
10649
10650
            // Original line.
10651
            temp = base64VLQ.decode(str);
10652
            mapping.originalLine = previousOriginalLine + temp.value;
10653
            previousOriginalLine = mapping.originalLine;
10654
            // Lines are stored 0-based
10655
            mapping.originalLine += 1;
10656
            str = temp.rest;
10657
            if (str.length === 0 || mappingSeparator.test(str.charAt(0))) {
10658
              throw new Error('Found a source and line, but no column');
10659
            }
10660
10661
            // Original column.
10662
            temp = base64VLQ.decode(str);
10663
            mapping.originalColumn = previousOriginalColumn + temp.value;
10664
            previousOriginalColumn = mapping.originalColumn;
10665
            str = temp.rest;
10666
10667
            if (str.length > 0 && !mappingSeparator.test(str.charAt(0))) {
10668
              // Original name.
10669
              temp = base64VLQ.decode(str);
10670
              mapping.name = this._names.at(previousName + temp.value);
10671
              previousName += temp.value;
10672
              str = temp.rest;
10673
            }
10674
          }
10675
10676
          this.__generatedMappings.push(mapping);
10677
          if (typeof mapping.originalLine === 'number') {
10678
            this.__originalMappings.push(mapping);
10679
          }
10680
        }
10681
      }
10682
10683
      this.__originalMappings.sort(util.compareByOriginalPositions);
10684
    };
10685
10686
  /**
10687
   * Find the mapping that best matches the hypothetical "needle" mapping that
10688
   * we are searching for in the given "haystack" of mappings.
10689
   */
10690
  SourceMapConsumer.prototype._findMapping =
10691
    function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName,
10692
                                           aColumnName, aComparator) {
10693
      // To return the position we are searching for, we must first find the
10694
      // mapping for the given position and then return the opposite position it
10695
      // points to. Because the mappings are sorted, we can use binary search to
10696
      // find the best mapping.
10697
10698
      if (aNeedle[aLineName] <= 0) {
10699
        throw new TypeError('Line must be greater than or equal to 1, got '
10700
                            + aNeedle[aLineName]);
10701
      }
10702
      if (aNeedle[aColumnName] < 0) {
10703
        throw new TypeError('Column must be greater than or equal to 0, got '
10704
                            + aNeedle[aColumnName]);
10705
      }
10706
10707
      return binarySearch.search(aNeedle, aMappings, aComparator);
10708
    };
10709
10710
  /**
10711
   * Returns the original source, line, and column information for the generated
10712
   * source's line and column positions provided. The only argument is an object
10713
   * with the following properties:
10714
   *
10715
   *   - line: The line number in the generated source.
10716
   *   - column: The column number in the generated source.
10717
   *
10718
   * and an object is returned with the following properties:
10719
   *
10720
   *   - source: The original source file, or null.
10721
   *   - line: The line number in the original source, or null.
10722
   *   - column: The column number in the original source, or null.
10723
   *   - name: The original identifier, or null.
10724
   */
10725
  SourceMapConsumer.prototype.originalPositionFor =
10726
    function SourceMapConsumer_originalPositionFor(aArgs) {
10727
      var needle = {
10728
        generatedLine: util.getArg(aArgs, 'line'),
10729
        generatedColumn: util.getArg(aArgs, 'column')
10730
      };
10731
10732
      var mapping = this._findMapping(needle,
10733
                                      this._generatedMappings,
10734
                                      "generatedLine",
10735
                                      "generatedColumn",
10736
                                      util.compareByGeneratedPositions);
10737
10738
      if (mapping) {
10739
        var source = util.getArg(mapping, 'source', null);
10740
        if (source && this.sourceRoot) {
10741
          source = util.join(this.sourceRoot, source);
10742
        }
10743
        return {
10744
          source: source,
10745
          line: util.getArg(mapping, 'originalLine', null),
10746
          column: util.getArg(mapping, 'originalColumn', null),
10747
          name: util.getArg(mapping, 'name', null)
10748
        };
10749
      }
10750
10751
      return {
10752
        source: null,
10753
        line: null,
10754
        column: null,
10755
        name: null
10756
      };
10757
    };
10758
10759
  /**
10760
   * Returns the original source content. The only argument is the url of the
10761
   * original source file. Returns null if no original source content is
10762
   * availible.
10763
   */
10764
  SourceMapConsumer.prototype.sourceContentFor =
10765
    function SourceMapConsumer_sourceContentFor(aSource) {
10766
      if (!this.sourcesContent) {
10767
        return null;
10768
      }
10769
10770
      if (this.sourceRoot) {
10771
        aSource = util.relative(this.sourceRoot, aSource);
10772
      }
10773
10774
      if (this._sources.has(aSource)) {
10775
        return this.sourcesContent[this._sources.indexOf(aSource)];
10776
      }
10777
10778
      var url;
10779
      if (this.sourceRoot
10780
          && (url = util.urlParse(this.sourceRoot))) {
10781
        // XXX: file:// URIs and absolute paths lead to unexpected behavior for
10782
        // many users. We can help them out when they expect file:// URIs to
10783
        // behave like it would if they were running a local HTTP server. See
10784
        // https://bugzilla.mozilla.org/show_bug.cgi?id=885597.
10785
        var fileUriAbsPath = aSource.replace(/^file:\/\//, "");
10786
        if (url.scheme == "file"
10787
            && this._sources.has(fileUriAbsPath)) {
10788
          return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)]
10789
        }
10790
10791
        if ((!url.path || url.path == "/")
10792
            && this._sources.has("/" + aSource)) {
10793
          return this.sourcesContent[this._sources.indexOf("/" + aSource)];
10794
        }
10795
      }
10796
10797
      throw new Error('"' + aSource + '" is not in the SourceMap.');
10798
    };
10799
10800
  /**
10801
   * Returns the generated line and column information for the original source,
10802
   * line, and column positions provided. The only argument is an object with
10803
   * the following properties:
10804
   *
10805
   *   - source: The filename of the original source.
10806
   *   - line: The line number in the original source.
10807
   *   - column: The column number in the original source.
10808
   *
10809
   * and an object is returned with the following properties:
10810
   *
10811
   *   - line: The line number in the generated source, or null.
10812
   *   - column: The column number in the generated source, or null.
10813
   */
10814
  SourceMapConsumer.prototype.generatedPositionFor =
10815
    function SourceMapConsumer_generatedPositionFor(aArgs) {
10816
      var needle = {
10817
        source: util.getArg(aArgs, 'source'),
10818
        originalLine: util.getArg(aArgs, 'line'),
10819
        originalColumn: util.getArg(aArgs, 'column')
10820
      };
10821
10822
      if (this.sourceRoot) {
10823
        needle.source = util.relative(this.sourceRoot, needle.source);
10824
      }
10825
10826
      var mapping = this._findMapping(needle,
10827
                                      this._originalMappings,
10828
                                      "originalLine",
10829
                                      "originalColumn",
10830
                                      util.compareByOriginalPositions);
10831
10832
      if (mapping) {
10833
        return {
10834
          line: util.getArg(mapping, 'generatedLine', null),
10835
          column: util.getArg(mapping, 'generatedColumn', null)
10836
        };
10837
      }
10838
10839
      return {
10840
        line: null,
10841
        column: null
10842
      };
10843
    };
10844
10845
  SourceMapConsumer.GENERATED_ORDER = 1;
10846
  SourceMapConsumer.ORIGINAL_ORDER = 2;
10847
10848
  /**
10849
   * Iterate over each mapping between an original source/line/column and a
10850
   * generated line/column in this source map.
10851
   *
10852
   * @param Function aCallback
10853
   *        The function that is called with each mapping.
10854
   * @param Object aContext
10855
   *        Optional. If specified, this object will be the value of `this` every
10856
   *        time that `aCallback` is called.
10857
   * @param aOrder
10858
   *        Either `SourceMapConsumer.GENERATED_ORDER` or
10859
   *        `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to
10860
   *        iterate over the mappings sorted by the generated file's line/column
10861
   *        order or the original's source/line/column order, respectively. Defaults to
10862
   *        `SourceMapConsumer.GENERATED_ORDER`.
10863
   */
10864
  SourceMapConsumer.prototype.eachMapping =
10865
    function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) {
10866
      var context = aContext || null;
10867
      var order = aOrder || SourceMapConsumer.GENERATED_ORDER;
10868
10869
      var mappings;
10870
      switch (order) {
10871
      case SourceMapConsumer.GENERATED_ORDER:
0 ignored issues
show
Bug introduced by
The variable SourceMapConsumer seems to be never declared. If this is a global, consider adding a /** global: SourceMapConsumer */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
10872
        mappings = this._generatedMappings;
10873
        break;
10874
      case SourceMapConsumer.ORIGINAL_ORDER:
10875
        mappings = this._originalMappings;
10876
        break;
10877
      default:
10878
        throw new Error("Unknown order of iteration.");
10879
      }
10880
10881
      var sourceRoot = this.sourceRoot;
10882
      mappings.map(function (mapping) {
10883
        var source = mapping.source;
10884
        if (source && sourceRoot) {
10885
          source = util.join(sourceRoot, source);
10886
        }
10887
        return {
10888
          source: source,
10889
          generatedLine: mapping.generatedLine,
10890
          generatedColumn: mapping.generatedColumn,
10891
          originalLine: mapping.originalLine,
10892
          originalColumn: mapping.originalColumn,
10893
          name: mapping.name
10894
        };
10895
      }).forEach(aCallback, context);
10896
    };
10897
10898
  exports.SourceMapConsumer = SourceMapConsumer;
10899
10900
});
10901
10902
},{"./array-set":12,"./base64-vlq":13,"./binary-search":15,"./util":19,"amdefine":20}],17:[function(_dereq_,module,exports){
0 ignored issues
show
Unused Code introduced by
The parameter exports is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
10903
/* -*- Mode: js; js-indent-level: 2; -*- */
10904
/*
10905
 * Copyright 2011 Mozilla Foundation and contributors
10906
 * Licensed under the New BSD license. See LICENSE or:
10907
 * http://opensource.org/licenses/BSD-3-Clause
10908
 */
10909
if (typeof define !== 'function') {
0 ignored issues
show
Bug introduced by
The variable define seems to be never initialized.
Loading history...
10910
    var define = _dereq_('amdefine')(module, _dereq_);
10911
}
10912
define(function (_dereq_, exports, module) {
0 ignored issues
show
Unused Code introduced by
The parameter module is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
10913
10914
  var base64VLQ = _dereq_('./base64-vlq');
10915
  var util = _dereq_('./util');
10916
  var ArraySet = _dereq_('./array-set').ArraySet;
10917
10918
  /**
10919
   * An instance of the SourceMapGenerator represents a source map which is
10920
   * being built incrementally. To create a new one, you must pass an object
10921
   * with the following properties:
10922
   *
10923
   *   - file: The filename of the generated source.
10924
   *   - sourceRoot: An optional root for all URLs in this source map.
10925
   */
10926
  function SourceMapGenerator(aArgs) {
10927
    this._file = util.getArg(aArgs, 'file');
10928
    this._sourceRoot = util.getArg(aArgs, 'sourceRoot', null);
10929
    this._sources = new ArraySet();
10930
    this._names = new ArraySet();
10931
    this._mappings = [];
10932
    this._sourcesContents = null;
10933
  }
10934
10935
  SourceMapGenerator.prototype._version = 3;
10936
10937
  /**
10938
   * Creates a new SourceMapGenerator based on a SourceMapConsumer
10939
   *
10940
   * @param aSourceMapConsumer The SourceMap.
10941
   */
10942
  SourceMapGenerator.fromSourceMap =
10943
    function SourceMapGenerator_fromSourceMap(aSourceMapConsumer) {
10944
      var sourceRoot = aSourceMapConsumer.sourceRoot;
10945
      var generator = new SourceMapGenerator({
10946
        file: aSourceMapConsumer.file,
10947
        sourceRoot: sourceRoot
10948
      });
10949
      aSourceMapConsumer.eachMapping(function (mapping) {
10950
        var newMapping = {
10951
          generated: {
10952
            line: mapping.generatedLine,
10953
            column: mapping.generatedColumn
10954
          }
10955
        };
10956
10957
        if (mapping.source) {
10958
          newMapping.source = mapping.source;
10959
          if (sourceRoot) {
10960
            newMapping.source = util.relative(sourceRoot, newMapping.source);
10961
          }
10962
10963
          newMapping.original = {
10964
            line: mapping.originalLine,
10965
            column: mapping.originalColumn
10966
          };
10967
10968
          if (mapping.name) {
10969
            newMapping.name = mapping.name;
10970
          }
10971
        }
10972
10973
        generator.addMapping(newMapping);
10974
      });
10975
      aSourceMapConsumer.sources.forEach(function (sourceFile) {
10976
        var content = aSourceMapConsumer.sourceContentFor(sourceFile);
10977
        if (content) {
10978
          generator.setSourceContent(sourceFile, content);
10979
        }
10980
      });
10981
      return generator;
10982
    };
10983
10984
  /**
10985
   * Add a single mapping from original source line and column to the generated
10986
   * source's line and column for this source map being created. The mapping
10987
   * object should have the following properties:
10988
   *
10989
   *   - generated: An object with the generated line and column positions.
10990
   *   - original: An object with the original line and column positions.
10991
   *   - source: The original source file (relative to the sourceRoot).
10992
   *   - name: An optional original token name for this mapping.
10993
   */
10994
  SourceMapGenerator.prototype.addMapping =
10995
    function SourceMapGenerator_addMapping(aArgs) {
10996
      var generated = util.getArg(aArgs, 'generated');
10997
      var original = util.getArg(aArgs, 'original', null);
10998
      var source = util.getArg(aArgs, 'source', null);
10999
      var name = util.getArg(aArgs, 'name', null);
11000
11001
      this._validateMapping(generated, original, source, name);
11002
11003
      if (source && !this._sources.has(source)) {
11004
        this._sources.add(source);
11005
      }
11006
11007
      if (name && !this._names.has(name)) {
11008
        this._names.add(name);
11009
      }
11010
11011
      this._mappings.push({
11012
        generatedLine: generated.line,
11013
        generatedColumn: generated.column,
11014
        originalLine: original != null && original.line,
11015
        originalColumn: original != null && original.column,
11016
        source: source,
11017
        name: name
11018
      });
11019
    };
11020
11021
  /**
11022
   * Set the source content for a source file.
11023
   */
11024
  SourceMapGenerator.prototype.setSourceContent =
11025
    function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) {
11026
      var source = aSourceFile;
11027
      if (this._sourceRoot) {
11028
        source = util.relative(this._sourceRoot, source);
11029
      }
11030
11031
      if (aSourceContent !== null) {
11032
        // Add the source content to the _sourcesContents map.
11033
        // Create a new _sourcesContents map if the property is null.
11034
        if (!this._sourcesContents) {
11035
          this._sourcesContents = {};
11036
        }
11037
        this._sourcesContents[util.toSetString(source)] = aSourceContent;
11038
      } else {
11039
        // Remove the source file from the _sourcesContents map.
11040
        // If the _sourcesContents map is empty, set the property to null.
11041
        delete this._sourcesContents[util.toSetString(source)];
11042
        if (Object.keys(this._sourcesContents).length === 0) {
11043
          this._sourcesContents = null;
11044
        }
11045
      }
11046
    };
11047
11048
  /**
11049
   * Applies the mappings of a sub-source-map for a specific source file to the
11050
   * source map being generated. Each mapping to the supplied source file is
11051
   * rewritten using the supplied source map. Note: The resolution for the
11052
   * resulting mappings is the minimium of this map and the supplied map.
11053
   *
11054
   * @param aSourceMapConsumer The source map to be applied.
11055
   * @param aSourceFile Optional. The filename of the source file.
11056
   *        If omitted, SourceMapConsumer's file property will be used.
11057
   */
11058
  SourceMapGenerator.prototype.applySourceMap =
11059
    function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile) {
11060
      // If aSourceFile is omitted, we will use the file property of the SourceMap
11061
      if (!aSourceFile) {
11062
        aSourceFile = aSourceMapConsumer.file;
11063
      }
11064
      var sourceRoot = this._sourceRoot;
11065
      // Make "aSourceFile" relative if an absolute Url is passed.
11066
      if (sourceRoot) {
11067
        aSourceFile = util.relative(sourceRoot, aSourceFile);
11068
      }
11069
      // Applying the SourceMap can add and remove items from the sources and
11070
      // the names array.
11071
      var newSources = new ArraySet();
11072
      var newNames = new ArraySet();
11073
11074
      // Find mappings for the "aSourceFile"
11075
      this._mappings.forEach(function (mapping) {
11076
        if (mapping.source === aSourceFile && mapping.originalLine) {
11077
          // Check if it can be mapped by the source map, then update the mapping.
11078
          var original = aSourceMapConsumer.originalPositionFor({
11079
            line: mapping.originalLine,
11080
            column: mapping.originalColumn
11081
          });
11082
          if (original.source !== null) {
11083
            // Copy mapping
11084
            if (sourceRoot) {
11085
              mapping.source = util.relative(sourceRoot, original.source);
11086
            } else {
11087
              mapping.source = original.source;
11088
            }
11089
            mapping.originalLine = original.line;
11090
            mapping.originalColumn = original.column;
11091
            if (original.name !== null && mapping.name !== null) {
11092
              // Only use the identifier name if it's an identifier
11093
              // in both SourceMaps
11094
              mapping.name = original.name;
11095
            }
11096
          }
11097
        }
11098
11099
        var source = mapping.source;
11100
        if (source && !newSources.has(source)) {
11101
          newSources.add(source);
11102
        }
11103
11104
        var name = mapping.name;
11105
        if (name && !newNames.has(name)) {
11106
          newNames.add(name);
11107
        }
11108
11109
      }, this);
11110
      this._sources = newSources;
11111
      this._names = newNames;
11112
11113
      // Copy sourcesContents of applied map.
11114
      aSourceMapConsumer.sources.forEach(function (sourceFile) {
11115
        var content = aSourceMapConsumer.sourceContentFor(sourceFile);
11116
        if (content) {
11117
          if (sourceRoot) {
11118
            sourceFile = util.relative(sourceRoot, sourceFile);
11119
          }
11120
          this.setSourceContent(sourceFile, content);
11121
        }
11122
      }, this);
11123
    };
11124
11125
  /**
11126
   * A mapping can have one of the three levels of data:
11127
   *
11128
   *   1. Just the generated position.
11129
   *   2. The Generated position, original position, and original source.
11130
   *   3. Generated and original position, original source, as well as a name
11131
   *      token.
11132
   *
11133
   * To maintain consistency, we validate that any new mapping being added falls
11134
   * in to one of these categories.
11135
   */
11136
  SourceMapGenerator.prototype._validateMapping =
11137
    function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource,
11138
                                                aName) {
11139
      if (aGenerated && 'line' in aGenerated && 'column' in aGenerated
11140
          && aGenerated.line > 0 && aGenerated.column >= 0
11141
          && !aOriginal && !aSource && !aName) {
11142
        // Case 1.
11143
        return;
0 ignored issues
show
Unused Code introduced by
This return has no effect and can be removed.
Loading history...
11144
      }
11145
      else if (aGenerated && 'line' in aGenerated && 'column' in aGenerated
11146
               && aOriginal && 'line' in aOriginal && 'column' in aOriginal
11147
               && aGenerated.line > 0 && aGenerated.column >= 0
11148
               && aOriginal.line > 0 && aOriginal.column >= 0
11149
               && aSource) {
11150
        // Cases 2 and 3.
11151
        return;
0 ignored issues
show
Unused Code introduced by
This return has no effect and can be removed.
Loading history...
11152
      }
11153
      else {
11154
        throw new Error('Invalid mapping: ' + JSON.stringify({
11155
          generated: aGenerated,
11156
          source: aSource,
11157
          orginal: aOriginal,
11158
          name: aName
11159
        }));
11160
      }
11161
    };
11162
11163
  /**
11164
   * Serialize the accumulated mappings in to the stream of base 64 VLQs
11165
   * specified by the source map format.
11166
   */
11167
  SourceMapGenerator.prototype._serializeMappings =
11168
    function SourceMapGenerator_serializeMappings() {
11169
      var previousGeneratedColumn = 0;
11170
      var previousGeneratedLine = 1;
11171
      var previousOriginalColumn = 0;
11172
      var previousOriginalLine = 0;
11173
      var previousName = 0;
11174
      var previousSource = 0;
11175
      var result = '';
11176
      var mapping;
11177
11178
      // The mappings must be guaranteed to be in sorted order before we start
11179
      // serializing them or else the generated line numbers (which are defined
11180
      // via the ';' separators) will be all messed up. Note: it might be more
11181
      // performant to maintain the sorting as we insert them, rather than as we
11182
      // serialize them, but the big O is the same either way.
11183
      this._mappings.sort(util.compareByGeneratedPositions);
11184
11185
      for (var i = 0, len = this._mappings.length; i < len; i++) {
11186
        mapping = this._mappings[i];
11187
11188
        if (mapping.generatedLine !== previousGeneratedLine) {
11189
          previousGeneratedColumn = 0;
11190
          while (mapping.generatedLine !== previousGeneratedLine) {
11191
            result += ';';
11192
            previousGeneratedLine++;
11193
          }
11194
        }
11195
        else {
11196
          if (i > 0) {
11197
            if (!util.compareByGeneratedPositions(mapping, this._mappings[i - 1])) {
11198
              continue;
11199
            }
11200
            result += ',';
11201
          }
11202
        }
11203
11204
        result += base64VLQ.encode(mapping.generatedColumn
11205
                                   - previousGeneratedColumn);
11206
        previousGeneratedColumn = mapping.generatedColumn;
11207
11208
        if (mapping.source) {
11209
          result += base64VLQ.encode(this._sources.indexOf(mapping.source)
11210
                                     - previousSource);
11211
          previousSource = this._sources.indexOf(mapping.source);
11212
11213
          // lines are stored 0-based in SourceMap spec version 3
11214
          result += base64VLQ.encode(mapping.originalLine - 1
11215
                                     - previousOriginalLine);
11216
          previousOriginalLine = mapping.originalLine - 1;
11217
11218
          result += base64VLQ.encode(mapping.originalColumn
11219
                                     - previousOriginalColumn);
11220
          previousOriginalColumn = mapping.originalColumn;
11221
11222
          if (mapping.name) {
11223
            result += base64VLQ.encode(this._names.indexOf(mapping.name)
11224
                                       - previousName);
11225
            previousName = this._names.indexOf(mapping.name);
11226
          }
11227
        }
11228
      }
11229
11230
      return result;
11231
    };
11232
11233
  SourceMapGenerator.prototype._generateSourcesContent =
11234
    function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) {
11235
      return aSources.map(function (source) {
11236
        if (!this._sourcesContents) {
11237
          return null;
11238
        }
11239
        if (aSourceRoot) {
11240
          source = util.relative(aSourceRoot, source);
11241
        }
11242
        var key = util.toSetString(source);
11243
        return Object.prototype.hasOwnProperty.call(this._sourcesContents,
11244
                                                    key)
11245
          ? this._sourcesContents[key]
11246
          : null;
11247
      }, this);
11248
    };
11249
11250
  /**
11251
   * Externalize the source map.
11252
   */
11253
  SourceMapGenerator.prototype.toJSON =
11254
    function SourceMapGenerator_toJSON() {
11255
      var map = {
11256
        version: this._version,
11257
        file: this._file,
11258
        sources: this._sources.toArray(),
11259
        names: this._names.toArray(),
11260
        mappings: this._serializeMappings()
11261
      };
11262
      if (this._sourceRoot) {
11263
        map.sourceRoot = this._sourceRoot;
11264
      }
11265
      if (this._sourcesContents) {
11266
        map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot);
11267
      }
11268
11269
      return map;
11270
    };
11271
11272
  /**
11273
   * Render the source map being generated to a string.
11274
   */
11275
  SourceMapGenerator.prototype.toString =
11276
    function SourceMapGenerator_toString() {
11277
      return JSON.stringify(this);
11278
    };
11279
11280
  exports.SourceMapGenerator = SourceMapGenerator;
11281
11282
});
11283
11284
},{"./array-set":12,"./base64-vlq":13,"./util":19,"amdefine":20}],18:[function(_dereq_,module,exports){
0 ignored issues
show
Unused Code introduced by
The parameter exports is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
11285
/* -*- Mode: js; js-indent-level: 2; -*- */
11286
/*
11287
 * Copyright 2011 Mozilla Foundation and contributors
11288
 * Licensed under the New BSD license. See LICENSE or:
11289
 * http://opensource.org/licenses/BSD-3-Clause
11290
 */
11291
if (typeof define !== 'function') {
0 ignored issues
show
Bug introduced by
The variable define seems to be never initialized.
Loading history...
11292
    var define = _dereq_('amdefine')(module, _dereq_);
11293
}
11294
define(function (_dereq_, exports, module) {
0 ignored issues
show
Unused Code introduced by
The parameter module is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
11295
11296
  var SourceMapGenerator = _dereq_('./source-map-generator').SourceMapGenerator;
11297
  var util = _dereq_('./util');
11298
11299
  /**
11300
   * SourceNodes provide a way to abstract over interpolating/concatenating
11301
   * snippets of generated JavaScript source code while maintaining the line and
11302
   * column information associated with the original source code.
11303
   *
11304
   * @param aLine The original line number.
11305
   * @param aColumn The original column number.
11306
   * @param aSource The original source's filename.
11307
   * @param aChunks Optional. An array of strings which are snippets of
11308
   *        generated JS, or other SourceNodes.
11309
   * @param aName The original identifier.
11310
   */
11311
  function SourceNode(aLine, aColumn, aSource, aChunks, aName) {
11312
    this.children = [];
11313
    this.sourceContents = {};
11314
    this.line = aLine === undefined ? null : aLine;
11315
    this.column = aColumn === undefined ? null : aColumn;
11316
    this.source = aSource === undefined ? null : aSource;
11317
    this.name = aName === undefined ? null : aName;
11318
    if (aChunks != null) this.add(aChunks);
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
11319
  }
11320
11321
  /**
11322
   * Creates a SourceNode from generated code and a SourceMapConsumer.
11323
   *
11324
   * @param aGeneratedCode The generated code
11325
   * @param aSourceMapConsumer The SourceMap for the generated code
11326
   */
11327
  SourceNode.fromStringWithSourceMap =
11328
    function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer) {
11329
      // The SourceNode we want to fill with the generated code
11330
      // and the SourceMap
11331
      var node = new SourceNode();
11332
11333
      // The generated code
11334
      // Processed fragments are removed from this array.
11335
      var remainingLines = aGeneratedCode.split('\n');
11336
11337
      // We need to remember the position of "remainingLines"
11338
      var lastGeneratedLine = 1, lastGeneratedColumn = 0;
11339
11340
      // The generate SourceNodes we need a code range.
11341
      // To extract it current and last mapping is used.
11342
      // Here we store the last mapping.
11343
      var lastMapping = null;
11344
11345
      aSourceMapConsumer.eachMapping(function (mapping) {
11346
        if (lastMapping === null) {
11347
          // We add the generated code until the first mapping
11348
          // to the SourceNode without any mapping.
11349
          // Each line is added as separate string.
11350
          while (lastGeneratedLine < mapping.generatedLine) {
0 ignored issues
show
Bug introduced by
The variable lastGeneratedLine is changed as part of the while loop for example by lastGeneratedLine++ on line 11352. Only the value of the last iteration will be visible in this function if it is called after the loop.
Loading history...
11351
            node.add(remainingLines.shift() + "\n");
11352
            lastGeneratedLine++;
11353
          }
11354
          if (lastGeneratedColumn < mapping.generatedColumn) {
11355
            var nextLine = remainingLines[0];
11356
            node.add(nextLine.substr(0, mapping.generatedColumn));
11357
            remainingLines[0] = nextLine.substr(mapping.generatedColumn);
11358
            lastGeneratedColumn = mapping.generatedColumn;
11359
          }
11360
        } else {
11361
          // We add the code from "lastMapping" to "mapping":
11362
          // First check if there is a new line in between.
11363
          if (lastGeneratedLine < mapping.generatedLine) {
11364
            var code = "";
11365
            // Associate full lines with "lastMapping"
11366
            do {
11367
              code += remainingLines.shift() + "\n";
11368
              lastGeneratedLine++;
11369
              lastGeneratedColumn = 0;
11370
            } while (lastGeneratedLine < mapping.generatedLine);
11371
            // When we reached the correct line, we add code until we
11372
            // reach the correct column too.
11373
            if (lastGeneratedColumn < mapping.generatedColumn) {
11374
              var nextLine = remainingLines[0];
0 ignored issues
show
Comprehensibility Naming Best Practice introduced by
The variable nextLine already seems to be declared on line 11355. Consider using another variable name or omitting the var keyword.

This check looks for variables that are declared in multiple lines. There may be several reasons for this.

In the simplest case the variable name was reused by mistake. This may lead to very hard to locate bugs.

If you want to reuse a variable for another purpose, consider declaring it at or near the top of your function and just assigning to it subsequently so it is always declared.

Loading history...
11375
              code += nextLine.substr(0, mapping.generatedColumn);
11376
              remainingLines[0] = nextLine.substr(mapping.generatedColumn);
11377
              lastGeneratedColumn = mapping.generatedColumn;
11378
            }
11379
            // Create the SourceNode.
11380
            addMappingWithCode(lastMapping, code);
11381
          } else {
11382
            // There is no new line in between.
11383
            // Associate the code between "lastGeneratedColumn" and
11384
            // "mapping.generatedColumn" with "lastMapping"
11385
            var nextLine = remainingLines[0];
0 ignored issues
show
Comprehensibility Naming Best Practice introduced by
The variable nextLine already seems to be declared on line 11355. Consider using another variable name or omitting the var keyword.

This check looks for variables that are declared in multiple lines. There may be several reasons for this.

In the simplest case the variable name was reused by mistake. This may lead to very hard to locate bugs.

If you want to reuse a variable for another purpose, consider declaring it at or near the top of your function and just assigning to it subsequently so it is always declared.

Loading history...
11386
            var code = nextLine.substr(0, mapping.generatedColumn -
0 ignored issues
show
Comprehensibility Naming Best Practice introduced by
The variable code already seems to be declared on line 11364. Consider using another variable name or omitting the var keyword.

This check looks for variables that are declared in multiple lines. There may be several reasons for this.

In the simplest case the variable name was reused by mistake. This may lead to very hard to locate bugs.

If you want to reuse a variable for another purpose, consider declaring it at or near the top of your function and just assigning to it subsequently so it is always declared.

Loading history...
11387
                                          lastGeneratedColumn);
11388
            remainingLines[0] = nextLine.substr(mapping.generatedColumn -
11389
                                                lastGeneratedColumn);
11390
            lastGeneratedColumn = mapping.generatedColumn;
11391
            addMappingWithCode(lastMapping, code);
11392
          }
11393
        }
11394
        lastMapping = mapping;
11395
      }, this);
11396
      // We have processed all mappings.
11397
      // Associate the remaining code in the current line with "lastMapping"
11398
      // and add the remaining lines without any mapping
11399
      addMappingWithCode(lastMapping, remainingLines.join("\n"));
11400
11401
      // Copy sourcesContent into SourceNode
11402
      aSourceMapConsumer.sources.forEach(function (sourceFile) {
11403
        var content = aSourceMapConsumer.sourceContentFor(sourceFile);
11404
        if (content) {
11405
          node.setSourceContent(sourceFile, content);
11406
        }
11407
      });
11408
11409
      return node;
11410
11411
      function addMappingWithCode(mapping, code) {
11412
        if (mapping === null || mapping.source === undefined) {
11413
          node.add(code);
11414
        } else {
11415
          node.add(new SourceNode(mapping.originalLine,
11416
                                  mapping.originalColumn,
11417
                                  mapping.source,
11418
                                  code,
11419
                                  mapping.name));
11420
        }
11421
      }
11422
    };
11423
11424
  /**
11425
   * Add a chunk of generated JS to this source node.
11426
   *
11427
   * @param aChunk A string snippet of generated JS code, another instance of
11428
   *        SourceNode, or an array where each member is one of those things.
11429
   */
11430
  SourceNode.prototype.add = function SourceNode_add(aChunk) {
11431
    if (Array.isArray(aChunk)) {
11432
      aChunk.forEach(function (chunk) {
11433
        this.add(chunk);
11434
      }, this);
11435
    }
11436
    else if (aChunk instanceof SourceNode || typeof aChunk === "string") {
11437
      if (aChunk) {
11438
        this.children.push(aChunk);
11439
      }
11440
    }
11441
    else {
11442
      throw new TypeError(
11443
        "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk
11444
      );
11445
    }
11446
    return this;
11447
  };
11448
11449
  /**
11450
   * Add a chunk of generated JS to the beginning of this source node.
11451
   *
11452
   * @param aChunk A string snippet of generated JS code, another instance of
11453
   *        SourceNode, or an array where each member is one of those things.
11454
   */
11455
  SourceNode.prototype.prepend = function SourceNode_prepend(aChunk) {
11456
    if (Array.isArray(aChunk)) {
11457
      for (var i = aChunk.length-1; i >= 0; i--) {
11458
        this.prepend(aChunk[i]);
11459
      }
11460
    }
11461
    else if (aChunk instanceof SourceNode || typeof aChunk === "string") {
11462
      this.children.unshift(aChunk);
11463
    }
11464
    else {
11465
      throw new TypeError(
11466
        "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk
11467
      );
11468
    }
11469
    return this;
11470
  };
11471
11472
  /**
11473
   * Walk over the tree of JS snippets in this node and its children. The
11474
   * walking function is called once for each snippet of JS and is passed that
11475
   * snippet and the its original associated source's line/column location.
11476
   *
11477
   * @param aFn The traversal function.
11478
   */
11479
  SourceNode.prototype.walk = function SourceNode_walk(aFn) {
11480
    var chunk;
11481
    for (var i = 0, len = this.children.length; i < len; i++) {
11482
      chunk = this.children[i];
11483
      if (chunk instanceof SourceNode) {
11484
        chunk.walk(aFn);
11485
      }
11486
      else {
11487
        if (chunk !== '') {
11488
          aFn(chunk, { source: this.source,
11489
                       line: this.line,
11490
                       column: this.column,
11491
                       name: this.name });
11492
        }
11493
      }
11494
    }
11495
  };
11496
11497
  /**
11498
   * Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between
11499
   * each of `this.children`.
11500
   *
11501
   * @param aSep The separator.
11502
   */
11503
  SourceNode.prototype.join = function SourceNode_join(aSep) {
11504
    var newChildren;
11505
    var i;
11506
    var len = this.children.length;
11507
    if (len > 0) {
11508
      newChildren = [];
11509
      for (i = 0; i < len-1; i++) {
11510
        newChildren.push(this.children[i]);
11511
        newChildren.push(aSep);
11512
      }
11513
      newChildren.push(this.children[i]);
11514
      this.children = newChildren;
11515
    }
11516
    return this;
11517
  };
11518
11519
  /**
11520
   * Call String.prototype.replace on the very right-most source snippet. Useful
11521
   * for trimming whitespace from the end of a source node, etc.
11522
   *
11523
   * @param aPattern The pattern to replace.
11524
   * @param aReplacement The thing to replace the pattern with.
11525
   */
11526
  SourceNode.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) {
11527
    var lastChild = this.children[this.children.length - 1];
11528
    if (lastChild instanceof SourceNode) {
11529
      lastChild.replaceRight(aPattern, aReplacement);
11530
    }
11531
    else if (typeof lastChild === 'string') {
11532
      this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement);
11533
    }
11534
    else {
11535
      this.children.push(''.replace(aPattern, aReplacement));
11536
    }
11537
    return this;
11538
  };
11539
11540
  /**
11541
   * Set the source content for a source file. This will be added to the SourceMapGenerator
11542
   * in the sourcesContent field.
11543
   *
11544
   * @param aSourceFile The filename of the source file
11545
   * @param aSourceContent The content of the source file
11546
   */
11547
  SourceNode.prototype.setSourceContent =
11548
    function SourceNode_setSourceContent(aSourceFile, aSourceContent) {
11549
      this.sourceContents[util.toSetString(aSourceFile)] = aSourceContent;
11550
    };
11551
11552
  /**
11553
   * Walk over the tree of SourceNodes. The walking function is called for each
11554
   * source file content and is passed the filename and source content.
11555
   *
11556
   * @param aFn The traversal function.
11557
   */
11558
  SourceNode.prototype.walkSourceContents =
11559
    function SourceNode_walkSourceContents(aFn) {
11560
      for (var i = 0, len = this.children.length; i < len; i++) {
11561
        if (this.children[i] instanceof SourceNode) {
11562
          this.children[i].walkSourceContents(aFn);
11563
        }
11564
      }
11565
11566
      var sources = Object.keys(this.sourceContents);
11567
      for (var i = 0, len = sources.length; i < len; i++) {
0 ignored issues
show
Comprehensibility Naming Best Practice introduced by
The variable len already seems to be declared on line 11560. Consider using another variable name or omitting the var keyword.

This check looks for variables that are declared in multiple lines. There may be several reasons for this.

In the simplest case the variable name was reused by mistake. This may lead to very hard to locate bugs.

If you want to reuse a variable for another purpose, consider declaring it at or near the top of your function and just assigning to it subsequently so it is always declared.

Loading history...
Comprehensibility Naming Best Practice introduced by
The variable i already seems to be declared on line 11560. Consider using another variable name or omitting the var keyword.

This check looks for variables that are declared in multiple lines. There may be several reasons for this.

In the simplest case the variable name was reused by mistake. This may lead to very hard to locate bugs.

If you want to reuse a variable for another purpose, consider declaring it at or near the top of your function and just assigning to it subsequently so it is always declared.

Loading history...
11568
        aFn(util.fromSetString(sources[i]), this.sourceContents[sources[i]]);
11569
      }
11570
    };
11571
11572
  /**
11573
   * Return the string representation of this source node. Walks over the tree
11574
   * and concatenates all the various snippets together to one string.
11575
   */
11576
  SourceNode.prototype.toString = function SourceNode_toString() {
11577
    var str = "";
11578
    this.walk(function (chunk) {
11579
      str += chunk;
11580
    });
11581
    return str;
11582
  };
11583
11584
  /**
11585
   * Returns the string representation of this source node along with a source
11586
   * map.
11587
   */
11588
  SourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) {
11589
    var generated = {
11590
      code: "",
11591
      line: 1,
11592
      column: 0
11593
    };
11594
    var map = new SourceMapGenerator(aArgs);
11595
    var sourceMappingActive = false;
11596
    var lastOriginalSource = null;
11597
    var lastOriginalLine = null;
11598
    var lastOriginalColumn = null;
11599
    var lastOriginalName = null;
11600
    this.walk(function (chunk, original) {
11601
      generated.code += chunk;
11602
      if (original.source !== null
11603
          && original.line !== null
11604
          && original.column !== null) {
11605
        if(lastOriginalSource !== original.source
11606
           || lastOriginalLine !== original.line
11607
           || lastOriginalColumn !== original.column
11608
           || lastOriginalName !== original.name) {
11609
          map.addMapping({
11610
            source: original.source,
11611
            original: {
11612
              line: original.line,
11613
              column: original.column
11614
            },
11615
            generated: {
11616
              line: generated.line,
11617
              column: generated.column
11618
            },
11619
            name: original.name
11620
          });
11621
        }
11622
        lastOriginalSource = original.source;
11623
        lastOriginalLine = original.line;
11624
        lastOriginalColumn = original.column;
11625
        lastOriginalName = original.name;
11626
        sourceMappingActive = true;
11627
      } else if (sourceMappingActive) {
11628
        map.addMapping({
11629
          generated: {
11630
            line: generated.line,
11631
            column: generated.column
11632
          }
11633
        });
11634
        lastOriginalSource = null;
11635
        sourceMappingActive = false;
11636
      }
11637
      chunk.split('').forEach(function (ch) {
11638
        if (ch === '\n') {
11639
          generated.line++;
11640
          generated.column = 0;
11641
        } else {
11642
          generated.column++;
11643
        }
11644
      });
11645
    });
11646
    this.walkSourceContents(function (sourceFile, sourceContent) {
11647
      map.setSourceContent(sourceFile, sourceContent);
11648
    });
11649
11650
    return { code: generated.code, map: map };
11651
  };
11652
11653
  exports.SourceNode = SourceNode;
11654
11655
});
11656
11657
},{"./source-map-generator":17,"./util":19,"amdefine":20}],19:[function(_dereq_,module,exports){
0 ignored issues
show
Unused Code introduced by
The parameter exports is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
11658
/* -*- Mode: js; js-indent-level: 2; -*- */
11659
/*
11660
 * Copyright 2011 Mozilla Foundation and contributors
11661
 * Licensed under the New BSD license. See LICENSE or:
11662
 * http://opensource.org/licenses/BSD-3-Clause
11663
 */
11664
if (typeof define !== 'function') {
0 ignored issues
show
Bug introduced by
The variable define seems to be never initialized.
Loading history...
11665
    var define = _dereq_('amdefine')(module, _dereq_);
11666
}
11667
define(function (_dereq_, exports, module) {
0 ignored issues
show
Unused Code introduced by
The parameter module is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
11668
11669
  /**
11670
   * This is a helper function for getting values from parameter/options
11671
   * objects.
11672
   *
11673
   * @param args The object we are extracting values from
0 ignored issues
show
Documentation Bug introduced by
The parameter args does not exist. Did you maybe mean aArgs instead?
Loading history...
11674
   * @param name The name of the property we are getting.
0 ignored issues
show
Documentation introduced by
The parameter name does not exist. Did you maybe forget to remove this comment?
Loading history...
11675
   * @param defaultValue An optional value to return if the property is missing
0 ignored issues
show
Documentation introduced by
The parameter defaultValue does not exist. Did you maybe forget to remove this comment?
Loading history...
11676
   * from the object. If this is not specified and the property is missing, an
11677
   * error will be thrown.
11678
   */
11679
  function getArg(aArgs, aName, aDefaultValue) {
11680
    if (aName in aArgs) {
11681
      return aArgs[aName];
11682
    } else if (arguments.length === 3) {
11683
      return aDefaultValue;
11684
    } else {
11685
      throw new Error('"' + aName + '" is a required argument.');
11686
    }
11687
  }
11688
  exports.getArg = getArg;
11689
11690
  var urlRegexp = /([\w+\-.]+):\/\/((\w+:\w+)@)?([\w.]+)?(:(\d+))?(\S+)?/;
11691
  var dataUrlRegexp = /^data:.+\,.+/;
11692
11693
  function urlParse(aUrl) {
11694
    var match = aUrl.match(urlRegexp);
11695
    if (!match) {
11696
      return null;
11697
    }
11698
    return {
11699
      scheme: match[1],
11700
      auth: match[3],
11701
      host: match[4],
11702
      port: match[6],
11703
      path: match[7]
11704
    };
11705
  }
11706
  exports.urlParse = urlParse;
11707
11708
  function urlGenerate(aParsedUrl) {
11709
    var url = aParsedUrl.scheme + "://";
11710
    if (aParsedUrl.auth) {
11711
      url += aParsedUrl.auth + "@"
11712
    }
11713
    if (aParsedUrl.host) {
11714
      url += aParsedUrl.host;
11715
    }
11716
    if (aParsedUrl.port) {
11717
      url += ":" + aParsedUrl.port
11718
    }
11719
    if (aParsedUrl.path) {
11720
      url += aParsedUrl.path;
11721
    }
11722
    return url;
11723
  }
11724
  exports.urlGenerate = urlGenerate;
11725
11726
  function join(aRoot, aPath) {
11727
    var url;
11728
11729
    if (aPath.match(urlRegexp) || aPath.match(dataUrlRegexp)) {
11730
      return aPath;
11731
    }
11732
11733
    if (aPath.charAt(0) === '/' && (url = urlParse(aRoot))) {
11734
      url.path = aPath;
11735
      return urlGenerate(url);
11736
    }
11737
11738
    return aRoot.replace(/\/$/, '') + '/' + aPath;
11739
  }
11740
  exports.join = join;
11741
11742
  /**
11743
   * Because behavior goes wacky when you set `__proto__` on objects, we
11744
   * have to prefix all the strings in our set with an arbitrary character.
11745
   *
11746
   * See https://github.com/mozilla/source-map/pull/31 and
11747
   * https://github.com/mozilla/source-map/issues/30
11748
   *
11749
   * @param String aStr
0 ignored issues
show
Documentation introduced by
The parameter String does not exist. Did you maybe forget to remove this comment?
Loading history...
11750
   */
11751
  function toSetString(aStr) {
11752
    return '$' + aStr;
11753
  }
11754
  exports.toSetString = toSetString;
11755
11756
  function fromSetString(aStr) {
11757
    return aStr.substr(1);
11758
  }
11759
  exports.fromSetString = fromSetString;
11760
11761
  function relative(aRoot, aPath) {
11762
    aRoot = aRoot.replace(/\/$/, '');
11763
11764
    var url = urlParse(aRoot);
11765
    if (aPath.charAt(0) == "/" && url && url.path == "/") {
11766
      return aPath.slice(1);
11767
    }
11768
11769
    return aPath.indexOf(aRoot + '/') === 0
11770
      ? aPath.substr(aRoot.length + 1)
11771
      : aPath;
11772
  }
11773
  exports.relative = relative;
11774
11775
  function strcmp(aStr1, aStr2) {
11776
    var s1 = aStr1 || "";
11777
    var s2 = aStr2 || "";
11778
    return (s1 > s2) - (s1 < s2);
11779
  }
11780
11781
  /**
11782
   * Comparator between two mappings where the original positions are compared.
11783
   *
11784
   * Optionally pass in `true` as `onlyCompareGenerated` to consider two
11785
   * mappings with the same original source/line/column, but different generated
11786
   * line and column the same. Useful when searching for a mapping with a
11787
   * stubbed out mapping.
11788
   */
11789
  function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) {
11790
    var cmp;
11791
11792
    cmp = strcmp(mappingA.source, mappingB.source);
11793
    if (cmp) {
11794
      return cmp;
11795
    }
11796
11797
    cmp = mappingA.originalLine - mappingB.originalLine;
11798
    if (cmp) {
11799
      return cmp;
11800
    }
11801
11802
    cmp = mappingA.originalColumn - mappingB.originalColumn;
11803
    if (cmp || onlyCompareOriginal) {
11804
      return cmp;
11805
    }
11806
11807
    cmp = strcmp(mappingA.name, mappingB.name);
11808
    if (cmp) {
11809
      return cmp;
11810
    }
11811
11812
    cmp = mappingA.generatedLine - mappingB.generatedLine;
11813
    if (cmp) {
11814
      return cmp;
11815
    }
11816
11817
    return mappingA.generatedColumn - mappingB.generatedColumn;
11818
  };
11819
  exports.compareByOriginalPositions = compareByOriginalPositions;
11820
11821
  /**
11822
   * Comparator between two mappings where the generated positions are
11823
   * compared.
11824
   *
11825
   * Optionally pass in `true` as `onlyCompareGenerated` to consider two
11826
   * mappings with the same generated line and column, but different
11827
   * source/name/original line and column the same. Useful when searching for a
11828
   * mapping with a stubbed out mapping.
11829
   */
11830
  function compareByGeneratedPositions(mappingA, mappingB, onlyCompareGenerated) {
11831
    var cmp;
11832
11833
    cmp = mappingA.generatedLine - mappingB.generatedLine;
11834
    if (cmp) {
11835
      return cmp;
11836
    }
11837
11838
    cmp = mappingA.generatedColumn - mappingB.generatedColumn;
11839
    if (cmp || onlyCompareGenerated) {
11840
      return cmp;
11841
    }
11842
11843
    cmp = strcmp(mappingA.source, mappingB.source);
11844
    if (cmp) {
11845
      return cmp;
11846
    }
11847
11848
    cmp = mappingA.originalLine - mappingB.originalLine;
11849
    if (cmp) {
11850
      return cmp;
11851
    }
11852
11853
    cmp = mappingA.originalColumn - mappingB.originalColumn;
11854
    if (cmp) {
11855
      return cmp;
11856
    }
11857
11858
    return strcmp(mappingA.name, mappingB.name);
11859
  };
11860
  exports.compareByGeneratedPositions = compareByGeneratedPositions;
11861
11862
});
11863
11864
},{"amdefine":20}],20:[function(_dereq_,module,exports){
11865
(function (process,__filename){
11866
/** vim: et:ts=4:sw=4:sts=4
11867
 * @license amdefine 0.1.0 Copyright (c) 2011, The Dojo Foundation All Rights Reserved.
11868
 * Available via the MIT or new BSD license.
11869
 * see: http://github.com/jrburke/amdefine for details
11870
 */
11871
11872
/*jslint node: true */
11873
/*global module, process */
11874
'use strict';
11875
11876
/**
11877
 * Creates a define for node.
11878
 * @param {Object} module the "module" object that is defined by Node for the
11879
 * current module.
11880
 * @param {Function} [requireFn]. Node's require function for the current module.
0 ignored issues
show
Documentation Bug introduced by
The parameter [requireFn]. does not exist. Did you maybe mean requireFn instead?
Loading history...
11881
 * It only needs to be passed in Node versions before 0.5, when module.require
11882
 * did not exist.
11883
 * @returns {Function} a define function that is usable for the current node
11884
 * module.
11885
 */
11886
function amdefine(module, requireFn) {
11887
    'use strict';
11888
    var defineCache = {},
11889
        loaderCache = {},
11890
        alreadyCalled = false,
11891
        path = _dereq_('path'),
11892
        makeRequire, stringRequire;
11893
11894
    /**
11895
     * Trims the . and .. from an array of path segments.
11896
     * It will keep a leading path segment if a .. will become
11897
     * the first path segment, to help with module name lookups,
11898
     * which act like paths, but can be remapped. But the end result,
11899
     * all paths that use this function should look normalized.
11900
     * NOTE: this method MODIFIES the input array.
11901
     * @param {Array} ary the array of path segments.
11902
     */
11903
    function trimDots(ary) {
11904
        var i, part;
11905
        for (i = 0; ary[i]; i+= 1) {
11906
            part = ary[i];
11907
            if (part === '.') {
11908
                ary.splice(i, 1);
11909
                i -= 1;
11910
            } else if (part === '..') {
11911
                if (i === 1 && (ary[2] === '..' || ary[0] === '..')) {
11912
                    //End of the line. Keep at least one non-dot
11913
                    //path segment at the front so it can be mapped
11914
                    //correctly to disk. Otherwise, there is likely
11915
                    //no path mapping for a path starting with '..'.
11916
                    //This can still fail, but catches the most reasonable
11917
                    //uses of ..
11918
                    break;
11919
                } else if (i > 0) {
11920
                    ary.splice(i - 1, 2);
11921
                    i -= 2;
11922
                }
11923
            }
11924
        }
11925
    }
11926
11927
    function normalize(name, baseName) {
11928
        var baseParts;
11929
11930
        //Adjust any relative paths.
11931
        if (name && name.charAt(0) === '.') {
11932
            //If have a base name, try to normalize against it,
11933
            //otherwise, assume it is a top-level require that will
11934
            //be relative to baseUrl in the end.
11935
            if (baseName) {
11936
                baseParts = baseName.split('/');
11937
                baseParts = baseParts.slice(0, baseParts.length - 1);
11938
                baseParts = baseParts.concat(name.split('/'));
11939
                trimDots(baseParts);
11940
                name = baseParts.join('/');
11941
            }
11942
        }
11943
11944
        return name;
11945
    }
11946
11947
    /**
11948
     * Create the normalize() function passed to a loader plugin's
11949
     * normalize method.
11950
     */
11951
    function makeNormalize(relName) {
11952
        return function (name) {
11953
            return normalize(name, relName);
11954
        };
11955
    }
11956
11957
    function makeLoad(id) {
11958
        function load(value) {
11959
            loaderCache[id] = value;
11960
        }
11961
11962
        load.fromText = function (id, text) {
0 ignored issues
show
Unused Code introduced by
The parameter id is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
Unused Code introduced by
The parameter text is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
11963
            //This one is difficult because the text can/probably uses
11964
            //define, and any relative paths and requires should be relative
11965
            //to that id was it would be found on disk. But this would require
11966
            //bootstrapping a module/require fairly deeply from node core.
11967
            //Not sure how best to go about that yet.
11968
            throw new Error('amdefine does not implement load.fromText');
11969
        };
11970
11971
        return load;
11972
    }
11973
11974
    makeRequire = function (systemRequire, exports, module, relId) {
11975
        function amdRequire(deps, callback) {
11976
            if (typeof deps === 'string') {
11977
                //Synchronous, single module require('')
11978
                return stringRequire(systemRequire, exports, module, deps, relId);
11979
            } else {
11980
                //Array of dependencies with a callback.
11981
11982
                //Convert the dependencies to modules.
11983
                deps = deps.map(function (depName) {
11984
                    return stringRequire(systemRequire, exports, module, depName, relId);
11985
                });
11986
11987
                //Wait for next tick to call back the require call.
11988
                process.nextTick(function () {
11989
                    callback.apply(null, deps);
11990
                });
0 ignored issues
show
Best Practice introduced by
There is no return statement in this branch, but you do return something in other branches. Did you maybe miss it? If you do not want to return anything, consider adding return undefined; explicitly.
Loading history...
11991
            }
11992
        }
11993
11994
        amdRequire.toUrl = function (filePath) {
11995
            if (filePath.indexOf('.') === 0) {
11996
                return normalize(filePath, path.dirname(module.filename));
11997
            } else {
11998
                return filePath;
11999
            }
12000
        };
12001
12002
        return amdRequire;
12003
    };
12004
12005
    //Favor explicit value, passed in if the module wants to support Node 0.4.
12006
    requireFn = requireFn || function req() {
12007
        return module.require.apply(module, arguments);
12008
    };
12009
12010
    function runFactory(id, deps, factory) {
12011
        var r, e, m, result;
12012
12013
        if (id) {
12014
            e = loaderCache[id] = {};
12015
            m = {
12016
                id: id,
12017
                uri: __filename,
12018
                exports: e
12019
            };
12020
            r = makeRequire(requireFn, e, m, id);
12021
        } else {
12022
            //Only support one define call per file
12023
            if (alreadyCalled) {
12024
                throw new Error('amdefine with no module ID cannot be called more than once per file.');
12025
            }
12026
            alreadyCalled = true;
12027
12028
            //Use the real variables from node
12029
            //Use module.exports for exports, since
12030
            //the exports in here is amdefine exports.
12031
            e = module.exports;
12032
            m = module;
12033
            r = makeRequire(requireFn, e, m, module.id);
12034
        }
12035
12036
        //If there are dependencies, they are strings, so need
12037
        //to convert them to dependency values.
12038
        if (deps) {
12039
            deps = deps.map(function (depName) {
12040
                return r(depName);
12041
            });
12042
        }
12043
12044
        //Call the factory with the right dependencies.
12045
        if (typeof factory === 'function') {
12046
            result = factory.apply(m.exports, deps);
12047
        } else {
12048
            result = factory;
12049
        }
12050
12051
        if (result !== undefined) {
12052
            m.exports = result;
12053
            if (id) {
12054
                loaderCache[id] = m.exports;
12055
            }
12056
        }
12057
    }
12058
12059
    stringRequire = function (systemRequire, exports, module, id, relId) {
12060
        //Split the ID by a ! so that
12061
        var index = id.indexOf('!'),
12062
            originalId = id,
12063
            prefix, plugin;
12064
12065
        if (index === -1) {
12066
            id = normalize(id, relId);
12067
12068
            //Straight module lookup. If it is one of the special dependencies,
12069
            //deal with it, otherwise, delegate to node.
12070
            if (id === 'require') {
12071
                return makeRequire(systemRequire, exports, module, relId);
12072
            } else if (id === 'exports') {
12073
                return exports;
12074
            } else if (id === 'module') {
12075
                return module;
12076
            } else if (loaderCache.hasOwnProperty(id)) {
12077
                return loaderCache[id];
12078
            } else if (defineCache[id]) {
12079
                runFactory.apply(null, defineCache[id]);
12080
                return loaderCache[id];
12081
            } else {
12082
                if(systemRequire) {
12083
                    return systemRequire(originalId);
12084
                } else {
12085
                    throw new Error('No module with ID: ' + id);
12086
                }
12087
            }
12088
        } else {
12089
            //There is a plugin in play.
12090
            prefix = id.substring(0, index);
12091
            id = id.substring(index + 1, id.length);
12092
12093
            plugin = stringRequire(systemRequire, exports, module, prefix, relId);
12094
12095
            if (plugin.normalize) {
12096
                id = plugin.normalize(id, makeNormalize(relId));
12097
            } else {
12098
                //Normalize the ID normally.
12099
                id = normalize(id, relId);
12100
            }
12101
12102
            if (loaderCache[id]) {
12103
                return loaderCache[id];
12104
            } else {
12105
                plugin.load(id, makeRequire(systemRequire, exports, module, relId), makeLoad(id), {});
12106
12107
                return loaderCache[id];
12108
            }
12109
        }
12110
    };
12111
12112
    //Create a define function specific to the module asking for amdefine.
12113
    function define(id, deps, factory) {
12114
        if (Array.isArray(id)) {
12115
            factory = deps;
12116
            deps = id;
12117
            id = undefined;
12118
        } else if (typeof id !== 'string') {
12119
            factory = id;
12120
            id = deps = undefined;
12121
        }
12122
12123
        if (deps && !Array.isArray(deps)) {
12124
            factory = deps;
12125
            deps = undefined;
12126
        }
12127
12128
        if (!deps) {
12129
            deps = ['require', 'exports', 'module'];
12130
        }
12131
12132
        //Set up properties for this module. If an ID, then use
12133
        //internal cache. If no ID, then use the external variables
12134
        //for this node module.
12135
        if (id) {
12136
            //Put the module in deep freeze until there is a
12137
            //require call for it.
12138
            defineCache[id] = [id, deps, factory];
12139
        } else {
12140
            runFactory(id, deps, factory);
12141
        }
12142
    }
12143
12144
    //define.require, which has access to all the values in the
12145
    //cache. Useful for AMD modules that all have IDs in the file,
12146
    //but need to finally export a value to node based on one of those
12147
    //IDs.
12148
    define.require = function (id) {
12149
        if (loaderCache[id]) {
12150
            return loaderCache[id];
12151
        }
12152
12153
        if (defineCache[id]) {
0 ignored issues
show
Complexity Best Practice introduced by
There is no return statement if defineCache.id is false. Are you sure this is correct? If so, consider adding return; explicitly.

This check looks for functions where a return statement is found in some execution paths, but not in all.

Consider this little piece of code

function isBig(a) {
    if (a > 5000) {
        return "yes";
    }
}

console.log(isBig(5001)); //returns yes
console.log(isBig(42)); //returns undefined

The function isBig will only return a specific value when its parameter is bigger than 5000. In any other case, it will implicitly return undefined.

This behaviour may not be what you had intended. In any case, you can add a return undefined to the other execution path to make the return value explicit.

Loading history...
12154
            runFactory.apply(null, defineCache[id]);
12155
            return loaderCache[id];
12156
        }
12157
    };
12158
12159
    define.amd = {};
12160
12161
    return define;
12162
}
12163
12164
module.exports = amdefine;
12165
12166
}).call(this,_dereq_('_process'),"/node_modules/jstransform/node_modules/source-map/node_modules/amdefine/amdefine.js")
12167
},{"_process":8,"path":7}],21:[function(_dereq_,module,exports){
12168
/**
12169
 * Copyright 2013 Facebook, Inc.
12170
 *
12171
 * Licensed under the Apache License, Version 2.0 (the "License");
12172
 * you may not use this file except in compliance with the License.
12173
 * You may obtain a copy of the License at
12174
 *
12175
 * http://www.apache.org/licenses/LICENSE-2.0
12176
 *
12177
 * Unless required by applicable law or agreed to in writing, software
12178
 * distributed under the License is distributed on an "AS IS" BASIS,
12179
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12180
 * See the License for the specific language governing permissions and
12181
 * limitations under the License.
12182
 */
12183
12184
var docblockRe = /^\s*(\/\*\*(.|\r?\n)*?\*\/)/;
12185
var ltrimRe = /^\s*/;
12186
/**
12187
 * @param {String} contents
12188
 * @return {String}
12189
 */
12190
function extract(contents) {
12191
  var match = contents.match(docblockRe);
12192
  if (match) {
12193
    return match[0].replace(ltrimRe, '') || '';
12194
  }
12195
  return '';
12196
}
12197
12198
12199
var commentStartRe = /^\/\*\*?/;
12200
var commentEndRe = /\*+\/$/;
12201
var wsRe = /[\t ]+/g;
12202
var stringStartRe = /(\r?\n|^) *\*/g;
12203
var multilineRe = /(?:^|\r?\n) *(@[^\r\n]*?) *\r?\n *([^@\r\n\s][^@\r\n]+?) *\r?\n/g;
12204
var propertyRe = /(?:^|\r?\n) *@(\S+) *([^\r\n]*)/g;
12205
12206
/**
12207
 * @param {String} contents
0 ignored issues
show
Documentation introduced by
The parameter contents does not exist. Did you maybe forget to remove this comment?
Loading history...
12208
 * @return {Array}
12209
 */
12210
function parse(docblock) {
12211
  docblock = docblock
12212
    .replace(commentStartRe, '')
12213
    .replace(commentEndRe, '')
12214
    .replace(wsRe, ' ')
12215
    .replace(stringStartRe, '$1');
12216
12217
  // Normalize multi-line directives
12218
  var prev = '';
12219
  while (prev != docblock) {
12220
    prev = docblock;
12221
    docblock = docblock.replace(multilineRe, "\n$1 $2\n");
12222
  }
12223
  docblock = docblock.trim();
12224
12225
  var result = [];
12226
  var match;
12227
  while (match = propertyRe.exec(docblock)) {
12228
    result.push([match[1], match[2]]);
12229
  }
12230
12231
  return result;
12232
}
12233
12234
/**
12235
 * Same as parse but returns an object of prop: value instead of array of paris
12236
 * If a property appers more than once the last one will be returned
12237
 *
12238
 * @param {String} contents
0 ignored issues
show
Documentation introduced by
The parameter contents does not exist. Did you maybe forget to remove this comment?
Loading history...
12239
 * @return {Object}
12240
 */
12241
function parseAsObject(docblock) {
12242
  var pairs = parse(docblock);
12243
  var result = {};
12244
  for (var i = 0; i < pairs.length; i++) {
12245
    result[pairs[i][0]] = pairs[i][1];
12246
  }
12247
  return result;
12248
}
12249
12250
12251
exports.extract = extract;
12252
exports.parse = parse;
12253
exports.parseAsObject = parseAsObject;
12254
12255
},{}],22:[function(_dereq_,module,exports){
12256
/**
12257
 * Copyright 2013 Facebook, Inc.
12258
 *
12259
 * Licensed under the Apache License, Version 2.0 (the "License");
12260
 * you may not use this file except in compliance with the License.
12261
 * You may obtain a copy of the License at
12262
 *
12263
 * http://www.apache.org/licenses/LICENSE-2.0
12264
 *
12265
 * Unless required by applicable law or agreed to in writing, software
12266
 * distributed under the License is distributed on an "AS IS" BASIS,
12267
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12268
 * See the License for the specific language governing permissions and
12269
 * limitations under the License.
12270
 */
12271
12272
12273
/*jslint node: true*/
12274
"use strict";
12275
12276
var esprima = _dereq_('esprima-fb');
12277
var utils = _dereq_('./utils');
12278
12279
var getBoundaryNode = utils.getBoundaryNode;
12280
var declareIdentInScope = utils.declareIdentInLocalScope;
12281
var initScopeMetadata = utils.initScopeMetadata;
12282
var Syntax = esprima.Syntax;
12283
12284
/**
12285
 * @param {object} node
12286
 * @param {object} parentNode
12287
 * @return {boolean}
12288
 */
12289
function _nodeIsClosureScopeBoundary(node, parentNode) {
12290
  if (node.type === Syntax.Program) {
12291
    return true;
12292
  }
12293
12294
  var parentIsFunction =
12295
    parentNode.type === Syntax.FunctionDeclaration
12296
    || parentNode.type === Syntax.FunctionExpression
12297
    || parentNode.type === Syntax.ArrowFunctionExpression;
12298
12299
  var parentIsCurlylessArrowFunc =
12300
    parentNode.type === Syntax.ArrowFunctionExpression
12301
    && node === parentNode.body;
12302
12303
  return parentIsFunction
12304
         && (node.type === Syntax.BlockStatement || parentIsCurlylessArrowFunc);
12305
}
12306
12307
function _nodeIsBlockScopeBoundary(node, parentNode) {
12308
  if (node.type === Syntax.Program) {
12309
    return false;
12310
  }
12311
12312
  return node.type === Syntax.BlockStatement
12313
         && parentNode.type === Syntax.CatchClause;
12314
}
12315
12316
/**
12317
 * @param {object} node
12318
 * @param {array} path
12319
 * @param {object} state
12320
 */
12321
function traverse(node, path, state) {
12322
  /*jshint -W004*/
12323
  // Create a scope stack entry if this is the first node we've encountered in
12324
  // its local scope
12325
  var startIndex = null;
12326
  var parentNode = path[0];
12327
  if (!Array.isArray(node) && state.localScope.parentNode !== parentNode) {
12328
    if (_nodeIsClosureScopeBoundary(node, parentNode)) {
12329
      var scopeIsStrict = state.scopeIsStrict;
12330
      if (!scopeIsStrict
12331
          && (node.type === Syntax.BlockStatement
12332
              || node.type === Syntax.Program)) {
12333
          scopeIsStrict =
12334
            node.body.length > 0
12335
            && node.body[0].type === Syntax.ExpressionStatement
12336
            && node.body[0].expression.type === Syntax.Literal
12337
            && node.body[0].expression.value === 'use ' + 'strict';
12338
      }
12339
12340
      if (node.type === Syntax.Program) {
12341
        startIndex = state.g.buffer.length;
12342
        state = utils.updateState(state, {
12343
          scopeIsStrict: scopeIsStrict
12344
        });
12345
      } else {
12346
        startIndex = state.g.buffer.length + 1;
12347
        state = utils.updateState(state, {
12348
          localScope: {
12349
            parentNode: parentNode,
12350
            parentScope: state.localScope,
12351
            identifiers: {},
12352
            tempVarIndex: 0,
12353
            tempVars: []
12354
          },
12355
          scopeIsStrict: scopeIsStrict
12356
        });
12357
12358
        // All functions have an implicit 'arguments' object in scope
12359
        declareIdentInScope('arguments', initScopeMetadata(node), state);
12360
12361
        // Include function arg identifiers in the scope boundaries of the
12362
        // function
12363
        if (parentNode.params.length > 0) {
12364
          var param;
12365
          var metadata = initScopeMetadata(parentNode, path.slice(1), path[0]);
12366
          for (var i = 0; i < parentNode.params.length; i++) {
12367
            param = parentNode.params[i];
12368
            if (param.type === Syntax.Identifier) {
12369
              declareIdentInScope(param.name, metadata, state);
12370
            }
12371
          }
12372
        }
12373
12374
        // Include rest arg identifiers in the scope boundaries of their
12375
        // functions
12376
        if (parentNode.rest) {
12377
          var metadata = initScopeMetadata(
0 ignored issues
show
Comprehensibility Naming Best Practice introduced by
The variable metadata already seems to be declared on line 12365. Consider using another variable name or omitting the var keyword.

This check looks for variables that are declared in multiple lines. There may be several reasons for this.

In the simplest case the variable name was reused by mistake. This may lead to very hard to locate bugs.

If you want to reuse a variable for another purpose, consider declaring it at or near the top of your function and just assigning to it subsequently so it is always declared.

Loading history...
12378
            parentNode,
12379
            path.slice(1),
12380
            path[0]
12381
          );
12382
          declareIdentInScope(parentNode.rest.name, metadata, state);
12383
        }
12384
12385
        // Named FunctionExpressions scope their name within the body block of
12386
        // themselves only
12387
        if (parentNode.type === Syntax.FunctionExpression && parentNode.id) {
12388
          var metaData =
12389
            initScopeMetadata(parentNode, path.parentNodeslice, parentNode);
12390
          declareIdentInScope(parentNode.id.name, metaData, state);
12391
        }
12392
      }
12393
12394
      // Traverse and find all local identifiers in this closure first to
12395
      // account for function/variable declaration hoisting
12396
      collectClosureIdentsAndTraverse(node, path, state);
12397
    }
12398
12399
    if (_nodeIsBlockScopeBoundary(node, parentNode)) {
12400
      startIndex = state.g.buffer.length;
12401
      state = utils.updateState(state, {
12402
        localScope: {
12403
          parentNode: parentNode,
12404
          parentScope: state.localScope,
12405
          identifiers: {},
12406
          tempVarIndex: 0,
12407
          tempVars: []
12408
        }
12409
      });
12410
12411
      if (parentNode.type === Syntax.CatchClause) {
12412
        var metadata = initScopeMetadata(
0 ignored issues
show
Comprehensibility Naming Best Practice introduced by
The variable metadata already seems to be declared on line 12365. Consider using another variable name or omitting the var keyword.

This check looks for variables that are declared in multiple lines. There may be several reasons for this.

In the simplest case the variable name was reused by mistake. This may lead to very hard to locate bugs.

If you want to reuse a variable for another purpose, consider declaring it at or near the top of your function and just assigning to it subsequently so it is always declared.

Loading history...
12413
          parentNode,
12414
          path.slice(1),
12415
          parentNode
12416
        );
12417
        declareIdentInScope(parentNode.param.name, metadata, state);
12418
      }
12419
      collectBlockIdentsAndTraverse(node, path, state);
12420
    }
12421
  }
12422
12423
  // Only catchup() before and after traversing a child node
12424
  function traverser(node, path, state) {
12425
    node.range && utils.catchup(node.range[0], state);
12426
    traverse(node, path, state);
12427
    node.range && utils.catchup(node.range[1], state);
12428
  }
12429
12430
  utils.analyzeAndTraverse(walker, traverser, node, path, state);
12431
12432
  // Inject temp variables into the scope.
12433
  if (startIndex !== null) {
12434
    utils.injectTempVarDeclarations(state, startIndex);
12435
  }
12436
}
12437
12438
function collectClosureIdentsAndTraverse(node, path, state) {
12439
  utils.analyzeAndTraverse(
12440
    visitLocalClosureIdentifiers,
12441
    collectClosureIdentsAndTraverse,
12442
    node,
12443
    path,
12444
    state
12445
  );
12446
}
12447
12448
function collectBlockIdentsAndTraverse(node, path, state) {
12449
  utils.analyzeAndTraverse(
12450
    visitLocalBlockIdentifiers,
12451
    collectBlockIdentsAndTraverse,
12452
    node,
12453
    path,
12454
    state
12455
  );
12456
}
12457
12458
function visitLocalClosureIdentifiers(node, path, state) {
12459
  var metaData;
12460
  switch (node.type) {
0 ignored issues
show
Coding Style introduced by
As per coding-style, switch statements should have a default case.
Loading history...
12461
    case Syntax.ArrowFunctionExpression:
0 ignored issues
show
Bug introduced by
The variable Syntax seems to be never declared. If this is a global, consider adding a /** global: Syntax */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
12462
    case Syntax.FunctionExpression:
12463
      // Function expressions don't get their names (if there is one) added to
12464
      // the closure scope they're defined in
12465
      return false;
12466
    case Syntax.ClassDeclaration:
12467
    case Syntax.ClassExpression:
12468
    case Syntax.FunctionDeclaration:
12469
      if (node.id) {
12470
        metaData = initScopeMetadata(getBoundaryNode(path), path.slice(), node);
12471
        declareIdentInScope(node.id.name, metaData, state);
12472
      }
12473
      return false;
12474
    case Syntax.VariableDeclarator:
12475
      // Variables have function-local scope
12476
      if (path[0].kind === 'var') {
12477
        metaData = initScopeMetadata(getBoundaryNode(path), path.slice(), node);
12478
        declareIdentInScope(node.id.name, metaData, state);
12479
      }
12480
      break;
0 ignored issues
show
Best Practice introduced by
There is no return statement in this branch, but you do return something in other branches. Did you maybe miss it? If you do not want to return anything, consider adding return undefined; explicitly.
Loading history...
12481
  }
0 ignored issues
show
Comprehensibility introduced by
There is no default case in this switch, so nothing gets returned when all cases fail. You might want to consider adding a default or return undefined explicitly.
Loading history...
12482
}
12483
12484
function visitLocalBlockIdentifiers(node, path, state) {
0 ignored issues
show
Unused Code introduced by
The parameter path is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
Unused Code introduced by
The parameter state is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
12485
  // TODO: Support 'let' here...maybe...one day...or something...
12486
  if (node.type === Syntax.CatchClause) {
0 ignored issues
show
Complexity Best Practice introduced by
There is no return statement if node.type === Syntax.CatchClause is false. Are you sure this is correct? If so, consider adding return; explicitly.

This check looks for functions where a return statement is found in some execution paths, but not in all.

Consider this little piece of code

function isBig(a) {
    if (a > 5000) {
        return "yes";
    }
}

console.log(isBig(5001)); //returns yes
console.log(isBig(42)); //returns undefined

The function isBig will only return a specific value when its parameter is bigger than 5000. In any other case, it will implicitly return undefined.

This behaviour may not be what you had intended. In any case, you can add a return undefined to the other execution path to make the return value explicit.

Loading history...
12487
    return false;
12488
  }
12489
}
12490
12491
function walker(node, path, state) {
12492
  var visitors = state.g.visitors;
12493
  for (var i = 0; i < visitors.length; i++) {
12494
    if (visitors[i].test(node, path, state)) {
12495
      return visitors[i](traverse, node, path, state);
12496
    }
12497
  }
0 ignored issues
show
Best Practice introduced by
There is no return statement in this branch, but you do return something in other branches. Did you maybe miss it? If you do not want to return anything, consider adding return undefined; explicitly.
Loading history...
12498
}
12499
12500
var _astCache = {};
12501
12502
function getAstForSource(source, options) {
12503
  if (_astCache[source] && !options.disableAstCache) {
12504
    return _astCache[source];
12505
  }
12506
  var ast = esprima.parse(source, {
12507
    comment: true,
12508
    loc: true,
12509
    range: true,
12510
    sourceType: options.sourceType
12511
  });
12512
  if (!options.disableAstCache) {
12513
    _astCache[source] = ast;
12514
  }
12515
  return ast;
12516
}
12517
12518
/**
12519
 * Applies all available transformations to the source
12520
 * @param {array} visitors
12521
 * @param {string} source
12522
 * @param {?object} options
12523
 * @return {object}
12524
 */
12525
function transform(visitors, source, options) {
12526
  options = options || {};
12527
  var ast;
12528
  try {
12529
    ast = getAstForSource(source, options);
12530
    } catch (e) {
12531
    e.message = 'Parse Error: ' + e.message;
12532
    throw e;
12533
  }
12534
  var state = utils.createState(source, ast, options);
12535
  state.g.visitors = visitors;
12536
12537
  if (options.sourceMap) {
12538
    var SourceMapGenerator = _dereq_('source-map').SourceMapGenerator;
12539
    state.g.sourceMap = new SourceMapGenerator({file: options.filename || 'transformed.js'});
12540
  }
12541
12542
  traverse(ast, [], state);
12543
  utils.catchup(source.length, state);
12544
12545
  var ret = {code: state.g.buffer, extra: state.g.extra};
12546
  if (options.sourceMap) {
12547
    ret.sourceMap = state.g.sourceMap;
12548
    ret.sourceMapFilename =  options.filename || 'source.js';
12549
  }
12550
  return ret;
12551
}
12552
12553
exports.transform = transform;
12554
exports.Syntax = Syntax;
12555
12556
},{"./utils":23,"esprima-fb":9,"source-map":11}],23:[function(_dereq_,module,exports){
12557
/**
12558
 * Copyright 2013 Facebook, Inc.
12559
 *
12560
 * Licensed under the Apache License, Version 2.0 (the "License");
12561
 * you may not use this file except in compliance with the License.
12562
 * You may obtain a copy of the License at
12563
 *
12564
 * http://www.apache.org/licenses/LICENSE-2.0
12565
 *
12566
 * Unless required by applicable law or agreed to in writing, software
12567
 * distributed under the License is distributed on an "AS IS" BASIS,
12568
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12569
 * See the License for the specific language governing permissions and
12570
 * limitations under the License.
12571
 */
12572
12573
12574
/*jslint node: true*/
12575
var Syntax = _dereq_('esprima-fb').Syntax;
12576
var leadingIndentRegexp = /(^|\n)( {2}|\t)/g;
12577
var nonWhiteRegexp = /(\S)/g;
12578
12579
/**
12580
 * A `state` object represents the state of the parser. It has "local" and
12581
 * "global" parts. Global contains parser position, source, etc. Local contains
12582
 * scope based properties like current class name. State should contain all the
12583
 * info required for transformation. It's the only mandatory object that is
12584
 * being passed to every function in transform chain.
12585
 *
12586
 * @param  {string} source
12587
 * @param  {object} transformOptions
12588
 * @return {object}
12589
 */
12590
function createState(source, rootNode, transformOptions) {
12591
  return {
12592
    /**
12593
     * A tree representing the current local scope (and its lexical scope chain)
12594
     * Useful for tracking identifiers from parent scopes, etc.
12595
     * @type {Object}
12596
     */
12597
    localScope: {
12598
      parentNode: rootNode,
12599
      parentScope: null,
12600
      identifiers: {},
12601
      tempVarIndex: 0,
12602
      tempVars: []
12603
    },
12604
    /**
12605
     * The name (and, if applicable, expression) of the super class
12606
     * @type {Object}
12607
     */
12608
    superClass: null,
12609
    /**
12610
     * The namespace to use when munging identifiers
12611
     * @type {String}
12612
     */
12613
    mungeNamespace: '',
12614
    /**
12615
     * Ref to the node for the current MethodDefinition
12616
     * @type {Object}
12617
     */
12618
    methodNode: null,
12619
    /**
12620
     * Ref to the node for the FunctionExpression of the enclosing
12621
     * MethodDefinition
12622
     * @type {Object}
12623
     */
12624
    methodFuncNode: null,
12625
    /**
12626
     * Name of the enclosing class
12627
     * @type {String}
12628
     */
12629
    className: null,
12630
    /**
12631
     * Whether we're currently within a `strict` scope
12632
     * @type {Bool}
12633
     */
12634
    scopeIsStrict: null,
12635
    /**
12636
     * Indentation offset
12637
     * @type {Number}
12638
     */
12639
    indentBy: 0,
12640
    /**
12641
     * Global state (not affected by updateState)
12642
     * @type {Object}
12643
     */
12644
    g: {
12645
      /**
12646
       * A set of general options that transformations can consider while doing
12647
       * a transformation:
12648
       *
12649
       * - minify
12650
       *   Specifies that transformation steps should do their best to minify
12651
       *   the output source when possible. This is useful for places where
12652
       *   minification optimizations are possible with higher-level context
12653
       *   info than what jsxmin can provide.
12654
       *
12655
       *   For example, the ES6 class transform will minify munged private
12656
       *   variables if this flag is set.
12657
       */
12658
      opts: transformOptions,
12659
      /**
12660
       * Current position in the source code
12661
       * @type {Number}
12662
       */
12663
      position: 0,
12664
      /**
12665
       * Auxiliary data to be returned by transforms
12666
       * @type {Object}
12667
       */
12668
      extra: {},
12669
      /**
12670
       * Buffer containing the result
12671
       * @type {String}
12672
       */
12673
      buffer: '',
12674
      /**
12675
       * Source that is being transformed
12676
       * @type {String}
12677
       */
12678
      source: source,
12679
12680
      /**
12681
       * Cached parsed docblock (see getDocblock)
12682
       * @type {object}
12683
       */
12684
      docblock: null,
12685
12686
      /**
12687
       * Whether the thing was used
12688
       * @type {Boolean}
12689
       */
12690
      tagNamespaceUsed: false,
12691
12692
      /**
12693
       * If using bolt xjs transformation
12694
       * @type {Boolean}
12695
       */
12696
      isBolt: undefined,
12697
12698
      /**
12699
       * Whether to record source map (expensive) or not
12700
       * @type {SourceMapGenerator|null}
12701
       */
12702
      sourceMap: null,
12703
12704
      /**
12705
       * Filename of the file being processed. Will be returned as a source
12706
       * attribute in the source map
12707
       */
12708
      sourceMapFilename: 'source.js',
12709
12710
      /**
12711
       * Only when source map is used: last line in the source for which
12712
       * source map was generated
12713
       * @type {Number}
12714
       */
12715
      sourceLine: 1,
12716
12717
      /**
12718
       * Only when source map is used: last line in the buffer for which
12719
       * source map was generated
12720
       * @type {Number}
12721
       */
12722
      bufferLine: 1,
12723
12724
      /**
12725
       * The top-level Program AST for the original file.
12726
       */
12727
      originalProgramAST: null,
12728
12729
      sourceColumn: 0,
12730
      bufferColumn: 0
12731
    }
12732
  };
12733
}
12734
12735
/**
12736
 * Updates a copy of a given state with "update" and returns an updated state.
12737
 *
12738
 * @param  {object} state
12739
 * @param  {object} update
12740
 * @return {object}
12741
 */
12742
function updateState(state, update) {
12743
  var ret = Object.create(state);
12744
  Object.keys(update).forEach(function(updatedKey) {
12745
    ret[updatedKey] = update[updatedKey];
12746
  });
12747
  return ret;
12748
}
12749
12750
/**
12751
 * Given a state fill the resulting buffer from the original source up to
12752
 * the end
12753
 *
12754
 * @param {number} end
12755
 * @param {object} state
12756
 * @param {?function} contentTransformer Optional callback to transform newly
12757
 *                                       added content.
12758
 */
12759
function catchup(end, state, contentTransformer) {
12760
  if (end < state.g.position) {
12761
    // cannot move backwards
12762
    return;
12763
  }
12764
  var source = state.g.source.substring(state.g.position, end);
12765
  var transformed = updateIndent(source, state);
12766
  if (state.g.sourceMap && transformed) {
12767
    // record where we are
12768
    state.g.sourceMap.addMapping({
12769
      generated: { line: state.g.bufferLine, column: state.g.bufferColumn },
12770
      original: { line: state.g.sourceLine, column: state.g.sourceColumn },
12771
      source: state.g.sourceMapFilename
12772
    });
12773
12774
    // record line breaks in transformed source
12775
    var sourceLines = source.split('\n');
12776
    var transformedLines = transformed.split('\n');
12777
    // Add line break mappings between last known mapping and the end of the
12778
    // added piece. So for the code piece
12779
    //  (foo, bar);
12780
    // > var x = 2;
12781
    // > var b = 3;
12782
    //   var c =
12783
    // only add lines marked with ">": 2, 3.
12784
    for (var i = 1; i < sourceLines.length - 1; i++) {
12785
      state.g.sourceMap.addMapping({
12786
        generated: { line: state.g.bufferLine, column: 0 },
12787
        original: { line: state.g.sourceLine, column: 0 },
12788
        source: state.g.sourceMapFilename
12789
      });
12790
      state.g.sourceLine++;
12791
      state.g.bufferLine++;
12792
    }
12793
    // offset for the last piece
12794
    if (sourceLines.length > 1) {
12795
      state.g.sourceLine++;
12796
      state.g.bufferLine++;
12797
      state.g.sourceColumn = 0;
12798
      state.g.bufferColumn = 0;
12799
    }
12800
    state.g.sourceColumn += sourceLines[sourceLines.length - 1].length;
12801
    state.g.bufferColumn +=
12802
      transformedLines[transformedLines.length - 1].length;
12803
  }
12804
  state.g.buffer +=
12805
    contentTransformer ? contentTransformer(transformed) : transformed;
12806
  state.g.position = end;
12807
}
12808
12809
/**
12810
 * Returns original source for an AST node.
12811
 * @param {object} node
12812
 * @param {object} state
12813
 * @return {string}
12814
 */
12815
function getNodeSourceText(node, state) {
12816
  return state.g.source.substring(node.range[0], node.range[1]);
12817
}
12818
12819
function _replaceNonWhite(value) {
12820
  return value.replace(nonWhiteRegexp, ' ');
12821
}
12822
12823
/**
12824
 * Removes all non-whitespace characters
12825
 */
12826
function _stripNonWhite(value) {
12827
  return value.replace(nonWhiteRegexp, '');
12828
}
12829
12830
/**
12831
 * Finds the position of the next instance of the specified syntactic char in
12832
 * the pending source.
12833
 *
12834
 * NOTE: This will skip instances of the specified char if they sit inside a
12835
 *       comment body.
12836
 *
12837
 * NOTE: This function also assumes that the buffer's current position is not
12838
 *       already within a comment or a string. This is rarely the case since all
12839
 *       of the buffer-advancement utility methods tend to be used on syntactic
12840
 *       nodes' range values -- but it's a small gotcha that's worth mentioning.
12841
 */
12842
function getNextSyntacticCharOffset(char, state) {
12843
  var pendingSource = state.g.source.substring(state.g.position);
12844
  var pendingSourceLines = pendingSource.split('\n');
12845
12846
  var charOffset = 0;
12847
  var line;
12848
  var withinBlockComment = false;
12849
  var withinString = false;
12850
  lineLoop: while ((line = pendingSourceLines.shift()) !== undefined) {
12851
    var lineEndPos = charOffset + line.length;
12852
    charLoop: for (; charOffset < lineEndPos; charOffset++) {
12853
      var currChar = pendingSource[charOffset];
12854
      if (currChar === '"' || currChar === '\'') {
12855
        withinString = !withinString;
12856
        continue charLoop;
12857
      } else if (withinString) {
12858
        continue charLoop;
12859
      } else if (charOffset + 1 < lineEndPos) {
12860
        var nextTwoChars = currChar + line[charOffset + 1];
12861
        if (nextTwoChars === '//') {
12862
          charOffset = lineEndPos + 1;
12863
          continue lineLoop;
12864
        } else if (nextTwoChars === '/*') {
12865
          withinBlockComment = true;
12866
          charOffset += 1;
12867
          continue charLoop;
12868
        } else if (nextTwoChars === '*/') {
12869
          withinBlockComment = false;
12870
          charOffset += 1;
12871
          continue charLoop;
12872
        }
12873
      }
12874
12875
      if (!withinBlockComment && currChar === char) {
12876
        return charOffset + state.g.position;
12877
      }
12878
    }
12879
12880
    // Account for '\n'
12881
    charOffset++;
12882
    withinString = false;
12883
  }
12884
12885
  throw new Error('`' + char + '` not found!');
12886
}
12887
12888
/**
12889
 * Catches up as `catchup` but replaces non-whitespace chars with spaces.
12890
 */
12891
function catchupWhiteOut(end, state) {
12892
  catchup(end, state, _replaceNonWhite);
12893
}
12894
12895
/**
12896
 * Catches up as `catchup` but removes all non-whitespace characters.
12897
 */
12898
function catchupWhiteSpace(end, state) {
12899
  catchup(end, state, _stripNonWhite);
12900
}
12901
12902
/**
12903
 * Removes all non-newline characters
12904
 */
12905
var reNonNewline = /[^\n]/g;
12906
function stripNonNewline(value) {
12907
  return value.replace(reNonNewline, function() {
12908
    return '';
12909
  });
12910
}
12911
12912
/**
12913
 * Catches up as `catchup` but removes all non-newline characters.
12914
 *
12915
 * Equivalent to appending as many newlines as there are in the original source
12916
 * between the current position and `end`.
12917
 */
12918
function catchupNewlines(end, state) {
12919
  catchup(end, state, stripNonNewline);
12920
}
12921
12922
12923
/**
12924
 * Same as catchup but does not touch the buffer
12925
 *
12926
 * @param  {number} end
12927
 * @param  {object} state
12928
 */
12929
function move(end, state) {
12930
  // move the internal cursors
12931
  if (state.g.sourceMap) {
12932
    if (end < state.g.position) {
12933
      state.g.position = 0;
12934
      state.g.sourceLine = 1;
12935
      state.g.sourceColumn = 0;
12936
    }
12937
12938
    var source = state.g.source.substring(state.g.position, end);
12939
    var sourceLines = source.split('\n');
12940
    if (sourceLines.length > 1) {
12941
      state.g.sourceLine += sourceLines.length - 1;
12942
      state.g.sourceColumn = 0;
12943
    }
12944
    state.g.sourceColumn += sourceLines[sourceLines.length - 1].length;
12945
  }
12946
  state.g.position = end;
12947
}
12948
12949
/**
12950
 * Appends a string of text to the buffer
12951
 *
12952
 * @param {string} str
12953
 * @param {object} state
12954
 */
12955
function append(str, state) {
12956
  if (state.g.sourceMap && str) {
12957
    state.g.sourceMap.addMapping({
12958
      generated: { line: state.g.bufferLine, column: state.g.bufferColumn },
12959
      original: { line: state.g.sourceLine, column: state.g.sourceColumn },
12960
      source: state.g.sourceMapFilename
12961
    });
12962
    var transformedLines = str.split('\n');
12963
    if (transformedLines.length > 1) {
12964
      state.g.bufferLine += transformedLines.length - 1;
12965
      state.g.bufferColumn = 0;
12966
    }
12967
    state.g.bufferColumn +=
12968
      transformedLines[transformedLines.length - 1].length;
12969
  }
12970
  state.g.buffer += str;
12971
}
12972
12973
/**
12974
 * Update indent using state.indentBy property. Indent is measured in
12975
 * double spaces. Updates a single line only.
12976
 *
12977
 * @param {string} str
12978
 * @param {object} state
12979
 * @return {string}
12980
 */
12981
function updateIndent(str, state) {
12982
  /*jshint -W004*/
12983
  var indentBy = state.indentBy;
12984
  if (indentBy < 0) {
12985
    for (var i = 0; i < -indentBy; i++) {
12986
      str = str.replace(leadingIndentRegexp, '$1');
12987
    }
12988
  } else {
12989
    for (var i = 0; i < indentBy; i++) {
0 ignored issues
show
Comprehensibility Naming Best Practice introduced by
The variable i already seems to be declared on line 12985. Consider using another variable name or omitting the var keyword.

This check looks for variables that are declared in multiple lines. There may be several reasons for this.

In the simplest case the variable name was reused by mistake. This may lead to very hard to locate bugs.

If you want to reuse a variable for another purpose, consider declaring it at or near the top of your function and just assigning to it subsequently so it is always declared.

Loading history...
12990
      str = str.replace(leadingIndentRegexp, '$1$2$2');
12991
    }
12992
  }
12993
  return str;
12994
}
12995
12996
/**
12997
 * Calculates indent from the beginning of the line until "start" or the first
12998
 * character before start.
12999
 * @example
13000
 *   "  foo.bar()"
13001
 *         ^
13002
 *       start
13003
 *   indent will be "  "
13004
 *
13005
 * @param  {number} start
13006
 * @param  {object} state
13007
 * @return {string}
13008
 */
13009
function indentBefore(start, state) {
13010
  var end = start;
13011
  start = start - 1;
13012
13013
  while (start > 0 && state.g.source[start] != '\n') {
13014
    if (!state.g.source[start].match(/[ \t]/)) {
13015
      end = start;
13016
    }
13017
    start--;
13018
  }
13019
  return state.g.source.substring(start + 1, end);
13020
}
13021
13022
function getDocblock(state) {
13023
  if (!state.g.docblock) {
13024
    var docblock = _dereq_('./docblock');
13025
    state.g.docblock =
13026
      docblock.parseAsObject(docblock.extract(state.g.source));
13027
  }
13028
  return state.g.docblock;
13029
}
13030
13031
function identWithinLexicalScope(identName, state, stopBeforeNode) {
13032
  var currScope = state.localScope;
13033
  while (currScope) {
13034
    if (currScope.identifiers[identName] !== undefined) {
13035
      return true;
13036
    }
13037
13038
    if (stopBeforeNode && currScope.parentNode === stopBeforeNode) {
13039
      break;
13040
    }
13041
13042
    currScope = currScope.parentScope;
13043
  }
13044
  return false;
13045
}
13046
13047
function identInLocalScope(identName, state) {
13048
  return state.localScope.identifiers[identName] !== undefined;
13049
}
13050
13051
/**
13052
 * @param {object} boundaryNode
13053
 * @param {?array} path
13054
 * @return {?object} node
13055
 */
13056
function initScopeMetadata(boundaryNode, path, node) {
13057
  return {
13058
    boundaryNode: boundaryNode,
13059
    bindingPath: path,
13060
    bindingNode: node
13061
  };
13062
}
13063
13064
function declareIdentInLocalScope(identName, metaData, state) {
13065
  state.localScope.identifiers[identName] = {
13066
    boundaryNode: metaData.boundaryNode,
13067
    path: metaData.bindingPath,
13068
    node: metaData.bindingNode,
13069
    state: Object.create(state)
13070
  };
13071
}
13072
13073
function getLexicalBindingMetadata(identName, state) {
13074
  var currScope = state.localScope;
13075
  while (currScope) {
13076
    if (currScope.identifiers[identName] !== undefined) {
13077
      return currScope.identifiers[identName];
13078
    }
13079
13080
    currScope = currScope.parentScope;
13081
  }
0 ignored issues
show
Best Practice introduced by
There is no return statement in this branch, but you do return something in other branches. Did you maybe miss it? If you do not want to return anything, consider adding return undefined; explicitly.
Loading history...
13082
}
13083
13084
function getLocalBindingMetadata(identName, state) {
13085
  return state.localScope.identifiers[identName];
13086
}
13087
13088
/**
13089
 * Apply the given analyzer function to the current node. If the analyzer
13090
 * doesn't return false, traverse each child of the current node using the given
13091
 * traverser function.
13092
 *
13093
 * @param {function} analyzer
13094
 * @param {function} traverser
13095
 * @param {object} node
13096
 * @param {array} path
13097
 * @param {object} state
13098
 */
13099
function analyzeAndTraverse(analyzer, traverser, node, path, state) {
13100
  if (node.type) {
13101
    if (analyzer(node, path, state) === false) {
13102
      return;
13103
    }
13104
    path.unshift(node);
13105
  }
13106
13107
  getOrderedChildren(node).forEach(function(child) {
13108
    traverser(child, path, state);
13109
  });
13110
13111
  node.type && path.shift();
13112
}
13113
13114
/**
13115
 * It is crucial that we traverse in order, or else catchup() on a later
13116
 * node that is processed out of order can move the buffer past a node
13117
 * that we haven't handled yet, preventing us from modifying that node.
13118
 *
13119
 * This can happen when a node has multiple properties containing children.
13120
 * For example, XJSElement nodes have `openingElement`, `closingElement` and
13121
 * `children`. If we traverse `openingElement`, then `closingElement`, then
13122
 * when we get to `children`, the buffer has already caught up to the end of
13123
 * the closing element, after the children.
13124
 *
13125
 * This is basically a Schwartzian transform. Collects an array of children,
13126
 * each one represented as [child, startIndex]; sorts the array by start
13127
 * index; then traverses the children in that order.
13128
 */
13129
function getOrderedChildren(node) {
13130
  var queue = [];
13131
  for (var key in node) {
13132
    if (node.hasOwnProperty(key)) {
13133
      enqueueNodeWithStartIndex(queue, node[key]);
13134
    }
13135
  }
13136
  queue.sort(function(a, b) { return a[1] - b[1]; });
13137
  return queue.map(function(pair) { return pair[0]; });
13138
}
13139
13140
/**
13141
 * Helper function for analyzeAndTraverse which queues up all of the children
13142
 * of the given node.
13143
 *
13144
 * Children can also be found in arrays, so we basically want to merge all of
13145
 * those arrays together so we can sort them and then traverse the children
13146
 * in order.
13147
 *
13148
 * One example is the Program node. It contains `body` and `comments`, both
13149
 * arrays. Lexographically, comments are interspersed throughout the body
13150
 * nodes, but esprima's AST groups them together.
13151
 */
13152
function enqueueNodeWithStartIndex(queue, node) {
13153
  if (typeof node !== 'object' || node === null) {
13154
    return;
13155
  }
13156
  if (node.range) {
13157
    queue.push([node, node.range[0]]);
13158
  } else if (Array.isArray(node)) {
13159
    for (var ii = 0; ii < node.length; ii++) {
13160
      enqueueNodeWithStartIndex(queue, node[ii]);
13161
    }
13162
  }
13163
}
13164
13165
/**
13166
 * Checks whether a node or any of its sub-nodes contains
13167
 * a syntactic construct of the passed type.
13168
 * @param {object} node - AST node to test.
13169
 * @param {string} type - node type to lookup.
13170
 */
13171
function containsChildOfType(node, type) {
13172
  return containsChildMatching(node, function(node) {
13173
    return node.type === type;
13174
  });
13175
}
13176
13177
function containsChildMatching(node, matcher) {
13178
  var foundMatchingChild = false;
13179
  function nodeTypeAnalyzer(node) {
13180
    if (matcher(node) === true) {
0 ignored issues
show
Complexity Best Practice introduced by
There is no return statement if matcher(node) === true is false. Are you sure this is correct? If so, consider adding return; explicitly.

This check looks for functions where a return statement is found in some execution paths, but not in all.

Consider this little piece of code

function isBig(a) {
    if (a > 5000) {
        return "yes";
    }
}

console.log(isBig(5001)); //returns yes
console.log(isBig(42)); //returns undefined

The function isBig will only return a specific value when its parameter is bigger than 5000. In any other case, it will implicitly return undefined.

This behaviour may not be what you had intended. In any case, you can add a return undefined to the other execution path to make the return value explicit.

Loading history...
13181
      foundMatchingChild = true;
13182
      return false;
13183
    }
13184
  }
13185
  function nodeTypeTraverser(child, path, state) {
0 ignored issues
show
Unused Code introduced by
The parameter state is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
Unused Code introduced by
The parameter path is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
13186
    if (!foundMatchingChild) {
13187
      foundMatchingChild = containsChildMatching(child, matcher);
13188
    }
13189
  }
13190
  analyzeAndTraverse(
13191
    nodeTypeAnalyzer,
13192
    nodeTypeTraverser,
13193
    node,
13194
    []
13195
  );
13196
  return foundMatchingChild;
13197
}
13198
13199
var scopeTypes = {};
13200
scopeTypes[Syntax.ArrowFunctionExpression] = true;
13201
scopeTypes[Syntax.FunctionExpression] = true;
13202
scopeTypes[Syntax.FunctionDeclaration] = true;
13203
scopeTypes[Syntax.Program] = true;
13204
13205
function getBoundaryNode(path) {
13206
  for (var ii = 0; ii < path.length; ++ii) {
13207
    if (scopeTypes[path[ii].type]) {
13208
      return path[ii];
13209
    }
13210
  }
13211
  throw new Error(
13212
    'Expected to find a node with one of the following types in path:\n' +
13213
    JSON.stringify(Object.keys(scopeTypes))
13214
  );
13215
}
13216
13217
function getTempVar(tempVarIndex) {
13218
  return '$__' + tempVarIndex;
13219
}
13220
13221
function injectTempVar(state) {
13222
  var tempVar = '$__' + (state.localScope.tempVarIndex++);
13223
  state.localScope.tempVars.push(tempVar);
13224
  return tempVar;
13225
}
13226
13227
function injectTempVarDeclarations(state, index) {
13228
  if (state.localScope.tempVars.length) {
13229
    state.g.buffer =
13230
      state.g.buffer.slice(0, index) +
13231
      'var ' + state.localScope.tempVars.join(', ') + ';' +
13232
      state.g.buffer.slice(index);
13233
    state.localScope.tempVars = [];
13234
  }
13235
}
13236
13237
exports.analyzeAndTraverse = analyzeAndTraverse;
13238
exports.append = append;
13239
exports.catchup = catchup;
13240
exports.catchupNewlines = catchupNewlines;
13241
exports.catchupWhiteOut = catchupWhiteOut;
13242
exports.catchupWhiteSpace = catchupWhiteSpace;
13243
exports.containsChildMatching = containsChildMatching;
13244
exports.containsChildOfType = containsChildOfType;
13245
exports.createState = createState;
13246
exports.declareIdentInLocalScope = declareIdentInLocalScope;
13247
exports.getBoundaryNode = getBoundaryNode;
13248
exports.getDocblock = getDocblock;
13249
exports.getLexicalBindingMetadata = getLexicalBindingMetadata;
13250
exports.getLocalBindingMetadata = getLocalBindingMetadata;
13251
exports.getNextSyntacticCharOffset = getNextSyntacticCharOffset;
13252
exports.getNodeSourceText = getNodeSourceText;
13253
exports.getOrderedChildren = getOrderedChildren;
13254
exports.getTempVar = getTempVar;
13255
exports.identInLocalScope = identInLocalScope;
13256
exports.identWithinLexicalScope = identWithinLexicalScope;
13257
exports.indentBefore = indentBefore;
13258
exports.initScopeMetadata = initScopeMetadata;
13259
exports.injectTempVar = injectTempVar;
13260
exports.injectTempVarDeclarations = injectTempVarDeclarations;
13261
exports.move = move;
13262
exports.scopeTypes = scopeTypes;
13263
exports.updateIndent = updateIndent;
13264
exports.updateState = updateState;
13265
13266
},{"./docblock":21,"esprima-fb":9}],24:[function(_dereq_,module,exports){
13267
/**
13268
 * Copyright 2013 Facebook, Inc.
13269
 *
13270
 * Licensed under the Apache License, Version 2.0 (the "License");
13271
 * you may not use this file except in compliance with the License.
13272
 * You may obtain a copy of the License at
13273
 *
13274
 * http://www.apache.org/licenses/LICENSE-2.0
13275
 *
13276
 * Unless required by applicable law or agreed to in writing, software
13277
 * distributed under the License is distributed on an "AS IS" BASIS,
13278
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13279
 * See the License for the specific language governing permissions and
13280
 * limitations under the License.
13281
 */
13282
13283
/*global exports:true*/
13284
13285
/**
13286
 * Desugars ES6 Arrow functions to ES3 function expressions.
13287
 * If the function contains `this` expression -- automatically
13288
 * binds the function to current value of `this`.
13289
 *
13290
 * Single parameter, simple expression:
13291
 *
13292
 * [1, 2, 3].map(x => x * x);
13293
 *
13294
 * [1, 2, 3].map(function(x) { return x * x; });
13295
 *
13296
 * Several parameters, complex block:
13297
 *
13298
 * this.users.forEach((user, idx) => {
13299
 *   return this.isActive(idx) && this.send(user);
13300
 * });
13301
 *
13302
 * this.users.forEach(function(user, idx) {
13303
 *   return this.isActive(idx) && this.send(user);
13304
 * }.bind(this));
13305
 *
13306
 */
13307
var restParamVisitors = _dereq_('./es6-rest-param-visitors');
13308
var destructuringVisitors = _dereq_('./es6-destructuring-visitors');
13309
13310
var Syntax = _dereq_('esprima-fb').Syntax;
13311
var utils = _dereq_('../src/utils');
13312
13313
/**
13314
 * @public
13315
 */
13316
function visitArrowFunction(traverse, node, path, state) {
13317
  var notInExpression = (path[0].type === Syntax.ExpressionStatement);
13318
13319
  // Wrap a function into a grouping operator, if it's not
13320
  // in the expression position.
13321
  if (notInExpression) {
13322
    utils.append('(', state);
13323
  }
13324
13325
  utils.append('function', state);
13326
  renderParams(traverse, node, path, state);
13327
13328
  // Skip arrow.
13329
  utils.catchupWhiteSpace(node.body.range[0], state);
13330
13331
  var renderBody = node.body.type == Syntax.BlockStatement
13332
    ? renderStatementBody
13333
    : renderExpressionBody;
13334
13335
  path.unshift(node);
13336
  renderBody(traverse, node, path, state);
13337
  path.shift();
13338
13339
  // Bind the function only if `this` value is used
13340
  // inside it or inside any sub-expression.
13341
  var containsBindingSyntax =
13342
    utils.containsChildMatching(node.body, function(node) {
13343
      return node.type === Syntax.ThisExpression
13344
             || (node.type === Syntax.Identifier
13345
                 && node.name === "super");
13346
    });
13347
13348
  if (containsBindingSyntax) {
13349
    utils.append('.bind(this)', state);
13350
  }
13351
13352
  utils.catchupWhiteSpace(node.range[1], state);
13353
13354
  // Close wrapper if not in the expression.
13355
  if (notInExpression) {
13356
    utils.append(')', state);
13357
  }
13358
13359
  return false;
13360
}
13361
13362
function renderParams(traverse, node, path, state) {
13363
  // To preserve inline typechecking directives, we
13364
  // distinguish between parens-free and paranthesized single param.
13365
  if (isParensFreeSingleParam(node, state) || !node.params.length) {
13366
    utils.append('(', state);
13367
  }
13368
  if (node.params.length !== 0) {
13369
    path.unshift(node);
13370
    traverse(node.params, path, state);
13371
    path.unshift();
13372
  }
13373
  utils.append(')', state);
13374
}
13375
13376
function isParensFreeSingleParam(node, state) {
13377
  return node.params.length === 1 &&
13378
    state.g.source[state.g.position] !== '(';
13379
}
13380
13381
function renderExpressionBody(traverse, node, path, state) {
13382
  // Wrap simple expression bodies into a block
13383
  // with explicit return statement.
13384
  utils.append('{', state);
13385
13386
  // Special handling of rest param.
13387
  if (node.rest) {
13388
    utils.append(
13389
      restParamVisitors.renderRestParamSetup(node, state),
13390
      state
13391
    );
13392
  }
13393
13394
  // Special handling of destructured params.
13395
  destructuringVisitors.renderDestructuredComponents(
13396
    node,
13397
    utils.updateState(state, {
13398
      localScope: {
13399
        parentNode: state.parentNode,
13400
        parentScope: state.parentScope,
13401
        identifiers: state.identifiers,
13402
        tempVarIndex: 0
13403
      }
13404
    })
13405
  );
13406
13407
  utils.append('return ', state);
13408
  renderStatementBody(traverse, node, path, state);
13409
  utils.append(';}', state);
13410
}
13411
13412
function renderStatementBody(traverse, node, path, state) {
13413
  traverse(node.body, path, state);
13414
  utils.catchup(node.body.range[1], state);
13415
}
13416
13417
visitArrowFunction.test = function(node, path, state) {
0 ignored issues
show
Unused Code introduced by
The parameter path is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
Unused Code introduced by
The parameter state is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
13418
  return node.type === Syntax.ArrowFunctionExpression;
13419
};
13420
13421
exports.visitorList = [
13422
  visitArrowFunction
13423
];
13424
13425
13426
},{"../src/utils":23,"./es6-destructuring-visitors":27,"./es6-rest-param-visitors":30,"esprima-fb":9}],25:[function(_dereq_,module,exports){
13427
/**
13428
 * Copyright 2004-present Facebook. All Rights Reserved.
13429
 */
13430
/*global exports:true*/
13431
13432
/**
13433
 * Implements ES6 call spread.
13434
 *
13435
 * instance.method(a, b, c, ...d)
13436
 *
13437
 * instance.method.apply(instance, [a, b, c].concat(d))
13438
 *
13439
 */
13440
13441
var Syntax = _dereq_('esprima-fb').Syntax;
13442
var utils = _dereq_('../src/utils');
13443
13444
function process(traverse, node, path, state) {
13445
  utils.move(node.range[0], state);
13446
  traverse(node, path, state);
13447
  utils.catchup(node.range[1], state);
13448
}
13449
13450
function visitCallSpread(traverse, node, path, state) {
13451
  utils.catchup(node.range[0], state);
13452
13453
  if (node.type === Syntax.NewExpression) {
13454
    // Input  = new Set(1, 2, ...list)
13455
    // Output = new (Function.prototype.bind.apply(Set, [null, 1, 2].concat(list)))
13456
    utils.append('new (Function.prototype.bind.apply(', state);
13457
    process(traverse, node.callee, path, state);
13458
  } else if (node.callee.type === Syntax.MemberExpression) {
13459
    // Input  = get().fn(1, 2, ...more)
13460
    // Output = (_ = get()).fn.apply(_, [1, 2].apply(more))
13461
    var tempVar = utils.injectTempVar(state);
13462
    utils.append('(' + tempVar + ' = ', state);
13463
    process(traverse, node.callee.object, path, state);
13464
    utils.append(')', state);
13465
    if (node.callee.property.type === Syntax.Identifier) {
13466
      utils.append('.', state);
13467
      process(traverse, node.callee.property, path, state);
13468
    } else {
13469
      utils.append('[', state);
13470
      process(traverse, node.callee.property, path, state);
13471
      utils.append(']', state);
13472
    }
13473
    utils.append('.apply(' + tempVar, state);
13474
  } else {
13475
    // Input  = max(1, 2, ...list)
13476
    // Output = max.apply(null, [1, 2].concat(list))
13477
    var needsToBeWrappedInParenthesis =
13478
      node.callee.type === Syntax.FunctionDeclaration ||
13479
      node.callee.type === Syntax.FunctionExpression;
13480
    if (needsToBeWrappedInParenthesis) {
13481
      utils.append('(', state);
13482
    }
13483
    process(traverse, node.callee, path, state);
13484
    if (needsToBeWrappedInParenthesis) {
13485
      utils.append(')', state);
13486
    }
13487
    utils.append('.apply(null', state);
13488
  }
13489
  utils.append(', ', state);
13490
13491
  var args = node.arguments.slice();
13492
  var spread = args.pop();
13493
  if (args.length || node.type === Syntax.NewExpression) {
13494
    utils.append('[', state);
13495
    if (node.type === Syntax.NewExpression) {
13496
      utils.append('null' + (args.length ? ', ' : ''), state);
13497
    }
13498
    while (args.length) {
13499
      var arg = args.shift();
13500
      utils.move(arg.range[0], state);
13501
      traverse(arg, path, state);
13502
      if (args.length) {
13503
        utils.catchup(args[0].range[0], state);
13504
      } else {
13505
        utils.catchup(arg.range[1], state);
13506
      }
13507
    }
13508
    utils.append('].concat(', state);
13509
    process(traverse, spread.argument, path, state);
13510
    utils.append(')', state);
13511
  } else {
13512
    process(traverse, spread.argument, path, state);
13513
  }
13514
  utils.append(node.type === Syntax.NewExpression ? '))' : ')', state);
13515
13516
  utils.move(node.range[1], state);
13517
  return false;
13518
}
13519
13520
visitCallSpread.test = function(node, path, state) {
0 ignored issues
show
Unused Code introduced by
The parameter path is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
Unused Code introduced by
The parameter state is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
13521
  return (
13522
    (
13523
      node.type === Syntax.CallExpression ||
13524
      node.type === Syntax.NewExpression
13525
    ) &&
13526
    node.arguments.length > 0 &&
13527
    node.arguments[node.arguments.length - 1].type === Syntax.SpreadElement
13528
  );
13529
};
13530
13531
exports.visitorList = [
13532
  visitCallSpread
13533
];
13534
13535
},{"../src/utils":23,"esprima-fb":9}],26:[function(_dereq_,module,exports){
13536
/**
13537
 * Copyright 2013 Facebook, Inc.
13538
 *
13539
 * Licensed under the Apache License, Version 2.0 (the "License");
13540
 * you may not use this file except in compliance with the License.
13541
 * You may obtain a copy of the License at
13542
 *
13543
 * http://www.apache.org/licenses/LICENSE-2.0
13544
 *
13545
 * Unless required by applicable law or agreed to in writing, software
13546
 * distributed under the License is distributed on an "AS IS" BASIS,
13547
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13548
 * See the License for the specific language governing permissions and
13549
 * limitations under the License.
13550
 */
13551
13552
/*jslint node:true*/
13553
13554
/**
13555
 * @typechecks
13556
 */
13557
'use strict';
13558
13559
var base62 = _dereq_('base62');
13560
var Syntax = _dereq_('esprima-fb').Syntax;
13561
var utils = _dereq_('../src/utils');
13562
var reservedWordsHelper = _dereq_('./reserved-words-helper');
13563
13564
var declareIdentInLocalScope = utils.declareIdentInLocalScope;
13565
var initScopeMetadata = utils.initScopeMetadata;
13566
13567
var SUPER_PROTO_IDENT_PREFIX = '____SuperProtoOf';
13568
13569
var _anonClassUUIDCounter = 0;
13570
var _mungedSymbolMaps = {};
13571
13572
function resetSymbols() {
13573
  _anonClassUUIDCounter = 0;
13574
  _mungedSymbolMaps = {};
13575
}
13576
13577
/**
13578
 * Used to generate a unique class for use with code-gens for anonymous class
13579
 * expressions.
13580
 *
13581
 * @param {object} state
13582
 * @return {string}
13583
 */
13584
function _generateAnonymousClassName(state) {
13585
  var mungeNamespace = state.mungeNamespace || '';
13586
  return '____Class' + mungeNamespace + base62.encode(_anonClassUUIDCounter++);
13587
}
13588
13589
/**
13590
 * Given an identifier name, munge it using the current state's mungeNamespace.
13591
 *
13592
 * @param {string} identName
13593
 * @param {object} state
13594
 * @return {string}
13595
 */
13596
function _getMungedName(identName, state) {
13597
  var mungeNamespace = state.mungeNamespace;
13598
  var shouldMinify = state.g.opts.minify;
13599
13600
  if (shouldMinify) {
13601
    if (!_mungedSymbolMaps[mungeNamespace]) {
13602
      _mungedSymbolMaps[mungeNamespace] = {
13603
        symbolMap: {},
13604
        identUUIDCounter: 0
13605
      };
13606
    }
13607
13608
    var symbolMap = _mungedSymbolMaps[mungeNamespace].symbolMap;
13609
    if (!symbolMap[identName]) {
13610
      symbolMap[identName] =
13611
        base62.encode(_mungedSymbolMaps[mungeNamespace].identUUIDCounter++);
13612
    }
13613
    identName = symbolMap[identName];
13614
  }
13615
  return '$' + mungeNamespace + identName;
13616
}
13617
13618
/**
13619
 * Extracts super class information from a class node.
13620
 *
13621
 * Information includes name of the super class and/or the expression string
13622
 * (if extending from an expression)
13623
 *
13624
 * @param {object} node
13625
 * @param {object} state
13626
 * @return {object}
13627
 */
13628
function _getSuperClassInfo(node, state) {
13629
  var ret = {
13630
    name: null,
13631
    expression: null
13632
  };
13633
  if (node.superClass) {
13634
    if (node.superClass.type === Syntax.Identifier) {
13635
      ret.name = node.superClass.name;
13636
    } else {
13637
      // Extension from an expression
13638
      ret.name = _generateAnonymousClassName(state);
13639
      ret.expression = state.g.source.substring(
13640
        node.superClass.range[0],
13641
        node.superClass.range[1]
13642
      );
13643
    }
13644
  }
13645
  return ret;
13646
}
13647
13648
/**
13649
 * Used with .filter() to find the constructor method in a list of
13650
 * MethodDefinition nodes.
13651
 *
13652
 * @param {object} classElement
13653
 * @return {boolean}
13654
 */
13655
function _isConstructorMethod(classElement) {
13656
  return classElement.type === Syntax.MethodDefinition &&
13657
         classElement.key.type === Syntax.Identifier &&
13658
         classElement.key.name === 'constructor';
13659
}
13660
13661
/**
13662
 * @param {object} node
13663
 * @param {object} state
13664
 * @return {boolean}
13665
 */
13666
function _shouldMungeIdentifier(node, state) {
13667
  return (
13668
    !!state.methodFuncNode &&
13669
    !utils.getDocblock(state).hasOwnProperty('preventMunge') &&
13670
    /^_(?!_)/.test(node.name)
13671
  );
13672
}
13673
13674
/**
13675
 * @param {function} traverse
13676
 * @param {object} node
13677
 * @param {array} path
13678
 * @param {object} state
13679
 */
13680
function visitClassMethod(traverse, node, path, state) {
13681
  if (!state.g.opts.es5 && (node.kind === 'get' || node.kind === 'set')) {
13682
    throw new Error(
13683
      'This transform does not support ' + node.kind + 'ter methods for ES6 ' +
13684
      'classes. (line: ' + node.loc.start.line + ', col: ' +
13685
      node.loc.start.column + ')'
13686
    );
13687
  }
13688
  state = utils.updateState(state, {
13689
    methodNode: node
13690
  });
13691
  utils.catchup(node.range[0], state);
13692
  path.unshift(node);
13693
  traverse(node.value, path, state);
13694
  path.shift();
13695
  return false;
13696
}
13697
visitClassMethod.test = function(node, path, state) {
0 ignored issues
show
Unused Code introduced by
The parameter state is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
Unused Code introduced by
The parameter path is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
13698
  return node.type === Syntax.MethodDefinition;
13699
};
13700
13701
/**
13702
 * @param {function} traverse
13703
 * @param {object} node
13704
 * @param {array} path
13705
 * @param {object} state
13706
 */
13707
function visitClassFunctionExpression(traverse, node, path, state) {
13708
  var methodNode = path[0];
13709
  var isGetter = methodNode.kind === 'get';
13710
  var isSetter = methodNode.kind === 'set';
13711
13712
  state = utils.updateState(state, {
13713
    methodFuncNode: node
13714
  });
13715
13716
  if (methodNode.key.name === 'constructor') {
13717
    utils.append('function ' + state.className, state);
13718
  } else {
13719
    var methodAccessorComputed = false;
13720
    var methodAccessor;
13721
    var prototypeOrStatic = methodNode["static"] ? '' : '.prototype';
13722
    var objectAccessor = state.className + prototypeOrStatic;
13723
13724
    if (methodNode.key.type === Syntax.Identifier) {
13725
      // foo() {}
13726
      methodAccessor = methodNode.key.name;
13727
      if (_shouldMungeIdentifier(methodNode.key, state)) {
13728
        methodAccessor = _getMungedName(methodAccessor, state);
13729
      }
13730
      if (isGetter || isSetter) {
13731
        methodAccessor = JSON.stringify(methodAccessor);
13732
      } else if (reservedWordsHelper.isReservedWord(methodAccessor)) {
13733
        methodAccessorComputed = true;
13734
        methodAccessor = JSON.stringify(methodAccessor);
13735
      }
13736
    } else if (methodNode.key.type === Syntax.Literal) {
13737
      // 'foo bar'() {}  | get 'foo bar'() {} | set 'foo bar'() {}
13738
      methodAccessor = JSON.stringify(methodNode.key.value);
13739
      methodAccessorComputed = true;
13740
    }
13741
13742
    if (isSetter || isGetter) {
13743
      utils.append(
13744
        'Object.defineProperty(' +
13745
          objectAccessor + ',' +
13746
          methodAccessor + ',' +
0 ignored issues
show
Bug introduced by
The variable methodAccessor does not seem to be initialized in case methodNode.key.type === Syntax.Literal on line 13736 is false. Are you sure this can never be the case?
Loading history...
13747
          '{configurable:true,' +
13748
          methodNode.kind + ':function',
13749
        state
13750
      );
13751
    } else {
13752
      if (state.g.opts.es3) {
13753
        if (methodAccessorComputed) {
13754
          methodAccessor = '[' + methodAccessor + ']';
13755
        } else {
13756
          methodAccessor = '.' + methodAccessor;
13757
        }
13758
        utils.append(
13759
          objectAccessor +
13760
          methodAccessor + '=function' + (node.generator ? '*' : ''),
13761
          state
13762
        );
13763
      } else {
13764
        if (!methodAccessorComputed) {
13765
          methodAccessor = JSON.stringify(methodAccessor);
13766
        }
13767
        utils.append(
13768
          'Object.defineProperty(' +
13769
            objectAccessor + ',' +
13770
            methodAccessor + ',' +
13771
            '{writable:true,configurable:true,' +
13772
            'value:function' + (node.generator ? '*' : ''),
13773
          state
13774
        );
13775
      }
13776
    }
13777
  }
13778
  utils.move(methodNode.key.range[1], state);
13779
  utils.append('(', state);
13780
13781
  var params = node.params;
13782
  if (params.length > 0) {
13783
    utils.catchupNewlines(params[0].range[0], state);
13784
    for (var i = 0; i < params.length; i++) {
13785
      utils.catchup(node.params[i].range[0], state);
13786
      path.unshift(node);
13787
      traverse(params[i], path, state);
13788
      path.shift();
13789
    }
13790
  }
13791
13792
  var closingParenPosition = utils.getNextSyntacticCharOffset(')', state);
13793
  utils.catchupWhiteSpace(closingParenPosition, state);
13794
13795
  var openingBracketPosition = utils.getNextSyntacticCharOffset('{', state);
13796
  utils.catchup(openingBracketPosition + 1, state);
13797
13798
  if (!state.scopeIsStrict) {
13799
    utils.append('"use ' + 'strict";', state);
13800
    state = utils.updateState(state, {
13801
      scopeIsStrict: true
13802
    });
13803
  }
13804
  utils.move(node.body.range[0] + '{'.length, state);
13805
13806
  path.unshift(node);
13807
  traverse(node.body, path, state);
13808
  path.shift();
13809
  utils.catchup(node.body.range[1], state);
13810
13811
  if (methodNode.key.name !== 'constructor') {
13812
    if (isGetter || isSetter || !state.g.opts.es3) {
13813
      utils.append('})', state);
13814
    }
13815
    utils.append(';', state);
13816
  }
13817
  return false;
13818
}
13819
visitClassFunctionExpression.test = function(node, path, state) {
0 ignored issues
show
Unused Code introduced by
The parameter state is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
13820
  return node.type === Syntax.FunctionExpression
13821
         && path[0].type === Syntax.MethodDefinition;
13822
};
13823
13824
function visitClassMethodParam(traverse, node, path, state) {
13825
  var paramName = node.name;
13826
  if (_shouldMungeIdentifier(node, state)) {
13827
    paramName = _getMungedName(node.name, state);
13828
  }
13829
  utils.append(paramName, state);
13830
  utils.move(node.range[1], state);
13831
}
13832
visitClassMethodParam.test = function(node, path, state) {
0 ignored issues
show
Unused Code introduced by
The parameter state is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
13833
  if (!path[0] || !path[1]) {
13834
    return;
13835
  }
13836
13837
  var parentFuncExpr = path[0];
13838
  var parentClassMethod = path[1];
13839
13840
  return parentFuncExpr.type === Syntax.FunctionExpression
13841
         && parentClassMethod.type === Syntax.MethodDefinition
13842
         && node.type === Syntax.Identifier;
13843
};
13844
13845
/**
13846
 * @param {function} traverse
13847
 * @param {object} node
13848
 * @param {array} path
13849
 * @param {object} state
13850
 */
13851
function _renderClassBody(traverse, node, path, state) {
13852
  var className = state.className;
13853
  var superClass = state.superClass;
13854
13855
  // Set up prototype of constructor on same line as `extends` for line-number
13856
  // preservation. This relies on function-hoisting if a constructor function is
13857
  // defined in the class body.
13858
  if (superClass.name) {
13859
    // If the super class is an expression, we need to memoize the output of the
13860
    // expression into the generated class name variable and use that to refer
13861
    // to the super class going forward. Example:
13862
    //
13863
    //   class Foo extends mixin(Bar, Baz) {}
13864
    //     --transforms to--
13865
    //   function Foo() {} var ____Class0Blah = mixin(Bar, Baz);
13866
    if (superClass.expression !== null) {
13867
      utils.append(
13868
        'var ' + superClass.name + '=' + superClass.expression + ';',
13869
        state
13870
      );
13871
    }
13872
13873
    var keyName = superClass.name + '____Key';
13874
    var keyNameDeclarator = '';
13875
    if (!utils.identWithinLexicalScope(keyName, state)) {
13876
      keyNameDeclarator = 'var ';
13877
      declareIdentInLocalScope(keyName, initScopeMetadata(node), state);
13878
    }
13879
    utils.append(
13880
      'for(' + keyNameDeclarator + keyName + ' in ' + superClass.name + '){' +
13881
        'if(' + superClass.name + '.hasOwnProperty(' + keyName + ')){' +
13882
          className + '[' + keyName + ']=' +
13883
            superClass.name + '[' + keyName + '];' +
13884
        '}' +
13885
      '}',
13886
      state
13887
    );
13888
13889
    var superProtoIdentStr = SUPER_PROTO_IDENT_PREFIX + superClass.name;
13890
    if (!utils.identWithinLexicalScope(superProtoIdentStr, state)) {
13891
      utils.append(
13892
        'var ' + superProtoIdentStr + '=' + superClass.name + '===null?' +
13893
        'null:' + superClass.name + '.prototype;',
13894
        state
13895
      );
13896
      declareIdentInLocalScope(superProtoIdentStr, initScopeMetadata(node), state);
13897
    }
13898
13899
    utils.append(
13900
      className + '.prototype=Object.create(' + superProtoIdentStr + ');',
13901
      state
13902
    );
13903
    utils.append(
13904
      className + '.prototype.constructor=' + className + ';',
13905
      state
13906
    );
13907
    utils.append(
13908
      className + '.__superConstructor__=' + superClass.name + ';',
13909
      state
13910
    );
13911
  }
13912
13913
  // If there's no constructor method specified in the class body, create an
13914
  // empty constructor function at the top (same line as the class keyword)
13915
  if (!node.body.body.filter(_isConstructorMethod).pop()) {
13916
    utils.append('function ' + className + '(){', state);
13917
    if (!state.scopeIsStrict) {
13918
      utils.append('"use ' + 'strict";', state);
13919
    }
13920
    if (superClass.name) {
13921
      utils.append(
13922
        'if(' + superClass.name + '!==null){' +
13923
        superClass.name + '.apply(this,arguments);}',
13924
        state
13925
      );
13926
    }
13927
    utils.append('}', state);
13928
  }
13929
13930
  utils.move(node.body.range[0] + '{'.length, state);
13931
  traverse(node.body, path, state);
13932
  utils.catchupWhiteSpace(node.range[1], state);
13933
}
13934
13935
/**
13936
 * @param {function} traverse
13937
 * @param {object} node
13938
 * @param {array} path
13939
 * @param {object} state
13940
 */
13941
function visitClassDeclaration(traverse, node, path, state) {
13942
  var className = node.id.name;
13943
  var superClass = _getSuperClassInfo(node, state);
13944
13945
  state = utils.updateState(state, {
13946
    mungeNamespace: className,
13947
    className: className,
13948
    superClass: superClass
13949
  });
13950
13951
  _renderClassBody(traverse, node, path, state);
13952
13953
  return false;
13954
}
13955
visitClassDeclaration.test = function(node, path, state) {
0 ignored issues
show
Unused Code introduced by
The parameter path is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
Unused Code introduced by
The parameter state is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
13956
  return node.type === Syntax.ClassDeclaration;
13957
};
13958
13959
/**
13960
 * @param {function} traverse
13961
 * @param {object} node
13962
 * @param {array} path
13963
 * @param {object} state
13964
 */
13965
function visitClassExpression(traverse, node, path, state) {
13966
  var className = node.id && node.id.name || _generateAnonymousClassName(state);
13967
  var superClass = _getSuperClassInfo(node, state);
13968
13969
  utils.append('(function(){', state);
13970
13971
  state = utils.updateState(state, {
13972
    mungeNamespace: className,
13973
    className: className,
13974
    superClass: superClass
13975
  });
13976
13977
  _renderClassBody(traverse, node, path, state);
13978
13979
  utils.append('return ' + className + ';})()', state);
13980
  return false;
13981
}
13982
visitClassExpression.test = function(node, path, state) {
0 ignored issues
show
Unused Code introduced by
The parameter path is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
Unused Code introduced by
The parameter state is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
13983
  return node.type === Syntax.ClassExpression;
13984
};
13985
13986
/**
13987
 * @param {function} traverse
13988
 * @param {object} node
13989
 * @param {array} path
13990
 * @param {object} state
13991
 */
13992
function visitPrivateIdentifier(traverse, node, path, state) {
13993
  utils.append(_getMungedName(node.name, state), state);
13994
  utils.move(node.range[1], state);
13995
}
13996
visitPrivateIdentifier.test = function(node, path, state) {
13997
  if (node.type === Syntax.Identifier && _shouldMungeIdentifier(node, state)) {
13998
    // Always munge non-computed properties of MemberExpressions
13999
    // (a la preventing access of properties of unowned objects)
14000
    if (path[0].type === Syntax.MemberExpression && path[0].object !== node
14001
        && path[0].computed === false) {
14002
      return true;
14003
    }
14004
14005
    // Always munge identifiers that were declared within the method function
14006
    // scope
14007
    if (utils.identWithinLexicalScope(node.name, state, state.methodFuncNode)) {
14008
      return true;
14009
    }
14010
14011
    // Always munge private keys on object literals defined within a method's
14012
    // scope.
14013
    if (path[0].type === Syntax.Property
14014
        && path[1].type === Syntax.ObjectExpression) {
14015
      return true;
14016
    }
14017
14018
    // Always munge function parameters
14019
    if (path[0].type === Syntax.FunctionExpression
14020
        || path[0].type === Syntax.FunctionDeclaration
14021
        || path[0].type === Syntax.ArrowFunctionExpression) {
14022
      for (var i = 0; i < path[0].params.length; i++) {
14023
        if (path[0].params[i] === node) {
14024
          return true;
14025
        }
14026
      }
14027
    }
14028
  }
14029
  return false;
14030
};
14031
14032
/**
14033
 * @param {function} traverse
14034
 * @param {object} node
14035
 * @param {array} path
14036
 * @param {object} state
14037
 */
14038
function visitSuperCallExpression(traverse, node, path, state) {
14039
  var superClassName = state.superClass.name;
14040
14041
  if (node.callee.type === Syntax.Identifier) {
14042
    if (_isConstructorMethod(state.methodNode)) {
14043
      utils.append(superClassName + '.call(', state);
14044
    } else {
14045
      var protoProp = SUPER_PROTO_IDENT_PREFIX + superClassName;
14046
      if (state.methodNode.key.type === Syntax.Identifier) {
14047
        protoProp += '.' + state.methodNode.key.name;
14048
      } else if (state.methodNode.key.type === Syntax.Literal) {
14049
        protoProp += '[' + JSON.stringify(state.methodNode.key.value) + ']';
14050
      }
14051
      utils.append(protoProp + ".call(", state);
14052
    }
14053
    utils.move(node.callee.range[1], state);
14054
  } else if (node.callee.type === Syntax.MemberExpression) {
14055
    utils.append(SUPER_PROTO_IDENT_PREFIX + superClassName, state);
14056
    utils.move(node.callee.object.range[1], state);
14057
14058
    if (node.callee.computed) {
14059
      // ["a" + "b"]
14060
      utils.catchup(node.callee.property.range[1] + ']'.length, state);
14061
    } else {
14062
      // .ab
14063
      utils.append('.' + node.callee.property.name, state);
14064
    }
14065
14066
    utils.append('.call(', state);
14067
    utils.move(node.callee.range[1], state);
14068
  }
14069
14070
  utils.append('this', state);
14071
  if (node.arguments.length > 0) {
14072
    utils.append(',', state);
14073
    utils.catchupWhiteSpace(node.arguments[0].range[0], state);
14074
    traverse(node.arguments, path, state);
14075
  }
14076
14077
  utils.catchupWhiteSpace(node.range[1], state);
14078
  utils.append(')', state);
14079
  return false;
14080
}
14081
visitSuperCallExpression.test = function(node, path, state) {
14082
  if (state.superClass && node.type === Syntax.CallExpression) {
14083
    var callee = node.callee;
14084
    if (callee.type === Syntax.Identifier && callee.name === 'super'
14085
        || callee.type == Syntax.MemberExpression
14086
           && callee.object.name === 'super') {
14087
      return true;
14088
    }
14089
  }
14090
  return false;
14091
};
14092
14093
/**
14094
 * @param {function} traverse
14095
 * @param {object} node
14096
 * @param {array} path
14097
 * @param {object} state
14098
 */
14099
function visitSuperMemberExpression(traverse, node, path, state) {
14100
  var superClassName = state.superClass.name;
14101
14102
  utils.append(SUPER_PROTO_IDENT_PREFIX + superClassName, state);
14103
  utils.move(node.object.range[1], state);
14104
}
14105
visitSuperMemberExpression.test = function(node, path, state) {
14106
  return state.superClass
14107
         && node.type === Syntax.MemberExpression
14108
         && node.object.type === Syntax.Identifier
14109
         && node.object.name === 'super';
14110
};
14111
14112
exports.resetSymbols = resetSymbols;
14113
14114
exports.visitorList = [
14115
  visitClassDeclaration,
14116
  visitClassExpression,
14117
  visitClassFunctionExpression,
14118
  visitClassMethod,
14119
  visitClassMethodParam,
14120
  visitPrivateIdentifier,
14121
  visitSuperCallExpression,
14122
  visitSuperMemberExpression
14123
];
14124
14125
},{"../src/utils":23,"./reserved-words-helper":34,"base62":10,"esprima-fb":9}],27:[function(_dereq_,module,exports){
14126
/**
14127
 * Copyright 2014 Facebook, Inc.
14128
 *
14129
 * Licensed under the Apache License, Version 2.0 (the "License");
14130
 * you may not use this file except in compliance with the License.
14131
 * You may obtain a copy of the License at
14132
 *
14133
 * http://www.apache.org/licenses/LICENSE-2.0
14134
 *
14135
 * Unless required by applicable law or agreed to in writing, software
14136
 * distributed under the License is distributed on an "AS IS" BASIS,
14137
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14138
 * See the License for the specific language governing permissions and
14139
 * limitations under the License.
14140
 */
14141
/*global exports:true*/
14142
14143
/**
14144
 * Implements ES6 destructuring assignment and pattern matchng.
14145
 *
14146
 * function init({port, ip, coords: [x, y]}) {
14147
 *   return (x && y) ? {id, port} : {ip};
14148
 * };
14149
 *
14150
 * function init($__0) {
14151
 *   var
14152
 *    port = $__0.port,
14153
 *    ip = $__0.ip,
14154
 *    $__1 = $__0.coords,
14155
 *    x = $__1[0],
14156
 *    y = $__1[1];
14157
 *   return (x && y) ? {id, port} : {ip};
14158
 * }
14159
 *
14160
 * var x, {ip, port} = init({ip, port});
14161
 *
14162
 * var x, $__0 = init({ip, port}), ip = $__0.ip, port = $__0.port;
14163
 *
14164
 */
14165
var Syntax = _dereq_('esprima-fb').Syntax;
14166
var utils = _dereq_('../src/utils');
14167
14168
var reservedWordsHelper = _dereq_('./reserved-words-helper');
14169
var restParamVisitors = _dereq_('./es6-rest-param-visitors');
14170
var restPropertyHelpers = _dereq_('./es7-rest-property-helpers');
14171
14172
// -------------------------------------------------------
14173
// 1. Structured variable declarations.
14174
//
14175
// var [a, b] = [b, a];
14176
// var {x, y} = {y, x};
14177
// -------------------------------------------------------
14178
14179
function visitStructuredVariable(traverse, node, path, state) {
14180
  // Allocate new temp for the pattern.
14181
  utils.append(utils.getTempVar(state.localScope.tempVarIndex) + '=', state);
14182
  // Skip the pattern and assign the init to the temp.
14183
  utils.catchupWhiteSpace(node.init.range[0], state);
14184
  traverse(node.init, path, state);
14185
  utils.catchup(node.init.range[1], state);
14186
  // Render the destructured data.
14187
  utils.append(',' + getDestructuredComponents(node.id, state), state);
14188
  state.localScope.tempVarIndex++;
14189
  return false;
14190
}
14191
14192
visitStructuredVariable.test = function(node, path, state) {
0 ignored issues
show
Unused Code introduced by
The parameter state is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
Unused Code introduced by
The parameter path is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
14193
  return node.type === Syntax.VariableDeclarator &&
14194
    isStructuredPattern(node.id);
14195
};
14196
14197
function isStructuredPattern(node) {
14198
  return node.type === Syntax.ObjectPattern ||
14199
    node.type === Syntax.ArrayPattern;
14200
}
14201
14202
// Main function which does actual recursive destructuring
14203
// of nested complex structures.
14204
function getDestructuredComponents(node, state) {
14205
  var tmpIndex = state.localScope.tempVarIndex;
14206
  var components = [];
14207
  var patternItems = getPatternItems(node);
14208
14209
  for (var idx = 0; idx < patternItems.length; idx++) {
14210
    var item = patternItems[idx];
14211
    if (!item) {
14212
      continue;
14213
    }
14214
14215
    if (item.type === Syntax.SpreadElement) {
14216
      // Spread/rest of an array.
14217
      // TODO(dmitrys): support spread in the middle of a pattern
14218
      // and also for function param patterns: [x, ...xs, y]
14219
      components.push(item.argument.name +
14220
        '=Array.prototype.slice.call(' +
14221
        utils.getTempVar(tmpIndex) + ',' + idx + ')'
14222
      );
14223
      continue;
14224
    }
14225
14226
    if (item.type === Syntax.SpreadProperty) {
14227
      var restExpression = restPropertyHelpers.renderRestExpression(
14228
        utils.getTempVar(tmpIndex),
14229
        patternItems
14230
      );
14231
      components.push(item.argument.name + '=' + restExpression);
14232
      continue;
14233
    }
14234
14235
    // Depending on pattern type (Array or Object), we get
14236
    // corresponding pattern item parts.
14237
    var accessor = getPatternItemAccessor(node, item, tmpIndex, idx);
14238
    var value = getPatternItemValue(node, item);
14239
14240
    // TODO(dmitrys): implement default values: {x, y=5}
14241
    if (value.type === Syntax.Identifier) {
14242
      // Simple pattern item.
14243
      components.push(value.name + '=' + accessor);
14244
    } else {
14245
      // Complex sub-structure.
14246
      components.push(
14247
        utils.getTempVar(++state.localScope.tempVarIndex) + '=' + accessor +
14248
        ',' + getDestructuredComponents(value, state)
14249
      );
14250
    }
14251
  }
14252
14253
  return components.join(',');
14254
}
14255
14256
function getPatternItems(node) {
14257
  return node.properties || node.elements;
14258
}
14259
14260
function getPatternItemAccessor(node, patternItem, tmpIndex, idx) {
14261
  var tmpName = utils.getTempVar(tmpIndex);
14262
  if (node.type === Syntax.ObjectPattern) {
14263
    if (reservedWordsHelper.isReservedWord(patternItem.key.name)) {
14264
      return tmpName + '["' + patternItem.key.name + '"]';
14265
    } else if (patternItem.key.type === Syntax.Literal) {
14266
      return tmpName + '[' + JSON.stringify(patternItem.key.value) + ']';
14267
    } else if (patternItem.key.type === Syntax.Identifier) {
0 ignored issues
show
Complexity Best Practice introduced by
There is no return statement if patternItem.key.type === Syntax.Identifier is false. Are you sure this is correct? If so, consider adding return; explicitly.

This check looks for functions where a return statement is found in some execution paths, but not in all.

Consider this little piece of code

function isBig(a) {
    if (a > 5000) {
        return "yes";
    }
}

console.log(isBig(5001)); //returns yes
console.log(isBig(42)); //returns undefined

The function isBig will only return a specific value when its parameter is bigger than 5000. In any other case, it will implicitly return undefined.

This behaviour may not be what you had intended. In any case, you can add a return undefined to the other execution path to make the return value explicit.

Loading history...
14268
      return tmpName + '.' + patternItem.key.name;
14269
    }
14270
  } else if (node.type === Syntax.ArrayPattern) {
0 ignored issues
show
Complexity Best Practice introduced by
There is no return statement if node.type === Syntax.ArrayPattern is false. Are you sure this is correct? If so, consider adding return; explicitly.

This check looks for functions where a return statement is found in some execution paths, but not in all.

Consider this little piece of code

function isBig(a) {
    if (a > 5000) {
        return "yes";
    }
}

console.log(isBig(5001)); //returns yes
console.log(isBig(42)); //returns undefined

The function isBig will only return a specific value when its parameter is bigger than 5000. In any other case, it will implicitly return undefined.

This behaviour may not be what you had intended. In any case, you can add a return undefined to the other execution path to make the return value explicit.

Loading history...
14271
    return tmpName + '[' + idx + ']';
14272
  }
14273
}
14274
14275
function getPatternItemValue(node, patternItem) {
14276
  return node.type === Syntax.ObjectPattern
14277
    ? patternItem.value
14278
    : patternItem;
14279
}
14280
14281
// -------------------------------------------------------
14282
// 2. Assignment expression.
14283
//
14284
// [a, b] = [b, a];
14285
// ({x, y} = {y, x});
14286
// -------------------------------------------------------
14287
14288
function visitStructuredAssignment(traverse, node, path, state) {
14289
  var exprNode = node.expression;
14290
  utils.append('var ' + utils.getTempVar(state.localScope.tempVarIndex) + '=', state);
14291
14292
  utils.catchupWhiteSpace(exprNode.right.range[0], state);
14293
  traverse(exprNode.right, path, state);
14294
  utils.catchup(exprNode.right.range[1], state);
14295
14296
  utils.append(
14297
    ';' + getDestructuredComponents(exprNode.left, state) + ';',
14298
    state
14299
  );
14300
14301
  utils.catchupWhiteSpace(node.range[1], state);
14302
  state.localScope.tempVarIndex++;
14303
  return false;
14304
}
14305
14306
visitStructuredAssignment.test = function(node, path, state) {
0 ignored issues
show
Unused Code introduced by
The parameter state is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
Unused Code introduced by
The parameter path is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
14307
  // We consider the expression statement rather than just assignment
14308
  // expression to cover case with object patters which should be
14309
  // wrapped in grouping operator: ({x, y} = {y, x});
14310
  return node.type === Syntax.ExpressionStatement &&
14311
    node.expression.type === Syntax.AssignmentExpression &&
14312
    isStructuredPattern(node.expression.left);
14313
};
14314
14315
// -------------------------------------------------------
14316
// 3. Structured parameter.
14317
//
14318
// function foo({x, y}) { ... }
14319
// -------------------------------------------------------
14320
14321
function visitStructuredParameter(traverse, node, path, state) {
14322
  utils.append(utils.getTempVar(getParamIndex(node, path)), state);
14323
  utils.catchupWhiteSpace(node.range[1], state);
14324
  return true;
14325
}
14326
14327
function getParamIndex(paramNode, path) {
14328
  var funcNode = path[0];
14329
  var tmpIndex = 0;
14330
  for (var k = 0; k < funcNode.params.length; k++) {
14331
    var param = funcNode.params[k];
14332
    if (param === paramNode) {
14333
      break;
14334
    }
14335
    if (isStructuredPattern(param)) {
14336
      tmpIndex++;
14337
    }
14338
  }
14339
  return tmpIndex;
14340
}
14341
14342
visitStructuredParameter.test = function(node, path, state) {
0 ignored issues
show
Unused Code introduced by
The parameter state is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
14343
  return isStructuredPattern(node) && isFunctionNode(path[0]);
14344
};
14345
14346
function isFunctionNode(node) {
14347
  return (node.type == Syntax.FunctionDeclaration ||
14348
    node.type == Syntax.FunctionExpression ||
14349
    node.type == Syntax.MethodDefinition ||
14350
    node.type == Syntax.ArrowFunctionExpression);
14351
}
14352
14353
// -------------------------------------------------------
14354
// 4. Function body for structured parameters.
14355
//
14356
// function foo({x, y}) { x; y; }
14357
// -------------------------------------------------------
14358
14359
function visitFunctionBodyForStructuredParameter(traverse, node, path, state) {
14360
  var funcNode = path[0];
14361
14362
  utils.catchup(funcNode.body.range[0] + 1, state);
14363
  renderDestructuredComponents(funcNode, state);
14364
14365
  if (funcNode.rest) {
14366
    utils.append(
14367
      restParamVisitors.renderRestParamSetup(funcNode, state),
14368
      state
14369
    );
14370
  }
14371
14372
  return true;
14373
}
14374
14375
function renderDestructuredComponents(funcNode, state) {
14376
  var destructuredComponents = [];
14377
14378
  for (var k = 0; k < funcNode.params.length; k++) {
14379
    var param = funcNode.params[k];
14380
    if (isStructuredPattern(param)) {
14381
      destructuredComponents.push(
14382
        getDestructuredComponents(param, state)
14383
      );
14384
      state.localScope.tempVarIndex++;
14385
    }
14386
  }
14387
14388
  if (destructuredComponents.length) {
14389
    utils.append('var ' + destructuredComponents.join(',') + ';', state);
14390
  }
14391
}
14392
14393
visitFunctionBodyForStructuredParameter.test = function(node, path, state) {
0 ignored issues
show
Unused Code introduced by
The parameter state is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
14394
  return node.type === Syntax.BlockStatement && isFunctionNode(path[0]);
14395
};
14396
14397
exports.visitorList = [
14398
  visitStructuredVariable,
14399
  visitStructuredAssignment,
14400
  visitStructuredParameter,
14401
  visitFunctionBodyForStructuredParameter
14402
];
14403
14404
exports.renderDestructuredComponents = renderDestructuredComponents;
14405
14406
14407
},{"../src/utils":23,"./es6-rest-param-visitors":30,"./es7-rest-property-helpers":32,"./reserved-words-helper":34,"esprima-fb":9}],28:[function(_dereq_,module,exports){
14408
/**
14409
 * Copyright 2013 Facebook, Inc.
14410
 *
14411
 * Licensed under the Apache License, Version 2.0 (the "License");
14412
 * you may not use this file except in compliance with the License.
14413
 * You may obtain a copy of the License at
14414
 *
14415
 * http://www.apache.org/licenses/LICENSE-2.0
14416
 *
14417
 * Unless required by applicable law or agreed to in writing, software
14418
 * distributed under the License is distributed on an "AS IS" BASIS,
14419
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14420
 * See the License for the specific language governing permissions and
14421
 * limitations under the License.
14422
 */
14423
14424
/*jslint node:true*/
14425
14426
/**
14427
 * Desugars concise methods of objects to function expressions.
14428
 *
14429
 * var foo = {
14430
 *   method(x, y) { ... }
14431
 * };
14432
 *
14433
 * var foo = {
14434
 *   method: function(x, y) { ... }
14435
 * };
14436
 *
14437
 */
14438
14439
var Syntax = _dereq_('esprima-fb').Syntax;
14440
var utils = _dereq_('../src/utils');
14441
var reservedWordsHelper = _dereq_('./reserved-words-helper');
14442
14443
function visitObjectConciseMethod(traverse, node, path, state) {
14444
  var isGenerator = node.value.generator;
14445
  if (isGenerator) {
14446
    utils.catchupWhiteSpace(node.range[0] + 1, state);
14447
  }
14448
  if (node.computed) { // [<expr>]() { ...}
14449
    utils.catchup(node.key.range[1] + 1, state);
14450
  } else if (reservedWordsHelper.isReservedWord(node.key.name)) {
14451
    utils.catchup(node.key.range[0], state);
14452
    utils.append('"', state);
14453
    utils.catchup(node.key.range[1], state);
14454
    utils.append('"', state);
14455
  }
14456
14457
  utils.catchup(node.key.range[1], state);
14458
  utils.append(
14459
    ':function' + (isGenerator ? '*' : ''),
14460
    state
14461
  );
14462
  path.unshift(node);
14463
  traverse(node.value, path, state);
14464
  path.shift();
14465
  return false;
14466
}
14467
14468
visitObjectConciseMethod.test = function(node, path, state) {
0 ignored issues
show
Unused Code introduced by
The parameter path is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
Unused Code introduced by
The parameter state is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
14469
  return node.type === Syntax.Property &&
14470
    node.value.type === Syntax.FunctionExpression &&
14471
    node.method === true;
14472
};
14473
14474
exports.visitorList = [
14475
  visitObjectConciseMethod
14476
];
14477
14478
},{"../src/utils":23,"./reserved-words-helper":34,"esprima-fb":9}],29:[function(_dereq_,module,exports){
14479
/**
14480
 * Copyright 2013 Facebook, Inc.
14481
 *
14482
 * Licensed under the Apache License, Version 2.0 (the "License");
14483
 * you may not use this file except in compliance with the License.
14484
 * You may obtain a copy of the License at
14485
 *
14486
 * http://www.apache.org/licenses/LICENSE-2.0
14487
 *
14488
 * Unless required by applicable law or agreed to in writing, software
14489
 * distributed under the License is distributed on an "AS IS" BASIS,
14490
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14491
 * See the License for the specific language governing permissions and
14492
 * limitations under the License.
14493
 */
14494
14495
/*jslint node: true*/
14496
14497
/**
14498
 * Desugars ES6 Object Literal short notations into ES3 full notation.
14499
 *
14500
 * // Easier return values.
14501
 * function foo(x, y) {
14502
 *   return {x, y}; // {x: x, y: y}
14503
 * };
14504
 *
14505
 * // Destructuring.
14506
 * function init({port, ip, coords: {x, y}}) { ... }
14507
 *
14508
 */
14509
var Syntax = _dereq_('esprima-fb').Syntax;
14510
var utils = _dereq_('../src/utils');
14511
14512
/**
14513
 * @public
14514
 */
14515
function visitObjectLiteralShortNotation(traverse, node, path, state) {
14516
  utils.catchup(node.key.range[1], state);
14517
  utils.append(':' + node.key.name, state);
14518
  return false;
14519
}
14520
14521
visitObjectLiteralShortNotation.test = function(node, path, state) {
0 ignored issues
show
Unused Code introduced by
The parameter state is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
14522
  return node.type === Syntax.Property &&
14523
    node.kind === 'init' &&
14524
    node.shorthand === true &&
14525
    path[0].type !== Syntax.ObjectPattern;
14526
};
14527
14528
exports.visitorList = [
14529
  visitObjectLiteralShortNotation
14530
];
14531
14532
14533
},{"../src/utils":23,"esprima-fb":9}],30:[function(_dereq_,module,exports){
14534
/**
14535
 * Copyright 2013 Facebook, Inc.
14536
 *
14537
 * Licensed under the Apache License, Version 2.0 (the "License");
14538
 * you may not use this file except in compliance with the License.
14539
 * You may obtain a copy of the License at
14540
 *
14541
 * http://www.apache.org/licenses/LICENSE-2.0
14542
 *
14543
 * Unless required by applicable law or agreed to in writing, software
14544
 * distributed under the License is distributed on an "AS IS" BASIS,
14545
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14546
 * See the License for the specific language governing permissions and
14547
 * limitations under the License.
14548
 */
14549
14550
/*jslint node:true*/
14551
14552
/**
14553
 * Desugars ES6 rest parameters into an ES3 arguments array.
14554
 *
14555
 * function printf(template, ...args) {
14556
 *   args.forEach(...);
14557
 * }
14558
 *
14559
 * We could use `Array.prototype.slice.call`, but that usage of arguments causes
14560
 * functions to be deoptimized in V8, so instead we use a for-loop.
14561
 *
14562
 * function printf(template) {
14563
 *   for (var args = [], $__0 = 1, $__1 = arguments.length; $__0 < $__1; $__0++)
14564
 *     args.push(arguments[$__0]);
14565
 *   args.forEach(...);
14566
 * }
14567
 *
14568
 */
14569
var Syntax = _dereq_('esprima-fb').Syntax;
14570
var utils = _dereq_('../src/utils');
14571
14572
14573
14574
function _nodeIsFunctionWithRestParam(node) {
14575
  return (node.type === Syntax.FunctionDeclaration
14576
          || node.type === Syntax.FunctionExpression
14577
          || node.type === Syntax.ArrowFunctionExpression)
14578
         && node.rest;
14579
}
14580
14581
function visitFunctionParamsWithRestParam(traverse, node, path, state) {
14582
  if (node.parametricType) {
14583
    utils.catchup(node.parametricType.range[0], state);
14584
    path.unshift(node);
14585
    traverse(node.parametricType, path, state);
14586
    path.shift();
14587
  }
14588
14589
  // Render params.
14590
  if (node.params.length) {
14591
    path.unshift(node);
14592
    traverse(node.params, path, state);
14593
    path.shift();
14594
  } else {
14595
    // -3 is for ... of the rest.
14596
    utils.catchup(node.rest.range[0] - 3, state);
14597
  }
14598
  utils.catchupWhiteSpace(node.rest.range[1], state);
14599
14600
  path.unshift(node);
14601
  traverse(node.body, path, state);
14602
  path.shift();
14603
14604
  return false;
14605
}
14606
14607
visitFunctionParamsWithRestParam.test = function(node, path, state) {
0 ignored issues
show
Unused Code introduced by
The parameter path is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
Unused Code introduced by
The parameter state is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
14608
  return _nodeIsFunctionWithRestParam(node);
14609
};
14610
14611
function renderRestParamSetup(functionNode, state) {
14612
  var idx = state.localScope.tempVarIndex++;
0 ignored issues
show
Unused Code introduced by
The assignment to variable idx seems to be never used. Consider removing it.
Loading history...
14613
  var len = state.localScope.tempVarIndex++;
0 ignored issues
show
Unused Code introduced by
The assignment to variable len seems to be never used. Consider removing it.
Loading history...
14614
14615
  return 'for (var ' + functionNode.rest.name + '=[],' +
14616
    utils.getTempVar(idx) + '=' + functionNode.params.length + ',' +
14617
    utils.getTempVar(len) + '=arguments.length;' +
14618
    utils.getTempVar(idx) + '<' +  utils.getTempVar(len) + ';' +
14619
    utils.getTempVar(idx) + '++) ' +
14620
    functionNode.rest.name + '.push(arguments[' + utils.getTempVar(idx) + ']);';
14621
}
14622
14623
function visitFunctionBodyWithRestParam(traverse, node, path, state) {
14624
  utils.catchup(node.range[0] + 1, state);
14625
  var parentNode = path[0];
14626
  utils.append(renderRestParamSetup(parentNode, state), state);
14627
  return true;
14628
}
14629
14630
visitFunctionBodyWithRestParam.test = function(node, path, state) {
0 ignored issues
show
Unused Code introduced by
The parameter state is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
14631
  return node.type === Syntax.BlockStatement
14632
         && _nodeIsFunctionWithRestParam(path[0]);
14633
};
14634
14635
exports.renderRestParamSetup = renderRestParamSetup;
14636
exports.visitorList = [
14637
  visitFunctionParamsWithRestParam,
14638
  visitFunctionBodyWithRestParam
14639
];
14640
14641
},{"../src/utils":23,"esprima-fb":9}],31:[function(_dereq_,module,exports){
14642
/**
14643
 * Copyright 2013 Facebook, Inc.
14644
 *
14645
 * Licensed under the Apache License, Version 2.0 (the "License");
14646
 * you may not use this file except in compliance with the License.
14647
 * You may obtain a copy of the License at
14648
 *
14649
 * http://www.apache.org/licenses/LICENSE-2.0
14650
 *
14651
 * Unless required by applicable law or agreed to in writing, software
14652
 * distributed under the License is distributed on an "AS IS" BASIS,
14653
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14654
 * See the License for the specific language governing permissions and
14655
 * limitations under the License.
14656
 */
14657
14658
/*jslint node:true*/
14659
14660
/**
14661
 * @typechecks
14662
 */
14663
'use strict';
14664
14665
var Syntax = _dereq_('esprima-fb').Syntax;
14666
var utils = _dereq_('../src/utils');
14667
14668
/**
14669
 * http://people.mozilla.org/~jorendorff/es6-draft.html#sec-12.1.9
14670
 */
14671
function visitTemplateLiteral(traverse, node, path, state) {
14672
  var templateElements = node.quasis;
14673
14674
  utils.append('(', state);
14675
  for (var ii = 0; ii < templateElements.length; ii++) {
14676
    var templateElement = templateElements[ii];
14677
    if (templateElement.value.raw !== '') {
14678
      utils.append(getCookedValue(templateElement), state);
14679
      if (!templateElement.tail) {
14680
        // + between element and substitution
14681
        utils.append(' + ', state);
14682
      }
14683
      // maintain line numbers
14684
      utils.move(templateElement.range[0], state);
14685
      utils.catchupNewlines(templateElement.range[1], state);
14686
    } else {  // templateElement.value.raw === ''
14687
      // Concatenat adjacent substitutions, e.g. `${x}${y}`. Empty templates
14688
      // appear before the first and after the last element - nothing to add in
14689
      // those cases.
14690
      if (ii > 0 && !templateElement.tail) {
14691
        // + between substitution and substitution
14692
        utils.append(' + ', state);
14693
      }
14694
    }
14695
14696
    utils.move(templateElement.range[1], state);
14697
    if (!templateElement.tail) {
14698
      var substitution = node.expressions[ii];
14699
      if (substitution.type === Syntax.Identifier ||
14700
          substitution.type === Syntax.MemberExpression ||
14701
          substitution.type === Syntax.CallExpression) {
14702
        utils.catchup(substitution.range[1], state);
14703
      } else {
14704
        utils.append('(', state);
14705
        traverse(substitution, path, state);
14706
        utils.catchup(substitution.range[1], state);
14707
        utils.append(')', state);
14708
      }
14709
      // if next templateElement isn't empty...
14710
      if (templateElements[ii + 1].value.cooked !== '') {
14711
        utils.append(' + ', state);
14712
      }
14713
    }
14714
  }
14715
  utils.move(node.range[1], state);
14716
  utils.append(')', state);
14717
  return false;
14718
}
14719
14720
visitTemplateLiteral.test = function(node, path, state) {
0 ignored issues
show
Unused Code introduced by
The parameter path is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
Unused Code introduced by
The parameter state is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
14721
  return node.type === Syntax.TemplateLiteral;
14722
};
14723
14724
/**
14725
 * http://people.mozilla.org/~jorendorff/es6-draft.html#sec-12.2.6
14726
 */
14727
function visitTaggedTemplateExpression(traverse, node, path, state) {
14728
  var template = node.quasi;
14729
  var numQuasis = template.quasis.length;
14730
14731
  // print the tag
14732
  utils.move(node.tag.range[0], state);
14733
  traverse(node.tag, path, state);
14734
  utils.catchup(node.tag.range[1], state);
14735
14736
  // print array of template elements
14737
  utils.append('(function() { var siteObj = [', state);
14738
  for (var ii = 0; ii < numQuasis; ii++) {
14739
    utils.append(getCookedValue(template.quasis[ii]), state);
14740
    if (ii !== numQuasis - 1) {
14741
      utils.append(', ', state);
14742
    }
14743
  }
14744
  utils.append(']; siteObj.raw = [', state);
14745
  for (ii = 0; ii < numQuasis; ii++) {
14746
    utils.append(getRawValue(template.quasis[ii]), state);
14747
    if (ii !== numQuasis - 1) {
14748
      utils.append(', ', state);
14749
    }
14750
  }
14751
  utils.append(
14752
    ']; Object.freeze(siteObj.raw); Object.freeze(siteObj); return siteObj; }()',
14753
    state
14754
  );
14755
14756
  // print substitutions
14757
  if (numQuasis > 1) {
14758
    for (ii = 0; ii < template.expressions.length; ii++) {
14759
      var expression = template.expressions[ii];
14760
      utils.append(', ', state);
14761
14762
      // maintain line numbers by calling catchupWhiteSpace over the whole
14763
      // previous TemplateElement
14764
      utils.move(template.quasis[ii].range[0], state);
14765
      utils.catchupNewlines(template.quasis[ii].range[1], state);
14766
14767
      utils.move(expression.range[0], state);
14768
      traverse(expression, path, state);
14769
      utils.catchup(expression.range[1], state);
14770
    }
14771
  }
14772
14773
  // print blank lines to push the closing ) down to account for the final
14774
  // TemplateElement.
14775
  utils.catchupNewlines(node.range[1], state);
14776
14777
  utils.append(')', state);
14778
14779
  return false;
14780
}
14781
14782
visitTaggedTemplateExpression.test = function(node, path, state) {
0 ignored issues
show
Unused Code introduced by
The parameter path is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
Unused Code introduced by
The parameter state is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
14783
  return node.type === Syntax.TaggedTemplateExpression;
14784
};
14785
14786
function getCookedValue(templateElement) {
14787
  return JSON.stringify(templateElement.value.cooked);
14788
}
14789
14790
function getRawValue(templateElement) {
14791
  return JSON.stringify(templateElement.value.raw);
14792
}
14793
14794
exports.visitorList = [
14795
  visitTemplateLiteral,
14796
  visitTaggedTemplateExpression
14797
];
14798
14799
},{"../src/utils":23,"esprima-fb":9}],32:[function(_dereq_,module,exports){
14800
/**
14801
 * Copyright 2013 Facebook, Inc.
14802
 *
14803
 * Licensed under the Apache License, Version 2.0 (the "License");
14804
 * you may not use this file except in compliance with the License.
14805
 * You may obtain a copy of the License at
14806
 *
14807
 * http://www.apache.org/licenses/LICENSE-2.0
14808
 *
14809
 * Unless required by applicable law or agreed to in writing, software
14810
 * distributed under the License is distributed on an "AS IS" BASIS,
14811
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14812
 * See the License for the specific language governing permissions and
14813
 * limitations under the License.
14814
 */
14815
14816
/*jslint node:true*/
14817
14818
/**
14819
 * Desugars ES7 rest properties into ES5 object iteration.
14820
 */
14821
14822
var Syntax = _dereq_('esprima-fb').Syntax;
14823
14824
// TODO: This is a pretty massive helper, it should only be defined once, in the
14825
// transform's runtime environment. We don't currently have a runtime though.
14826
var restFunction =
14827
  '(function(source, exclusion) {' +
14828
    'var rest = {};' +
14829
    'var hasOwn = Object.prototype.hasOwnProperty;' +
14830
    'if (source == null) {' +
14831
      'throw new TypeError();' +
14832
    '}' +
14833
    'for (var key in source) {' +
14834
      'if (hasOwn.call(source, key) && !hasOwn.call(exclusion, key)) {' +
14835
        'rest[key] = source[key];' +
14836
      '}' +
14837
    '}' +
14838
    'return rest;' +
14839
  '})';
14840
14841
function getPropertyNames(properties) {
14842
  var names = [];
14843
  for (var i = 0; i < properties.length; i++) {
14844
    var property = properties[i];
14845
    if (property.type === Syntax.SpreadProperty) {
14846
      continue;
14847
    }
14848
    if (property.type === Syntax.Identifier) {
14849
      names.push(property.name);
14850
    } else {
14851
      names.push(property.key.name);
14852
    }
14853
  }
14854
  return names;
14855
}
14856
14857
function getRestFunctionCall(source, exclusion) {
14858
  return restFunction + '(' + source + ',' + exclusion + ')';
14859
}
14860
14861
function getSimpleShallowCopy(accessorExpression) {
14862
  // This could be faster with 'Object.assign({}, ' + accessorExpression + ')'
14863
  // but to unify code paths and avoid a ES6 dependency we use the same
14864
  // helper as for the exclusion case.
14865
  return getRestFunctionCall(accessorExpression, '{}');
14866
}
14867
14868
function renderRestExpression(accessorExpression, excludedProperties) {
14869
  var excludedNames = getPropertyNames(excludedProperties);
14870
  if (!excludedNames.length) {
14871
    return getSimpleShallowCopy(accessorExpression);
14872
  }
14873
  return getRestFunctionCall(
14874
    accessorExpression,
14875
    '{' + excludedNames.join(':1,') + ':1}'
14876
  );
14877
}
14878
14879
exports.renderRestExpression = renderRestExpression;
14880
14881
},{"esprima-fb":9}],33:[function(_dereq_,module,exports){
14882
/**
14883
 * Copyright 2004-present Facebook. All Rights Reserved.
14884
 */
14885
/*global exports:true*/
14886
14887
/**
14888
 * Implements ES7 object spread property.
14889
 * https://gist.github.com/sebmarkbage/aa849c7973cb4452c547
14890
 *
14891
 * { ...a, x: 1 }
14892
 *
14893
 * Object.assign({}, a, {x: 1 })
14894
 *
14895
 */
14896
14897
var Syntax = _dereq_('esprima-fb').Syntax;
14898
var utils = _dereq_('../src/utils');
14899
14900
function visitObjectLiteralSpread(traverse, node, path, state) {
14901
  utils.catchup(node.range[0], state);
14902
14903
  utils.append('Object.assign({', state);
14904
14905
  // Skip the original {
14906
  utils.move(node.range[0] + 1, state);
14907
14908
  var previousWasSpread = false;
14909
14910
  for (var i = 0; i < node.properties.length; i++) {
14911
    var property = node.properties[i];
14912
    if (property.type === Syntax.SpreadProperty) {
14913
14914
      // Close the previous object or initial object
14915
      if (!previousWasSpread) {
14916
        utils.append('}', state);
14917
      }
14918
14919
      if (i === 0) {
14920
        // Normally there will be a comma when we catch up, but not before
14921
        // the first property.
14922
        utils.append(',', state);
14923
      }
14924
14925
      utils.catchup(property.range[0], state);
14926
14927
      // skip ...
14928
      utils.move(property.range[0] + 3, state);
14929
14930
      traverse(property.argument, path, state);
14931
14932
      utils.catchup(property.range[1], state);
14933
14934
      previousWasSpread = true;
14935
14936
    } else {
14937
14938
      utils.catchup(property.range[0], state);
14939
14940
      if (previousWasSpread) {
14941
        utils.append('{', state);
14942
      }
14943
14944
      traverse(property, path, state);
14945
14946
      utils.catchup(property.range[1], state);
14947
14948
      previousWasSpread = false;
14949
14950
    }
14951
  }
14952
14953
  // Strip any non-whitespace between the last item and the end.
14954
  // We only catch up on whitespace so that we ignore any trailing commas which
14955
  // are stripped out for IE8 support. Unfortunately, this also strips out any
14956
  // trailing comments.
14957
  utils.catchupWhiteSpace(node.range[1] - 1, state);
14958
14959
  // Skip the trailing }
14960
  utils.move(node.range[1], state);
14961
14962
  if (!previousWasSpread) {
14963
    utils.append('}', state);
14964
  }
14965
14966
  utils.append(')', state);
14967
  return false;
14968
}
14969
14970
visitObjectLiteralSpread.test = function(node, path, state) {
0 ignored issues
show
Unused Code introduced by
The parameter path is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
Unused Code introduced by
The parameter state is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
14971
  if (node.type !== Syntax.ObjectExpression) {
14972
    return false;
14973
  }
14974
  // Tight loop optimization
14975
  var hasAtLeastOneSpreadProperty = false;
14976
  for (var i = 0; i < node.properties.length; i++) {
14977
    var property = node.properties[i];
14978
    if (property.type === Syntax.SpreadProperty) {
14979
      hasAtLeastOneSpreadProperty = true;
14980
    } else if (property.kind !== 'init') {
14981
      return false;
14982
    }
14983
  }
14984
  return hasAtLeastOneSpreadProperty;
14985
};
14986
14987
exports.visitorList = [
14988
  visitObjectLiteralSpread
14989
];
14990
14991
},{"../src/utils":23,"esprima-fb":9}],34:[function(_dereq_,module,exports){
14992
/**
14993
 * Copyright 2014 Facebook, Inc.
14994
 *
14995
 * Licensed under the Apache License, Version 2.0 (the "License");
14996
 * you may not use this file except in compliance with the License.
14997
 * You may obtain a copy of the License at
14998
 *
14999
 * http://www.apache.org/licenses/LICENSE-2.0
15000
 *
15001
 * Unless required by applicable law or agreed to in writing, software
15002
 * distributed under the License is distributed on an "AS IS" BASIS,
15003
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15004
 * See the License for the specific language governing permissions and
15005
 * limitations under the License.
15006
 */
15007
15008
var KEYWORDS = [
15009
  'break', 'do', 'in', 'typeof', 'case', 'else', 'instanceof', 'var', 'catch',
15010
  'export', 'new', 'void', 'class', 'extends', 'return', 'while', 'const',
15011
  'finally', 'super', 'with', 'continue', 'for', 'switch', 'yield', 'debugger',
15012
  'function', 'this', 'default', 'if', 'throw', 'delete', 'import', 'try'
15013
];
15014
15015
var FUTURE_RESERVED_WORDS = [
15016
  'enum', 'await', 'implements', 'package', 'protected', 'static', 'interface',
15017
  'private', 'public'
15018
];
15019
15020
var LITERALS = [
15021
  'null',
15022
  'true',
15023
  'false'
15024
];
15025
15026
// https://people.mozilla.org/~jorendorff/es6-draft.html#sec-reserved-words
15027
var RESERVED_WORDS = [].concat(
15028
  KEYWORDS,
15029
  FUTURE_RESERVED_WORDS,
15030
  LITERALS
15031
);
15032
15033
var reservedWordsMap = Object.create(null);
15034
RESERVED_WORDS.forEach(function(k) {
15035
    reservedWordsMap[k] = true;
15036
});
15037
15038
/**
15039
 * This list should not grow as new reserved words are introdued. This list is
15040
 * of words that need to be quoted because ES3-ish browsers do not allow their
15041
 * use as identifier names.
15042
 */
15043
var ES3_FUTURE_RESERVED_WORDS = [
15044
  'enum', 'implements', 'package', 'protected', 'static', 'interface',
15045
  'private', 'public'
15046
];
15047
15048
var ES3_RESERVED_WORDS = [].concat(
15049
  KEYWORDS,
15050
  ES3_FUTURE_RESERVED_WORDS,
15051
  LITERALS
15052
);
15053
15054
var es3ReservedWordsMap = Object.create(null);
15055
ES3_RESERVED_WORDS.forEach(function(k) {
15056
    es3ReservedWordsMap[k] = true;
15057
});
15058
15059
exports.isReservedWord = function(word) {
15060
  return !!reservedWordsMap[word];
15061
};
15062
15063
exports.isES3ReservedWord = function(word) {
15064
  return !!es3ReservedWordsMap[word];
15065
};
15066
15067
},{}],35:[function(_dereq_,module,exports){
15068
/**
15069
 * Copyright 2014 Facebook, Inc.
15070
 *
15071
 * Licensed under the Apache License, Version 2.0 (the "License");
15072
 * you may not use this file except in compliance with the License.
15073
 * You may obtain a copy of the License at
15074
 *
15075
 * http://www.apache.org/licenses/LICENSE-2.0
15076
 *
15077
 * Unless required by applicable law or agreed to in writing, software
15078
 * distributed under the License is distributed on an "AS IS" BASIS,
15079
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15080
 * See the License for the specific language governing permissions and
15081
 * limitations under the License.
15082
 *
15083
 */
15084
/*global exports:true*/
15085
15086
var Syntax = _dereq_('esprima-fb').Syntax;
15087
var utils = _dereq_('../src/utils');
15088
var reserverdWordsHelper = _dereq_('./reserved-words-helper');
15089
15090
/**
15091
 * Code adapted from https://github.com/spicyj/es3ify
15092
 * The MIT License (MIT)
15093
 * Copyright (c) 2014 Ben Alpert
15094
 */
15095
15096
function visitProperty(traverse, node, path, state) {
15097
  utils.catchup(node.key.range[0], state);
15098
  utils.append('"', state);
15099
  utils.catchup(node.key.range[1], state);
15100
  utils.append('"', state);
15101
  utils.catchup(node.value.range[0], state);
15102
  traverse(node.value, path, state);
15103
  return false;
15104
}
15105
15106
visitProperty.test = function(node) {
15107
  return node.type === Syntax.Property &&
15108
    node.key.type === Syntax.Identifier &&
15109
    !node.method &&
15110
    !node.shorthand &&
15111
    !node.computed &&
15112
    reserverdWordsHelper.isES3ReservedWord(node.key.name);
15113
};
15114
15115
function visitMemberExpression(traverse, node, path, state) {
15116
  traverse(node.object, path, state);
15117
  utils.catchup(node.property.range[0] - 1, state);
15118
  utils.append('[', state);
15119
  utils.catchupWhiteSpace(node.property.range[0], state);
15120
  utils.append('"', state);
15121
  utils.catchup(node.property.range[1], state);
15122
  utils.append('"]', state);
15123
  return false;
15124
}
15125
15126
visitMemberExpression.test = function(node) {
15127
  return node.type === Syntax.MemberExpression &&
15128
    node.property.type === Syntax.Identifier &&
15129
    reserverdWordsHelper.isES3ReservedWord(node.property.name);
15130
};
15131
15132
exports.visitorList = [
15133
  visitProperty,
15134
  visitMemberExpression
15135
];
15136
15137
},{"../src/utils":23,"./reserved-words-helper":34,"esprima-fb":9}],36:[function(_dereq_,module,exports){
15138
var esprima = _dereq_('esprima-fb');
15139
var utils = _dereq_('../src/utils');
15140
15141
var Syntax = esprima.Syntax;
15142
15143
function _isFunctionNode(node) {
15144
  return node.type === Syntax.FunctionDeclaration
15145
         || node.type === Syntax.FunctionExpression
15146
         || node.type === Syntax.ArrowFunctionExpression;
15147
}
15148
15149
function visitClassProperty(traverse, node, path, state) {
15150
  utils.catchup(node.range[0], state);
15151
  utils.catchupWhiteOut(node.range[1], state);
15152
  return false;
15153
}
15154
visitClassProperty.test = function(node, path, state) {
0 ignored issues
show
Unused Code introduced by
The parameter path is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
Unused Code introduced by
The parameter state is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
15155
  return node.type === Syntax.ClassProperty;
15156
};
15157
15158
function visitTypeAlias(traverse, node, path, state) {
15159
  utils.catchupWhiteOut(node.range[1], state);
15160
  return false;
15161
}
15162
visitTypeAlias.test = function(node, path, state) {
0 ignored issues
show
Unused Code introduced by
The parameter path is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
Unused Code introduced by
The parameter state is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
15163
  return node.type === Syntax.TypeAlias;
15164
};
15165
15166
function visitTypeCast(traverse, node, path, state) {
15167
  path.unshift(node);
15168
  traverse(node.expression, path, state);
15169
  path.shift();
15170
15171
  utils.catchup(node.typeAnnotation.range[0], state);
15172
  utils.catchupWhiteOut(node.typeAnnotation.range[1], state);
15173
  return false;
15174
}
15175
visitTypeCast.test = function(node, path, state) {
0 ignored issues
show
Unused Code introduced by
The parameter state is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
Unused Code introduced by
The parameter path is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
15176
  return node.type === Syntax.TypeCastExpression;
15177
};
15178
15179
function visitInterfaceDeclaration(traverse, node, path, state) {
15180
  utils.catchupWhiteOut(node.range[1], state);
15181
  return false;
15182
}
15183
visitInterfaceDeclaration.test = function(node, path, state) {
0 ignored issues
show
Unused Code introduced by
The parameter state is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
Unused Code introduced by
The parameter path is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
15184
  return node.type === Syntax.InterfaceDeclaration;
15185
};
15186
15187
function visitDeclare(traverse, node, path, state) {
15188
  utils.catchupWhiteOut(node.range[1], state);
15189
  return false;
15190
}
15191
visitDeclare.test = function(node, path, state) {
0 ignored issues
show
Unused Code introduced by
The parameter state is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
Unused Code introduced by
The parameter path is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
15192
  switch (node.type) {
0 ignored issues
show
Coding Style introduced by
As per coding-style, switch statements should have a default case.
Loading history...
15193
    case Syntax.DeclareVariable:
0 ignored issues
show
Bug introduced by
The variable Syntax seems to be never declared. If this is a global, consider adding a /** global: Syntax */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
15194
    case Syntax.DeclareFunction:
15195
    case Syntax.DeclareClass:
15196
    case Syntax.DeclareModule:
15197
      return true;
15198
  }
15199
  return false;
15200
};
15201
15202
function visitFunctionParametricAnnotation(traverse, node, path, state) {
15203
  utils.catchup(node.range[0], state);
15204
  utils.catchupWhiteOut(node.range[1], state);
15205
  return false;
15206
}
15207
visitFunctionParametricAnnotation.test = function(node, path, state) {
0 ignored issues
show
Unused Code introduced by
The parameter state is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
15208
  return node.type === Syntax.TypeParameterDeclaration
15209
         && path[0]
15210
         && _isFunctionNode(path[0])
15211
         && node === path[0].typeParameters;
15212
};
15213
15214
function visitFunctionReturnAnnotation(traverse, node, path, state) {
15215
  utils.catchup(node.range[0], state);
15216
  utils.catchupWhiteOut(node.range[1], state);
15217
  return false;
15218
}
15219
visitFunctionReturnAnnotation.test = function(node, path, state) {
0 ignored issues
show
Unused Code introduced by
The parameter state is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
15220
  return path[0] && _isFunctionNode(path[0]) && node === path[0].returnType;
15221
};
15222
15223
function visitOptionalFunctionParameterAnnotation(traverse, node, path, state) {
15224
  utils.catchup(node.range[0] + node.name.length, state);
15225
  utils.catchupWhiteOut(node.range[1], state);
15226
  return false;
15227
}
15228
visitOptionalFunctionParameterAnnotation.test = function(node, path, state) {
0 ignored issues
show
Unused Code introduced by
The parameter state is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
15229
  return node.type === Syntax.Identifier
15230
         && node.optional
15231
         && path[0]
15232
         && _isFunctionNode(path[0]);
15233
};
15234
15235
function visitTypeAnnotatedIdentifier(traverse, node, path, state) {
15236
  utils.catchup(node.typeAnnotation.range[0], state);
15237
  utils.catchupWhiteOut(node.typeAnnotation.range[1], state);
15238
  return false;
15239
}
15240
visitTypeAnnotatedIdentifier.test = function(node, path, state) {
0 ignored issues
show
Unused Code introduced by
The parameter state is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
Unused Code introduced by
The parameter path is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
15241
  return node.type === Syntax.Identifier && node.typeAnnotation;
15242
};
15243
15244
function visitTypeAnnotatedObjectOrArrayPattern(traverse, node, path, state) {
15245
  utils.catchup(node.typeAnnotation.range[0], state);
15246
  utils.catchupWhiteOut(node.typeAnnotation.range[1], state);
15247
  return false;
15248
}
15249
visitTypeAnnotatedObjectOrArrayPattern.test = function(node, path, state) {
0 ignored issues
show
Unused Code introduced by
The parameter path is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
Unused Code introduced by
The parameter state is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
15250
  var rightType = node.type === Syntax.ObjectPattern
15251
                || node.type === Syntax.ArrayPattern;
15252
  return rightType && node.typeAnnotation;
15253
};
15254
15255
/**
15256
 * Methods cause trouble, since esprima parses them as a key/value pair, where
15257
 * the location of the value starts at the method body. For example
15258
 * { bar(x:number,...y:Array<number>):number {} }
15259
 * is parsed as
15260
 * { bar: function(x: number, ...y:Array<number>): number {} }
15261
 * except that the location of the FunctionExpression value is 40-something,
15262
 * which is the location of the function body. This means that by the time we
15263
 * visit the params, rest param, and return type organically, we've already
15264
 * catchup()'d passed them.
15265
 */
15266
function visitMethod(traverse, node, path, state) {
15267
  path.unshift(node);
15268
  traverse(node.key, path, state);
15269
15270
  path.unshift(node.value);
15271
  traverse(node.value.params, path, state);
15272
  node.value.rest && traverse(node.value.rest, path, state);
15273
  node.value.returnType && traverse(node.value.returnType, path, state);
15274
  traverse(node.value.body, path, state);
15275
15276
  path.shift();
15277
15278
  path.shift();
15279
  return false;
15280
}
15281
15282
visitMethod.test = function(node, path, state) {
0 ignored issues
show
Unused Code introduced by
The parameter path is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
Unused Code introduced by
The parameter state is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
15283
  return (node.type === "Property" && (node.method || node.kind === "set" || node.kind === "get"))
15284
      || (node.type === "MethodDefinition");
15285
};
15286
15287
function visitImportType(traverse, node, path, state) {
15288
  utils.catchupWhiteOut(node.range[1], state);
15289
  return false;
15290
}
15291
visitImportType.test = function(node, path, state) {
0 ignored issues
show
Unused Code introduced by
The parameter state is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
Unused Code introduced by
The parameter path is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
15292
  return node.type === 'ImportDeclaration'
15293
         && node.isType;
15294
};
15295
15296
exports.visitorList = [
15297
  visitClassProperty,
15298
  visitDeclare,
15299
  visitImportType,
15300
  visitInterfaceDeclaration,
15301
  visitFunctionParametricAnnotation,
15302
  visitFunctionReturnAnnotation,
15303
  visitMethod,
15304
  visitOptionalFunctionParameterAnnotation,
15305
  visitTypeAlias,
15306
  visitTypeCast,
15307
  visitTypeAnnotatedIdentifier,
15308
  visitTypeAnnotatedObjectOrArrayPattern
15309
];
15310
15311
},{"../src/utils":23,"esprima-fb":9}],37:[function(_dereq_,module,exports){
15312
/**
15313
 * Copyright 2013-2015, Facebook, Inc.
15314
 * All rights reserved.
15315
 *
15316
 * This source code is licensed under the BSD-style license found in the
15317
 * LICENSE file in the root directory of this source tree. An additional grant
15318
 * of patent rights can be found in the PATENTS file in the same directory.
15319
 */
15320
/*global exports:true*/
15321
'use strict';
15322
var Syntax = _dereq_('jstransform').Syntax;
15323
var utils = _dereq_('jstransform/src/utils');
15324
15325
function renderJSXLiteral(object, isLast, state, start, end) {
15326
  var lines = object.value.split(/\r\n|\n|\r/);
15327
15328
  if (start) {
15329
    utils.append(start, state);
15330
  }
15331
15332
  var lastNonEmptyLine = 0;
15333
15334
  lines.forEach(function(line, index) {
15335
    if (line.match(/[^ \t]/)) {
15336
      lastNonEmptyLine = index;
15337
    }
15338
  });
15339
15340
  lines.forEach(function(line, index) {
15341
    var isFirstLine = index === 0;
15342
    var isLastLine = index === lines.length - 1;
15343
    var isLastNonEmptyLine = index === lastNonEmptyLine;
15344
15345
    // replace rendered whitespace tabs with spaces
15346
    var trimmedLine = line.replace(/\t/g, ' ');
15347
15348
    // trim whitespace touching a newline
15349
    if (!isFirstLine) {
15350
      trimmedLine = trimmedLine.replace(/^[ ]+/, '');
15351
    }
15352
    if (!isLastLine) {
15353
      trimmedLine = trimmedLine.replace(/[ ]+$/, '');
15354
    }
15355
15356
    if (!isFirstLine) {
15357
      utils.append(line.match(/^[ \t]*/)[0], state);
15358
    }
15359
15360
    if (trimmedLine || isLastNonEmptyLine) {
15361
      utils.append(
15362
        JSON.stringify(trimmedLine) +
15363
        (!isLastNonEmptyLine ? ' + \' \' +' : ''),
15364
        state);
15365
15366
      if (isLastNonEmptyLine) {
15367
        if (end) {
15368
          utils.append(end, state);
15369
        }
15370
        if (!isLast) {
15371
          utils.append(', ', state);
15372
        }
15373
      }
15374
15375
      // only restore tail whitespace if line had literals
15376
      if (trimmedLine && !isLastLine) {
15377
        utils.append(line.match(/[ \t]*$/)[0], state);
15378
      }
15379
    }
15380
15381
    if (!isLastLine) {
15382
      utils.append('\n', state);
15383
    }
15384
  });
15385
15386
  utils.move(object.range[1], state);
15387
}
15388
15389
function renderJSXExpressionContainer(traverse, object, isLast, path, state) {
15390
  // Plus 1 to skip `{`.
15391
  utils.move(object.range[0] + 1, state);
15392
  utils.catchup(object.expression.range[0], state);
15393
  traverse(object.expression, path, state);
15394
15395
  if (!isLast && object.expression.type !== Syntax.JSXEmptyExpression) {
15396
    // If we need to append a comma, make sure to do so after the expression.
15397
    utils.catchup(object.expression.range[1], state, trimLeft);
15398
    utils.append(', ', state);
15399
  }
15400
15401
  // Minus 1 to skip `}`.
15402
  utils.catchup(object.range[1] - 1, state, trimLeft);
15403
  utils.move(object.range[1], state);
15404
  return false;
15405
}
15406
15407
function quoteAttrName(attr) {
15408
  // Quote invalid JS identifiers.
15409
  if (!/^[a-z_$][a-z\d_$]*$/i.test(attr)) {
15410
    return '"' + attr + '"';
15411
  }
15412
  return attr;
15413
}
15414
15415
function trimLeft(value) {
15416
  return value.replace(/^[ ]+/, '');
15417
}
15418
15419
exports.renderJSXExpressionContainer = renderJSXExpressionContainer;
15420
exports.renderJSXLiteral = renderJSXLiteral;
15421
exports.quoteAttrName = quoteAttrName;
15422
exports.trimLeft = trimLeft;
15423
15424
},{"jstransform":22,"jstransform/src/utils":23}],38:[function(_dereq_,module,exports){
15425
/**
15426
 * Copyright 2013-2015, Facebook, Inc.
15427
 * All rights reserved.
15428
 *
15429
 * This source code is licensed under the BSD-style license found in the
15430
 * LICENSE file in the root directory of this source tree. An additional grant
15431
 * of patent rights can be found in the PATENTS file in the same directory.
15432
 */
15433
/*global exports:true*/
15434
'use strict';
15435
15436
var Syntax = _dereq_('jstransform').Syntax;
15437
var utils = _dereq_('jstransform/src/utils');
15438
15439
var renderJSXExpressionContainer =
15440
  _dereq_('./jsx').renderJSXExpressionContainer;
15441
var renderJSXLiteral = _dereq_('./jsx').renderJSXLiteral;
15442
var quoteAttrName = _dereq_('./jsx').quoteAttrName;
15443
15444
var trimLeft = _dereq_('./jsx').trimLeft;
15445
15446
/**
15447
 * Customized desugar processor for React JSX. Currently:
15448
 *
15449
 * <X> </X> => React.createElement(X, null)
15450
 * <X prop="1" /> => React.createElement(X, {prop: '1'}, null)
15451
 * <X prop="2"><Y /></X> => React.createElement(X, {prop:'2'},
15452
 *   React.createElement(Y, null)
15453
 * )
15454
 * <div /> => React.createElement("div", null)
15455
 */
15456
15457
/**
15458
 * Removes all non-whitespace/parenthesis characters
15459
 */
15460
var reNonWhiteParen = /([^\s\(\)])/g;
15461
function stripNonWhiteParen(value) {
15462
  return value.replace(reNonWhiteParen, '');
15463
}
15464
15465
var tagConvention = /^[a-z]|\-/;
15466
function isTagName(name) {
15467
  return tagConvention.test(name);
15468
}
15469
15470
function visitReactTag(traverse, object, path, state) {
15471
  var openingElement = object.openingElement;
15472
  var nameObject = openingElement.name;
15473
  var attributesObject = openingElement.attributes;
15474
15475
  utils.catchup(openingElement.range[0], state, trimLeft);
15476
15477
  if (nameObject.type === Syntax.JSXNamespacedName && nameObject.namespace) {
15478
    throw new Error('Namespace tags are not supported. ReactJSX is not XML.');
15479
  }
15480
15481
  // We assume that the React runtime is already in scope
15482
  utils.append('React.createElement(', state);
15483
15484
  if (nameObject.type === Syntax.JSXIdentifier && isTagName(nameObject.name)) {
15485
    utils.append('"' + nameObject.name + '"', state);
15486
    utils.move(nameObject.range[1], state);
15487
  } else {
15488
    // Use utils.catchup in this case so we can easily handle
15489
    // JSXMemberExpressions which look like Foo.Bar.Baz. This also handles
15490
    // JSXIdentifiers that aren't fallback tags.
15491
    utils.move(nameObject.range[0], state);
15492
    utils.catchup(nameObject.range[1], state);
15493
  }
15494
15495
  utils.append(', ', state);
15496
15497
  var hasAttributes = attributesObject.length;
15498
15499
  var hasAtLeastOneSpreadProperty = attributesObject.some(function(attr) {
15500
    return attr.type === Syntax.JSXSpreadAttribute;
15501
  });
15502
15503
  // if we don't have any attributes, pass in null
15504
  if (hasAtLeastOneSpreadProperty) {
15505
    utils.append('React.__spread({', state);
15506
  } else if (hasAttributes) {
15507
    utils.append('{', state);
15508
  } else {
15509
    utils.append('null', state);
15510
  }
15511
15512
  // keep track of if the previous attribute was a spread attribute
15513
  var previousWasSpread = false;
15514
15515
  // write attributes
15516
  attributesObject.forEach(function(attr, index) {
15517
    var isLast = index === attributesObject.length - 1;
15518
15519
    if (attr.type === Syntax.JSXSpreadAttribute) {
15520
      // Close the previous object or initial object
15521
      if (!previousWasSpread) {
15522
        utils.append('}, ', state);
15523
      }
15524
15525
      // Move to the expression start, ignoring everything except parenthesis
15526
      // and whitespace.
15527
      utils.catchup(attr.range[0], state, stripNonWhiteParen);
15528
      // Plus 1 to skip `{`.
15529
      utils.move(attr.range[0] + 1, state);
15530
      utils.catchup(attr.argument.range[0], state, stripNonWhiteParen);
15531
15532
      traverse(attr.argument, path, state);
15533
15534
      utils.catchup(attr.argument.range[1], state);
15535
15536
      // Move to the end, ignoring parenthesis and the closing `}`
15537
      utils.catchup(attr.range[1] - 1, state, stripNonWhiteParen);
15538
15539
      if (!isLast) {
15540
        utils.append(', ', state);
15541
      }
15542
15543
      utils.move(attr.range[1], state);
15544
15545
      previousWasSpread = true;
15546
15547
      return;
15548
    }
15549
15550
    // If the next attribute is a spread, we're effective last in this object
15551
    if (!isLast) {
15552
      isLast = attributesObject[index + 1].type === Syntax.JSXSpreadAttribute;
15553
    }
15554
15555
    if (attr.name.namespace) {
15556
      throw new Error(
15557
         'Namespace attributes are not supported. ReactJSX is not XML.');
15558
    }
15559
    var name = attr.name.name;
15560
15561
    utils.catchup(attr.range[0], state, trimLeft);
15562
15563
    if (previousWasSpread) {
15564
      utils.append('{', state);
15565
    }
15566
15567
    utils.append(quoteAttrName(name), state);
15568
    utils.append(': ', state);
15569
15570
    if (!attr.value) {
15571
      state.g.buffer += 'true';
15572
      state.g.position = attr.name.range[1];
15573
      if (!isLast) {
15574
        utils.append(', ', state);
15575
      }
15576
    } else {
15577
      utils.move(attr.name.range[1], state);
15578
      // Use catchupNewlines to skip over the '=' in the attribute
15579
      utils.catchupNewlines(attr.value.range[0], state);
15580
      if (attr.value.type === Syntax.Literal) {
15581
        renderJSXLiteral(attr.value, isLast, state);
15582
      } else {
15583
        renderJSXExpressionContainer(traverse, attr.value, isLast, path, state);
15584
      }
15585
    }
15586
15587
    utils.catchup(attr.range[1], state, trimLeft);
15588
15589
    previousWasSpread = false;
15590
15591
  });
15592
15593
  if (!openingElement.selfClosing) {
15594
    utils.catchup(openingElement.range[1] - 1, state, trimLeft);
15595
    utils.move(openingElement.range[1], state);
15596
  }
15597
15598
  if (hasAttributes && !previousWasSpread) {
15599
    utils.append('}', state);
15600
  }
15601
15602
  if (hasAtLeastOneSpreadProperty) {
15603
    utils.append(')', state);
15604
  }
15605
15606
  // filter out whitespace
15607
  var childrenToRender = object.children.filter(function(child) {
15608
    return !(child.type === Syntax.Literal
15609
             && typeof child.value === 'string'
15610
             && child.value.match(/^[ \t]*[\r\n][ \t\r\n]*$/));
15611
  });
15612
  if (childrenToRender.length > 0) {
15613
    var lastRenderableIndex;
15614
15615
    childrenToRender.forEach(function(child, index) {
15616
      if (child.type !== Syntax.JSXExpressionContainer ||
15617
          child.expression.type !== Syntax.JSXEmptyExpression) {
15618
        lastRenderableIndex = index;
15619
      }
15620
    });
15621
15622
    if (lastRenderableIndex !== undefined) {
15623
      utils.append(', ', state);
15624
    }
15625
15626
    childrenToRender.forEach(function(child, index) {
15627
      utils.catchup(child.range[0], state, trimLeft);
15628
15629
      var isLast = index >= lastRenderableIndex;
15630
15631
      if (child.type === Syntax.Literal) {
15632
        renderJSXLiteral(child, isLast, state);
15633
      } else if (child.type === Syntax.JSXExpressionContainer) {
15634
        renderJSXExpressionContainer(traverse, child, isLast, path, state);
15635
      } else {
15636
        traverse(child, path, state);
15637
        if (!isLast) {
15638
          utils.append(', ', state);
15639
        }
15640
      }
15641
15642
      utils.catchup(child.range[1], state, trimLeft);
15643
    });
15644
  }
15645
15646
  if (openingElement.selfClosing) {
15647
    // everything up to />
15648
    utils.catchup(openingElement.range[1] - 2, state, trimLeft);
15649
    utils.move(openingElement.range[1], state);
15650
  } else {
15651
    // everything up to </ sdflksjfd>
15652
    utils.catchup(object.closingElement.range[0], state, trimLeft);
15653
    utils.move(object.closingElement.range[1], state);
15654
  }
15655
15656
  utils.append(')', state);
15657
  return false;
15658
}
15659
15660
visitReactTag.test = function(object, path, state) {
0 ignored issues
show
Unused Code introduced by
The parameter path is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
Unused Code introduced by
The parameter state is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
15661
  return object.type === Syntax.JSXElement;
15662
};
15663
15664
exports.visitorList = [
15665
  visitReactTag
15666
];
15667
15668
},{"./jsx":37,"jstransform":22,"jstransform/src/utils":23}],39:[function(_dereq_,module,exports){
15669
/**
15670
 * Copyright 2013-2015, Facebook, Inc.
15671
 * All rights reserved.
15672
 *
15673
 * This source code is licensed under the BSD-style license found in the
15674
 * LICENSE file in the root directory of this source tree. An additional grant
15675
 * of patent rights can be found in the PATENTS file in the same directory.
15676
 */
15677
/*global exports:true*/
15678
'use strict';
15679
15680
var Syntax = _dereq_('jstransform').Syntax;
15681
var utils = _dereq_('jstransform/src/utils');
15682
15683
function addDisplayName(displayName, object, state) {
15684
  if (object &&
15685
      object.type === Syntax.CallExpression &&
15686
      object.callee.type === Syntax.MemberExpression &&
15687
      object.callee.object.type === Syntax.Identifier &&
15688
      object.callee.object.name === 'React' &&
15689
      object.callee.property.type === Syntax.Identifier &&
15690
      object.callee.property.name === 'createClass' &&
15691
      object.arguments.length === 1 &&
15692
      object.arguments[0].type === Syntax.ObjectExpression) {
15693
    // Verify that the displayName property isn't already set
15694
    var properties = object.arguments[0].properties;
15695
    var safe = properties.every(function(property) {
15696
      var value = property.key.type === Syntax.Identifier ?
15697
        property.key.name :
15698
        property.key.value;
15699
      return value !== 'displayName';
15700
    });
15701
15702
    if (safe) {
15703
      utils.catchup(object.arguments[0].range[0] + 1, state);
15704
      utils.append('displayName: "' + displayName + '",', state);
15705
    }
15706
  }
15707
}
15708
15709
/**
15710
 * Transforms the following:
15711
 *
15712
 * var MyComponent = React.createClass({
15713
 *    render: ...
15714
 * });
15715
 *
15716
 * into:
15717
 *
15718
 * var MyComponent = React.createClass({
15719
 *    displayName: 'MyComponent',
15720
 *    render: ...
15721
 * });
15722
 *
15723
 * Also catches:
15724
 *
15725
 * MyComponent = React.createClass(...);
15726
 * exports.MyComponent = React.createClass(...);
15727
 * module.exports = {MyComponent: React.createClass(...)};
15728
 */
15729
function visitReactDisplayName(traverse, object, path, state) {
15730
  var left, right;
15731
15732
  if (object.type === Syntax.AssignmentExpression) {
15733
    left = object.left;
15734
    right = object.right;
15735
  } else if (object.type === Syntax.Property) {
15736
    left = object.key;
15737
    right = object.value;
15738
  } else if (object.type === Syntax.VariableDeclarator) {
15739
    left = object.id;
15740
    right = object.init;
15741
  }
15742
15743
  if (left && left.type === Syntax.MemberExpression) {
15744
    left = left.property;
15745
  }
15746
  if (left && left.type === Syntax.Identifier) {
15747
    addDisplayName(left.name, right, state);
0 ignored issues
show
Bug introduced by
The variable right does not seem to be initialized in case object.type === Syntax.VariableDeclarator on line 15738 is false. Are you sure the function addDisplayName handles undefined variables?
Loading history...
15748
  }
15749
}
15750
15751
visitReactDisplayName.test = function(object, path, state) {
0 ignored issues
show
Unused Code introduced by
The parameter path is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
Unused Code introduced by
The parameter state is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
15752
  return (
15753
    object.type === Syntax.AssignmentExpression ||
15754
    object.type === Syntax.Property ||
15755
    object.type === Syntax.VariableDeclarator
15756
  );
15757
};
15758
15759
exports.visitorList = [
15760
  visitReactDisplayName
15761
];
15762
15763
},{"jstransform":22,"jstransform/src/utils":23}],40:[function(_dereq_,module,exports){
15764
/*global exports:true*/
15765
15766
'use strict';
15767
15768
var es6ArrowFunctions =
15769
  _dereq_('jstransform/visitors/es6-arrow-function-visitors');
15770
var es6Classes = _dereq_('jstransform/visitors/es6-class-visitors');
15771
var es6Destructuring =
15772
  _dereq_('jstransform/visitors/es6-destructuring-visitors');
15773
var es6ObjectConciseMethod =
15774
  _dereq_('jstransform/visitors/es6-object-concise-method-visitors');
15775
var es6ObjectShortNotation =
15776
  _dereq_('jstransform/visitors/es6-object-short-notation-visitors');
15777
var es6RestParameters = _dereq_('jstransform/visitors/es6-rest-param-visitors');
15778
var es6Templates = _dereq_('jstransform/visitors/es6-template-visitors');
15779
var es6CallSpread =
15780
  _dereq_('jstransform/visitors/es6-call-spread-visitors');
15781
var es7SpreadProperty =
15782
  _dereq_('jstransform/visitors/es7-spread-property-visitors');
15783
var react = _dereq_('./transforms/react');
15784
var reactDisplayName = _dereq_('./transforms/reactDisplayName');
15785
var reservedWords = _dereq_('jstransform/visitors/reserved-words-visitors');
15786
15787
/**
15788
 * Map from transformName => orderedListOfVisitors.
15789
 */
15790
var transformVisitors = {
15791
  'es6-arrow-functions': es6ArrowFunctions.visitorList,
15792
  'es6-classes': es6Classes.visitorList,
15793
  'es6-destructuring': es6Destructuring.visitorList,
15794
  'es6-object-concise-method': es6ObjectConciseMethod.visitorList,
15795
  'es6-object-short-notation': es6ObjectShortNotation.visitorList,
15796
  'es6-rest-params': es6RestParameters.visitorList,
15797
  'es6-templates': es6Templates.visitorList,
15798
  'es6-call-spread': es6CallSpread.visitorList,
15799
  'es7-spread-property': es7SpreadProperty.visitorList,
15800
  'react': react.visitorList.concat(reactDisplayName.visitorList),
15801
  'reserved-words': reservedWords.visitorList
15802
};
15803
15804
var transformSets = {
15805
  'harmony': [
15806
    'es6-arrow-functions',
15807
    'es6-object-concise-method',
15808
    'es6-object-short-notation',
15809
    'es6-classes',
15810
    'es6-rest-params',
15811
    'es6-templates',
15812
    'es6-destructuring',
15813
    'es6-call-spread',
15814
    'es7-spread-property'
15815
  ],
15816
  'es3': [
15817
    'reserved-words'
15818
  ],
15819
  'react': [
15820
    'react'
15821
  ]
15822
};
15823
15824
/**
15825
 * Specifies the order in which each transform should run.
15826
 */
15827
var transformRunOrder = [
15828
  'reserved-words',
15829
  'es6-arrow-functions',
15830
  'es6-object-concise-method',
15831
  'es6-object-short-notation',
15832
  'es6-classes',
15833
  'es6-rest-params',
15834
  'es6-templates',
15835
  'es6-destructuring',
15836
  'es6-call-spread',
15837
  'es7-spread-property',
15838
  'react'
15839
];
15840
15841
/**
15842
 * Given a list of transform names, return the ordered list of visitors to be
15843
 * passed to the transform() function.
15844
 *
15845
 * @param {array?} excludes
15846
 * @return {array}
15847
 */
15848
function getAllVisitors(excludes) {
15849
  var ret = [];
15850
  for (var i = 0, il = transformRunOrder.length; i < il; i++) {
15851
    if (!excludes || excludes.indexOf(transformRunOrder[i]) === -1) {
15852
      ret = ret.concat(transformVisitors[transformRunOrder[i]]);
15853
    }
15854
  }
15855
  return ret;
15856
}
15857
15858
/**
15859
 * Given a list of visitor set names, return the ordered list of visitors to be
15860
 * passed to jstransform.
15861
 *
15862
 * @param {array}
0 ignored issues
show
Documentation introduced by
The parameter * does not exist. Did you maybe forget to remove this comment?
Loading history...
15863
 * @return {array}
15864
 */
15865
function getVisitorsBySet(sets) {
15866
  var visitorsToInclude = sets.reduce(function(visitors, set) {
15867
    if (!transformSets.hasOwnProperty(set)) {
15868
      throw new Error('Unknown visitor set: ' + set);
15869
    }
15870
    transformSets[set].forEach(function(visitor) {
15871
      visitors[visitor] = true;
15872
    });
15873
    return visitors;
15874
  }, {});
15875
15876
  var visitorList = [];
15877
  for (var i = 0; i < transformRunOrder.length; i++) {
15878
    if (visitorsToInclude.hasOwnProperty(transformRunOrder[i])) {
15879
      visitorList = visitorList.concat(transformVisitors[transformRunOrder[i]]);
15880
    }
15881
  }
15882
15883
  return visitorList;
15884
}
15885
15886
exports.getVisitorsBySet = getVisitorsBySet;
15887
exports.getAllVisitors = getAllVisitors;
15888
exports.transformVisitors = transformVisitors;
15889
15890
},{"./transforms/react":38,"./transforms/reactDisplayName":39,"jstransform/visitors/es6-arrow-function-visitors":24,"jstransform/visitors/es6-call-spread-visitors":25,"jstransform/visitors/es6-class-visitors":26,"jstransform/visitors/es6-destructuring-visitors":27,"jstransform/visitors/es6-object-concise-method-visitors":28,"jstransform/visitors/es6-object-short-notation-visitors":29,"jstransform/visitors/es6-rest-param-visitors":30,"jstransform/visitors/es6-template-visitors":31,"jstransform/visitors/es7-spread-property-visitors":33,"jstransform/visitors/reserved-words-visitors":35}],41:[function(_dereq_,module,exports){
15891
/**
15892
 * Copyright 2013-2015, Facebook, Inc.
15893
 * All rights reserved.
15894
 *
15895
 * This source code is licensed under the BSD-style license found in the
15896
 * LICENSE file in the root directory of this source tree. An additional grant
15897
 * of patent rights can be found in the PATENTS file in the same directory.
15898
 */
15899
15900
'use strict';
15901
/*eslint-disable no-undef*/
15902
var Buffer = _dereq_('buffer').Buffer;
15903
15904
function inlineSourceMap(sourceMap, sourceCode, sourceFilename) {
15905
  // This can be used with a sourcemap that has already has toJSON called on it.
15906
  // Check first.
15907
  var json = sourceMap;
15908
  if (typeof sourceMap.toJSON === 'function') {
15909
    json = sourceMap.toJSON();
15910
  }
15911
  json.sources = [sourceFilename];
15912
  json.sourcesContent = [sourceCode];
15913
  var base64 = Buffer(JSON.stringify(json)).toString('base64');
15914
  return '//# sourceMappingURL=data:application/json;base64,' + base64;
15915
}
15916
15917
module.exports = inlineSourceMap;
15918
15919
},{"buffer":3}]},{},[1])(1)
15920
});