build/JSXTransformer.js in react-source-0.12.2 vs build/JSXTransformer.js in react-source-0.13.0
- old
+ new
@@ -1,26 +1,26 @@
/**
- * JSXTransformer v0.12.2
+ * JSXTransformer v0.13.0
*/
-!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.JSXTransformer=e()}}(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){
+(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){
/**
- * Copyright 2013-2014, Facebook, Inc.
+ * Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
/* jshint browser: true */
/* jslint evil: true */
+/*eslint-disable no-eval */
+/*eslint-disable block-scoped-var */
'use strict';
-var buffer = _dereq_('buffer');
-var transform = _dereq_('jstransform').transform;
-var typesSyntax = _dereq_('jstransform/visitors/type-syntax');
-var visitors = _dereq_('./fbtransform/visitors');
+var ReactTools = _dereq_('../main');
+var inlineSourceMap = _dereq_('./inline-source-map');
var headEl;
var dummyAnchor;
var inlineScriptCount = 0;
@@ -36,30 +36,22 @@
* @param {string} source Original source code
* @param {object?} options Options to pass to jstransform
* @return {object} object as returned from jstransform
*/
function transformReact(source, options) {
- // TODO: just use react-tools
options = options || {};
- var visitorList;
- if (options.harmony) {
- visitorList = visitors.getAllVisitors();
- } else {
- visitorList = visitors.transformVisitors.react;
- }
- if (options.stripTypes) {
- // Stripping types needs to happen before the other transforms
- // unfortunately, due to bad interactions. For example,
- // es6-rest-param-visitors conflict with stripping rest param type
- // annotation
- source = transform(typesSyntax.visitorList, source, options).code;
+ // Force the sourcemaps option manually. We don't want to use it if it will
+ // break (see above note about supportsAccessors). We'll only override the
+ // value here if sourceMap was specified and is truthy. This guarantees that
+ // we won't override any user intent (since this method is exposed publicly).
+ if (options.sourceMap) {
+ options.sourceMap = supportsAccessors;
}
- return transform(visitorList, source, {
- sourceMap: supportsAccessors && options.sourceMap
- });
+ // Otherwise just pass all options straight through to react-tools.
+ return ReactTools.transformWithDetails(source, options);
}
/**
* Eval provided source after transforming it.
*
@@ -84,10 +76,17 @@
* @return {string} formatted message
* @internal
*/
function createSourceCodeErrorMessage(code, e) {
var sourceLines = code.split('\n');
+ // e.lineNumber is non-standard so we can't depend on its availability. If
+ // we're in a browser where it isn't supported, don't even bother trying to
+ // format anything. We may also hit a case where the line number is reported
+ // incorrectly and is outside the bounds of the actual code. Handle that too.
+ if (!e.lineNumber || e.lineNumber > sourceLines.length) {
+ return '';
+ }
var erroneousLine = sourceLines[e.lineNumber - 1];
// Removes any leading indenting spaces and gets the number of
// chars indenting the `erroneousLine`
var indentation = 0;
@@ -132,11 +131,11 @@
// We set `fileName` if it's supported by this error object and
// a `url` was provided.
// The error will correctly point to `url` in Firefox.
e.fileName = url;
}
- e.message += url + ':' + e.lineNumber + ':' + e.column;
+ e.message += url + ':' + e.lineNumber + ':' + e.columnNumber;
} else {
e.message += location.href;
}
e.message += createSourceCodeErrorMessage(code, e);
throw e;
@@ -144,14 +143,13 @@
if (!transformed.sourceMap) {
return transformed.code;
}
- var map = transformed.sourceMap.toJSON();
var source;
if (url == null) {
- source = "Inline JSX script";
+ source = 'Inline JSX script';
inlineScriptCount++;
if (inlineScriptCount > 1) {
source += ' (' + inlineScriptCount + ')';
}
} else if (dummyAnchor) {
@@ -160,17 +158,15 @@
// filename, but hopefully using the full path will prevent potential
// issues where the same filename exists in multiple directories.
dummyAnchor.href = url;
source = dummyAnchor.pathname.substr(1);
}
- map.sources = [source];
- map.sourcesContent = [code];
return (
transformed.code +
- '\n//# sourceMappingURL=data:application/json;base64,' +
- buffer.Buffer(JSON.stringify(map)).toString('base64')
+ '\n' +
+ inlineSourceMap(transformed.sourceMap, code, source)
);
}
/**
@@ -210,11 +206,11 @@
if (xhr.readyState === 4) {
if (xhr.status === 0 || xhr.status === 200) {
successCallback(xhr.responseText);
} else {
errorCallback();
- throw new Error("Could not load " + url);
+ throw new Error('Could not load ' + url);
}
}
};
return xhr.send(null);
}
@@ -249,11 +245,11 @@
scripts.forEach(function(script, i) {
var options = {
sourceMap: true
};
if (/;harmony=true(;|$)/.test(script.type)) {
- options.harmony = true
+ options.harmony = true;
}
if (/;stripTypes=true(;|$)/.test(script.type)) {
options.stripTypes = true;
}
@@ -324,11 +320,11 @@
loadScripts(jsxScripts);
}
// Listen for load event if we're in a browser and then kick off finding and
// running of scripts.
-if (typeof window !== "undefined" && window !== null) {
+if (typeof window !== 'undefined' && window !== null) {
headEl = document.getElementsByTagName('head')[0];
dummyAnchor = document.createElement('a');
if (window.addEventListener) {
window.addEventListener('DOMContentLoaded', runScripts, false);
@@ -340,11 +336,108 @@
module.exports = {
transform: transformReact,
exec: exec
};
-},{"./fbtransform/visitors":37,"buffer":2,"jstransform":21,"jstransform/visitors/type-syntax":33}],2:[function(_dereq_,module,exports){
+},{"../main":2,"./inline-source-map":41}],2:[function(_dereq_,module,exports){
+/**
+ * Copyright 2013-2015, Facebook, Inc.
+ * All rights reserved.
+ *
+ * This source code is licensed under the BSD-style license found in the
+ * LICENSE file in the root directory of this source tree. An additional grant
+ * of patent rights can be found in the PATENTS file in the same directory.
+ */
+
+'use strict';
+/*eslint-disable no-undef*/
+var visitors = _dereq_('./vendor/fbtransform/visitors');
+var transform = _dereq_('jstransform').transform;
+var typesSyntax = _dereq_('jstransform/visitors/type-syntax');
+var inlineSourceMap = _dereq_('./vendor/inline-source-map');
+
+module.exports = {
+ transform: function(input, options) {
+ options = processOptions(options);
+ var output = innerTransform(input, options);
+ var result = output.code;
+ if (options.sourceMap) {
+ var map = inlineSourceMap(
+ output.sourceMap,
+ input,
+ options.filename
+ );
+ result += '\n' + map;
+ }
+ return result;
+ },
+ transformWithDetails: function(input, options) {
+ options = processOptions(options);
+ var output = innerTransform(input, options);
+ var result = {};
+ result.code = output.code;
+ if (options.sourceMap) {
+ result.sourceMap = output.sourceMap.toJSON();
+ }
+ if (options.filename) {
+ result.sourceMap.sources = [options.filename];
+ }
+ return result;
+ }
+};
+
+/**
+ * Only copy the values that we need. We'll do some preprocessing to account for
+ * converting command line flags to options that jstransform can actually use.
+ */
+function processOptions(opts) {
+ opts = opts || {};
+ var options = {};
+
+ options.harmony = opts.harmony;
+ options.stripTypes = opts.stripTypes;
+ options.sourceMap = opts.sourceMap;
+ options.filename = opts.sourceFilename;
+
+ if (opts.es6module) {
+ options.sourceType = 'module';
+ }
+ if (opts.nonStrictEs6Module) {
+ options.sourceType = 'nonStrict6Module';
+ }
+
+ // Instead of doing any fancy validation, only look for 'es3'. If we have
+ // that, then use it. Otherwise use 'es5'.
+ options.es3 = opts.target === 'es3';
+ options.es5 = !options.es3;
+
+ return options;
+}
+
+function innerTransform(input, options) {
+ var visitorSets = ['react'];
+ if (options.harmony) {
+ visitorSets.push('harmony');
+ }
+
+ if (options.es3) {
+ visitorSets.push('es3');
+ }
+
+ if (options.stripTypes) {
+ // Stripping types needs to happen before the other transforms
+ // unfortunately, due to bad interactions. For example,
+ // es6-rest-param-visitors conflict with stripping rest param type
+ // annotation
+ input = transform(typesSyntax.visitorList, input, options).code;
+ }
+
+ var visitorList = visitors.getVisitorsBySet(visitorSets);
+ return transform(visitorList, input, options);
+}
+
+},{"./vendor/fbtransform/visitors":40,"./vendor/inline-source-map":41,"jstransform":22,"jstransform/visitors/type-syntax":36}],3:[function(_dereq_,module,exports){
/*!
* The buffer module from node.js, for the browser.
*
* @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
* @license MIT
@@ -353,15 +446,16 @@
var base64 = _dereq_('base64-js')
var ieee754 = _dereq_('ieee754')
var isArray = _dereq_('is-array')
exports.Buffer = Buffer
-exports.SlowBuffer = Buffer
+exports.SlowBuffer = SlowBuffer
exports.INSPECT_MAX_BYTES = 50
Buffer.poolSize = 8192 // not used by this implementation
var kMaxLength = 0x3fffffff
+var rootParent = {}
/**
* If `Buffer.TYPED_ARRAY_SUPPORT`:
* === true Use Uint8Array implementation (fastest)
* === false Use Object implementation (most compatible, even IE6)
@@ -386,11 +480,11 @@
Buffer.TYPED_ARRAY_SUPPORT = (function () {
try {
var buf = new ArrayBuffer(0)
var arr = new Uint8Array(buf)
arr.foo = function () { return 42 }
- return 42 === arr.foo() && // typed array instances can be augmented
+ return arr.foo() === 42 && // typed array instances can be augmented
typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray`
new Uint8Array(1).subarray(1, 1).byteLength === 0 // ie10 has broken `subarray`
} catch (e) {
return false
}
@@ -407,77 +501,94 @@
*
* By augmenting the instances, we can avoid modifying the `Uint8Array`
* prototype.
*/
function Buffer (subject, encoding, noZero) {
- if (!(this instanceof Buffer))
- return new Buffer(subject, encoding, noZero)
+ if (!(this instanceof Buffer)) return new Buffer(subject, encoding, noZero)
var type = typeof subject
-
- // Find the length
var length
- if (type === 'number')
- length = subject > 0 ? subject >>> 0 : 0
- else if (type === 'string') {
- if (encoding === 'base64')
- subject = base64clean(subject)
+
+ if (type === 'number') {
+ length = +subject
+ } else if (type === 'string') {
length = Buffer.byteLength(subject, encoding)
- } else if (type === 'object' && subject !== null) { // assume object is array-like
- if (subject.type === 'Buffer' && isArray(subject.data))
- subject = subject.data
- length = +subject.length > 0 ? Math.floor(+subject.length) : 0
- } else
+ } else if (type === 'object' && subject !== null) {
+ // assume object is array-like
+ if (subject.type === 'Buffer' && isArray(subject.data)) subject = subject.data
+ length = +subject.length
+ } else {
throw new TypeError('must start with number, buffer, array or string')
+ }
- if (this.length > kMaxLength)
- throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
- 'size: 0x' + kMaxLength.toString(16) + ' bytes')
+ if (length > kMaxLength) {
+ throw new RangeError('Attempt to allocate Buffer larger than maximum size: 0x' +
+ kMaxLength.toString(16) + ' bytes')
+ }
- var buf
+ if (length < 0) length = 0
+ else length >>>= 0 // coerce to uint32
+
+ var self = this
if (Buffer.TYPED_ARRAY_SUPPORT) {
// Preferred: Return an augmented `Uint8Array` instance for best performance
- buf = Buffer._augment(new Uint8Array(length))
+ /*eslint-disable consistent-this */
+ self = Buffer._augment(new Uint8Array(length))
+ /*eslint-enable consistent-this */
} else {
// Fallback: Return THIS instance of Buffer (created by `new`)
- buf = this
- buf.length = length
- buf._isBuffer = true
+ self.length = length
+ self._isBuffer = true
}
var i
if (Buffer.TYPED_ARRAY_SUPPORT && typeof subject.byteLength === 'number') {
// Speed optimization -- use set if we're copying from a typed array
- buf._set(subject)
+ self._set(subject)
} else if (isArrayish(subject)) {
// Treat array-ish objects as a byte array
if (Buffer.isBuffer(subject)) {
- for (i = 0; i < length; i++)
- buf[i] = subject.readUInt8(i)
+ for (i = 0; i < length; i++) {
+ self[i] = subject.readUInt8(i)
+ }
} else {
- for (i = 0; i < length; i++)
- buf[i] = ((subject[i] % 256) + 256) % 256
+ for (i = 0; i < length; i++) {
+ self[i] = ((subject[i] % 256) + 256) % 256
+ }
}
} else if (type === 'string') {
- buf.write(subject, 0, encoding)
+ self.write(subject, 0, encoding)
} else if (type === 'number' && !Buffer.TYPED_ARRAY_SUPPORT && !noZero) {
for (i = 0; i < length; i++) {
- buf[i] = 0
+ self[i] = 0
}
}
+ if (length > 0 && length <= Buffer.poolSize) self.parent = rootParent
+
+ return self
+}
+
+function SlowBuffer (subject, encoding, noZero) {
+ if (!(this instanceof SlowBuffer)) return new SlowBuffer(subject, encoding, noZero)
+
+ var buf = new Buffer(subject, encoding, noZero)
+ delete buf.parent
return buf
}
-Buffer.isBuffer = function (b) {
+Buffer.isBuffer = function isBuffer (b) {
return !!(b != null && b._isBuffer)
}
-Buffer.compare = function (a, b) {
- if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b))
+Buffer.compare = function compare (a, b) {
+ if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
throw new TypeError('Arguments must be Buffers')
+ }
+ if (a === b) return 0
+
var x = a.length
var y = b.length
for (var i = 0, len = Math.min(x, y); i < len && a[i] === b[i]; i++) {}
if (i !== len) {
x = a[i]
@@ -486,11 +597,11 @@
if (x < y) return -1
if (y < x) return 1
return 0
}
-Buffer.isEncoding = function (encoding) {
+Buffer.isEncoding = function isEncoding (encoding) {
switch (String(encoding).toLowerCase()) {
case 'hex':
case 'utf8':
case 'utf-8':
case 'ascii':
@@ -505,11 +616,11 @@
default:
return false
}
}
-Buffer.concat = function (list, totalLength) {
+Buffer.concat = function concat (list, totalLength) {
if (!isArray(list)) throw new TypeError('Usage: Buffer.concat(list[, length])')
if (list.length === 0) {
return new Buffer(0)
} else if (list.length === 1) {
@@ -532,11 +643,11 @@
pos += item.length
}
return buf
}
-Buffer.byteLength = function (str, encoding) {
+Buffer.byteLength = function byteLength (str, encoding) {
var ret
str = str + ''
switch (encoding || 'utf8') {
case 'ascii':
case 'binary':
@@ -568,11 +679,11 @@
// pre-set for values that may exist in the future
Buffer.prototype.length = undefined
Buffer.prototype.parent = undefined
// toString(encoding, start=0, end=buffer.length)
-Buffer.prototype.toString = function (encoding, start, end) {
+Buffer.prototype.toString = function toString (encoding, start, end) {
var loweredCase = false
start = start >>> 0
end = end === undefined || end === Infinity ? this.length : end >>> 0
@@ -604,47 +715,88 @@
case 'utf16le':
case 'utf-16le':
return utf16leSlice(this, start, end)
default:
- if (loweredCase)
- throw new TypeError('Unknown encoding: ' + encoding)
+ if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
encoding = (encoding + '').toLowerCase()
loweredCase = true
}
}
}
-Buffer.prototype.equals = function (b) {
- if(!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
+Buffer.prototype.equals = function equals (b) {
+ if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
+ if (this === b) return true
return Buffer.compare(this, b) === 0
}
-Buffer.prototype.inspect = function () {
+Buffer.prototype.inspect = function inspect () {
var str = ''
var max = exports.INSPECT_MAX_BYTES
if (this.length > 0) {
str = this.toString('hex', 0, max).match(/.{2}/g).join(' ')
- if (this.length > max)
- str += ' ... '
+ if (this.length > max) str += ' ... '
}
return '<Buffer ' + str + '>'
}
-Buffer.prototype.compare = function (b) {
+Buffer.prototype.compare = function compare (b) {
if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
+ if (this === b) return 0
return Buffer.compare(this, b)
}
+Buffer.prototype.indexOf = function indexOf (val, byteOffset) {
+ if (byteOffset > 0x7fffffff) byteOffset = 0x7fffffff
+ else if (byteOffset < -0x80000000) byteOffset = -0x80000000
+ byteOffset >>= 0
+
+ if (this.length === 0) return -1
+ if (byteOffset >= this.length) return -1
+
+ // Negative offsets start from the end of the buffer
+ if (byteOffset < 0) byteOffset = Math.max(this.length + byteOffset, 0)
+
+ if (typeof val === 'string') {
+ if (val.length === 0) return -1 // special case: looking for empty string always fails
+ return String.prototype.indexOf.call(this, val, byteOffset)
+ }
+ if (Buffer.isBuffer(val)) {
+ return arrayIndexOf(this, val, byteOffset)
+ }
+ if (typeof val === 'number') {
+ if (Buffer.TYPED_ARRAY_SUPPORT && Uint8Array.prototype.indexOf === 'function') {
+ return Uint8Array.prototype.indexOf.call(this, val, byteOffset)
+ }
+ return arrayIndexOf(this, [ val ], byteOffset)
+ }
+
+ function arrayIndexOf (arr, val, byteOffset) {
+ var foundIndex = -1
+ for (var i = 0; byteOffset + i < arr.length; i++) {
+ if (arr[byteOffset + i] === val[foundIndex === -1 ? 0 : i - foundIndex]) {
+ if (foundIndex === -1) foundIndex = i
+ if (i - foundIndex + 1 === val.length) return byteOffset + foundIndex
+ } else {
+ foundIndex = -1
+ }
+ }
+ return -1
+ }
+
+ throw new TypeError('val must be string, number or Buffer')
+}
+
// `get` will be removed in Node 0.13+
-Buffer.prototype.get = function (offset) {
+Buffer.prototype.get = function get (offset) {
console.log('.get() is deprecated. Access using array indexes instead.')
return this.readUInt8(offset)
}
// `set` will be removed in Node 0.13+
-Buffer.prototype.set = function (v, offset) {
+Buffer.prototype.set = function set (v, offset) {
console.log('.set() is deprecated. Access using array indexes instead.')
return this.writeUInt8(v, offset)
}
function hexWrite (buf, string, offset, length) {
@@ -665,19 +817,19 @@
if (length > strLen / 2) {
length = strLen / 2
}
for (var i = 0; i < length; i++) {
- var byte = parseInt(string.substr(i * 2, 2), 16)
- if (isNaN(byte)) throw new Error('Invalid hex string')
- buf[offset + i] = byte
+ var parsed = parseInt(string.substr(i * 2, 2), 16)
+ if (isNaN(parsed)) throw new Error('Invalid hex string')
+ buf[offset + i] = parsed
}
return i
}
function utf8Write (buf, string, offset, length) {
- var charsWritten = blitBuffer(utf8ToBytes(string), buf, offset, length)
+ var charsWritten = blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
return charsWritten
}
function asciiWrite (buf, string, offset, length) {
var charsWritten = blitBuffer(asciiToBytes(string), buf, offset, length)
@@ -692,15 +844,15 @@
var charsWritten = blitBuffer(base64ToBytes(string), buf, offset, length)
return charsWritten
}
function utf16leWrite (buf, string, offset, length) {
- var charsWritten = blitBuffer(utf16leToBytes(string), buf, offset, length)
+ var charsWritten = blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
return charsWritten
}
-Buffer.prototype.write = function (string, offset, length, encoding) {
+Buffer.prototype.write = function write (string, offset, length, encoding) {
// Support both (string, offset, length, encoding)
// and the legacy (string, encoding, offset, length)
if (isFinite(offset)) {
if (!isFinite(length)) {
encoding = length
@@ -712,10 +864,15 @@
offset = length
length = swap
}
offset = Number(offset) || 0
+
+ if (length < 0 || offset < 0 || offset > this.length) {
+ throw new RangeError('attempt to write outside buffer bounds')
+ }
+
var remaining = this.length - offset
if (!length) {
length = remaining
} else {
length = Number(length)
@@ -753,11 +910,11 @@
throw new TypeError('Unknown encoding: ' + encoding)
}
return ret
}
-Buffer.prototype.toJSON = function () {
+Buffer.prototype.toJSON = function toJSON () {
return {
type: 'Buffer',
data: Array.prototype.slice.call(this._arr || this, 0)
}
}
@@ -790,17 +947,23 @@
function asciiSlice (buf, start, end) {
var ret = ''
end = Math.min(buf.length, end)
for (var i = start; i < end; i++) {
- ret += String.fromCharCode(buf[i])
+ ret += String.fromCharCode(buf[i] & 0x7F)
}
return ret
}
function binarySlice (buf, start, end) {
- return asciiSlice(buf, start, end)
+ var ret = ''
+ end = Math.min(buf.length, end)
+
+ for (var i = start; i < end; i++) {
+ ret += String.fromCharCode(buf[i])
+ }
+ return ret
}
function hexSlice (buf, start, end) {
var len = buf.length
@@ -821,171 +984,253 @@
res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256)
}
return res
}
-Buffer.prototype.slice = function (start, end) {
+Buffer.prototype.slice = function slice (start, end) {
var len = this.length
start = ~~start
end = end === undefined ? len : ~~end
if (start < 0) {
- start += len;
- if (start < 0)
- start = 0
+ start += len
+ if (start < 0) start = 0
} else if (start > len) {
start = len
}
if (end < 0) {
end += len
- if (end < 0)
- end = 0
+ if (end < 0) end = 0
} else if (end > len) {
end = len
}
- if (end < start)
- end = start
+ if (end < start) end = start
+ var newBuf
if (Buffer.TYPED_ARRAY_SUPPORT) {
- return Buffer._augment(this.subarray(start, end))
+ newBuf = Buffer._augment(this.subarray(start, end))
} else {
var sliceLen = end - start
- var newBuf = new Buffer(sliceLen, undefined, true)
+ newBuf = new Buffer(sliceLen, undefined, true)
for (var i = 0; i < sliceLen; i++) {
newBuf[i] = this[i + start]
}
- return newBuf
}
+
+ if (newBuf.length) newBuf.parent = this.parent || this
+
+ return newBuf
}
/*
* Need to make sure that buffer isn't trying to write out of bounds.
*/
function checkOffset (offset, ext, length) {
- if ((offset % 1) !== 0 || offset < 0)
- throw new RangeError('offset is not uint')
- if (offset + ext > length)
- throw new RangeError('Trying to access beyond buffer length')
+ if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
+ if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
}
-Buffer.prototype.readUInt8 = function (offset, noAssert) {
- if (!noAssert)
- checkOffset(offset, 1, this.length)
+Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
+ offset = offset >>> 0
+ byteLength = byteLength >>> 0
+ if (!noAssert) checkOffset(offset, byteLength, this.length)
+
+ var val = this[offset]
+ var mul = 1
+ var i = 0
+ while (++i < byteLength && (mul *= 0x100)) {
+ val += this[offset + i] * mul
+ }
+
+ return val
+}
+
+Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
+ offset = offset >>> 0
+ byteLength = byteLength >>> 0
+ if (!noAssert) {
+ checkOffset(offset, byteLength, this.length)
+ }
+
+ var val = this[offset + --byteLength]
+ var mul = 1
+ while (byteLength > 0 && (mul *= 0x100)) {
+ val += this[offset + --byteLength] * mul
+ }
+
+ return val
+}
+
+Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
+ if (!noAssert) checkOffset(offset, 1, this.length)
return this[offset]
}
-Buffer.prototype.readUInt16LE = function (offset, noAssert) {
- if (!noAssert)
- checkOffset(offset, 2, this.length)
+Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
+ if (!noAssert) checkOffset(offset, 2, this.length)
return this[offset] | (this[offset + 1] << 8)
}
-Buffer.prototype.readUInt16BE = function (offset, noAssert) {
- if (!noAssert)
- checkOffset(offset, 2, this.length)
+Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
+ if (!noAssert) checkOffset(offset, 2, this.length)
return (this[offset] << 8) | this[offset + 1]
}
-Buffer.prototype.readUInt32LE = function (offset, noAssert) {
- if (!noAssert)
- checkOffset(offset, 4, this.length)
+Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
+ if (!noAssert) checkOffset(offset, 4, this.length)
return ((this[offset]) |
(this[offset + 1] << 8) |
(this[offset + 2] << 16)) +
(this[offset + 3] * 0x1000000)
}
-Buffer.prototype.readUInt32BE = function (offset, noAssert) {
- if (!noAssert)
- checkOffset(offset, 4, this.length)
+Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
+ if (!noAssert) checkOffset(offset, 4, this.length)
return (this[offset] * 0x1000000) +
- ((this[offset + 1] << 16) |
- (this[offset + 2] << 8) |
- this[offset + 3])
+ ((this[offset + 1] << 16) |
+ (this[offset + 2] << 8) |
+ this[offset + 3])
}
-Buffer.prototype.readInt8 = function (offset, noAssert) {
- if (!noAssert)
- checkOffset(offset, 1, this.length)
- if (!(this[offset] & 0x80))
- return (this[offset])
+Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
+ offset = offset >>> 0
+ byteLength = byteLength >>> 0
+ if (!noAssert) checkOffset(offset, byteLength, this.length)
+
+ var val = this[offset]
+ var mul = 1
+ var i = 0
+ while (++i < byteLength && (mul *= 0x100)) {
+ val += this[offset + i] * mul
+ }
+ mul *= 0x80
+
+ if (val >= mul) val -= Math.pow(2, 8 * byteLength)
+
+ return val
+}
+
+Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
+ offset = offset >>> 0
+ byteLength = byteLength >>> 0
+ if (!noAssert) checkOffset(offset, byteLength, this.length)
+
+ var i = byteLength
+ var mul = 1
+ var val = this[offset + --i]
+ while (i > 0 && (mul *= 0x100)) {
+ val += this[offset + --i] * mul
+ }
+ mul *= 0x80
+
+ if (val >= mul) val -= Math.pow(2, 8 * byteLength)
+
+ return val
+}
+
+Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
+ if (!noAssert) checkOffset(offset, 1, this.length)
+ if (!(this[offset] & 0x80)) return (this[offset])
return ((0xff - this[offset] + 1) * -1)
}
-Buffer.prototype.readInt16LE = function (offset, noAssert) {
- if (!noAssert)
- checkOffset(offset, 2, this.length)
+Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
+ if (!noAssert) checkOffset(offset, 2, this.length)
var val = this[offset] | (this[offset + 1] << 8)
return (val & 0x8000) ? val | 0xFFFF0000 : val
}
-Buffer.prototype.readInt16BE = function (offset, noAssert) {
- if (!noAssert)
- checkOffset(offset, 2, this.length)
+Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
+ if (!noAssert) checkOffset(offset, 2, this.length)
var val = this[offset + 1] | (this[offset] << 8)
return (val & 0x8000) ? val | 0xFFFF0000 : val
}
-Buffer.prototype.readInt32LE = function (offset, noAssert) {
- if (!noAssert)
- checkOffset(offset, 4, this.length)
+Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
+ if (!noAssert) checkOffset(offset, 4, this.length)
return (this[offset]) |
- (this[offset + 1] << 8) |
- (this[offset + 2] << 16) |
- (this[offset + 3] << 24)
+ (this[offset + 1] << 8) |
+ (this[offset + 2] << 16) |
+ (this[offset + 3] << 24)
}
-Buffer.prototype.readInt32BE = function (offset, noAssert) {
- if (!noAssert)
- checkOffset(offset, 4, this.length)
+Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
+ if (!noAssert) checkOffset(offset, 4, this.length)
return (this[offset] << 24) |
- (this[offset + 1] << 16) |
- (this[offset + 2] << 8) |
- (this[offset + 3])
+ (this[offset + 1] << 16) |
+ (this[offset + 2] << 8) |
+ (this[offset + 3])
}
-Buffer.prototype.readFloatLE = function (offset, noAssert) {
- if (!noAssert)
- checkOffset(offset, 4, this.length)
+Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
+ if (!noAssert) checkOffset(offset, 4, this.length)
return ieee754.read(this, offset, true, 23, 4)
}
-Buffer.prototype.readFloatBE = function (offset, noAssert) {
- if (!noAssert)
- checkOffset(offset, 4, this.length)
+Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
+ if (!noAssert) checkOffset(offset, 4, this.length)
return ieee754.read(this, offset, false, 23, 4)
}
-Buffer.prototype.readDoubleLE = function (offset, noAssert) {
- if (!noAssert)
- checkOffset(offset, 8, this.length)
+Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
+ if (!noAssert) checkOffset(offset, 8, this.length)
return ieee754.read(this, offset, true, 52, 8)
}
-Buffer.prototype.readDoubleBE = function (offset, noAssert) {
- if (!noAssert)
- checkOffset(offset, 8, this.length)
+Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
+ if (!noAssert) checkOffset(offset, 8, this.length)
return ieee754.read(this, offset, false, 52, 8)
}
function checkInt (buf, value, offset, ext, max, min) {
if (!Buffer.isBuffer(buf)) throw new TypeError('buffer must be a Buffer instance')
- if (value > max || value < min) throw new TypeError('value is out of bounds')
- if (offset + ext > buf.length) throw new TypeError('index out of range')
+ if (value > max || value < min) throw new RangeError('value is out of bounds')
+ if (offset + ext > buf.length) throw new RangeError('index out of range')
}
-Buffer.prototype.writeUInt8 = function (value, offset, noAssert) {
+Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
value = +value
offset = offset >>> 0
- if (!noAssert)
- checkInt(this, value, offset, 1, 0xff, 0)
+ byteLength = byteLength >>> 0
+ if (!noAssert) checkInt(this, value, offset, byteLength, Math.pow(2, 8 * byteLength), 0)
+
+ var mul = 1
+ var i = 0
+ this[offset] = value & 0xFF
+ while (++i < byteLength && (mul *= 0x100)) {
+ this[offset + i] = (value / mul) >>> 0 & 0xFF
+ }
+
+ return offset + byteLength
+}
+
+Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
+ value = +value
+ offset = offset >>> 0
+ byteLength = byteLength >>> 0
+ if (!noAssert) checkInt(this, value, offset, byteLength, Math.pow(2, 8 * byteLength), 0)
+
+ var i = byteLength - 1
+ var mul = 1
+ this[offset + i] = value & 0xFF
+ while (--i >= 0 && (mul *= 0x100)) {
+ this[offset + i] = (value / mul) >>> 0 & 0xFF
+ }
+
+ return offset + byteLength
+}
+
+Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
+ value = +value
+ offset = offset >>> 0
+ if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)
if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
this[offset] = value
return offset + 1
}
@@ -995,218 +1240,276 @@
buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>>
(littleEndian ? i : 1 - i) * 8
}
}
-Buffer.prototype.writeUInt16LE = function (value, offset, noAssert) {
+Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
value = +value
offset = offset >>> 0
- if (!noAssert)
- checkInt(this, value, offset, 2, 0xffff, 0)
+ if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = value
this[offset + 1] = (value >>> 8)
- } else objectWriteUInt16(this, value, offset, true)
+ } else {
+ objectWriteUInt16(this, value, offset, true)
+ }
return offset + 2
}
-Buffer.prototype.writeUInt16BE = function (value, offset, noAssert) {
+Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
value = +value
offset = offset >>> 0
- if (!noAssert)
- checkInt(this, value, offset, 2, 0xffff, 0)
+ if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = (value >>> 8)
this[offset + 1] = value
- } else objectWriteUInt16(this, value, offset, false)
+ } else {
+ objectWriteUInt16(this, value, offset, false)
+ }
return offset + 2
}
function objectWriteUInt32 (buf, value, offset, littleEndian) {
if (value < 0) value = 0xffffffff + value + 1
for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; i++) {
buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff
}
}
-Buffer.prototype.writeUInt32LE = function (value, offset, noAssert) {
+Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
value = +value
offset = offset >>> 0
- if (!noAssert)
- checkInt(this, value, offset, 4, 0xffffffff, 0)
+ if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset + 3] = (value >>> 24)
this[offset + 2] = (value >>> 16)
this[offset + 1] = (value >>> 8)
this[offset] = value
- } else objectWriteUInt32(this, value, offset, true)
+ } else {
+ objectWriteUInt32(this, value, offset, true)
+ }
return offset + 4
}
-Buffer.prototype.writeUInt32BE = function (value, offset, noAssert) {
+Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
value = +value
offset = offset >>> 0
- if (!noAssert)
- checkInt(this, value, offset, 4, 0xffffffff, 0)
+ if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = (value >>> 24)
this[offset + 1] = (value >>> 16)
this[offset + 2] = (value >>> 8)
this[offset + 3] = value
- } else objectWriteUInt32(this, value, offset, false)
+ } else {
+ objectWriteUInt32(this, value, offset, false)
+ }
return offset + 4
}
-Buffer.prototype.writeInt8 = function (value, offset, noAssert) {
+Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
value = +value
offset = offset >>> 0
- if (!noAssert)
- checkInt(this, value, offset, 1, 0x7f, -0x80)
+ if (!noAssert) {
+ checkInt(
+ this, value, offset, byteLength,
+ Math.pow(2, 8 * byteLength - 1) - 1,
+ -Math.pow(2, 8 * byteLength - 1)
+ )
+ }
+
+ var i = 0
+ var mul = 1
+ var sub = value < 0 ? 1 : 0
+ this[offset] = value & 0xFF
+ while (++i < byteLength && (mul *= 0x100)) {
+ this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
+ }
+
+ return offset + byteLength
+}
+
+Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
+ value = +value
+ offset = offset >>> 0
+ if (!noAssert) {
+ checkInt(
+ this, value, offset, byteLength,
+ Math.pow(2, 8 * byteLength - 1) - 1,
+ -Math.pow(2, 8 * byteLength - 1)
+ )
+ }
+
+ var i = byteLength - 1
+ var mul = 1
+ var sub = value < 0 ? 1 : 0
+ this[offset + i] = value & 0xFF
+ while (--i >= 0 && (mul *= 0x100)) {
+ this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
+ }
+
+ return offset + byteLength
+}
+
+Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
+ value = +value
+ offset = offset >>> 0
+ if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)
if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
if (value < 0) value = 0xff + value + 1
this[offset] = value
return offset + 1
}
-Buffer.prototype.writeInt16LE = function (value, offset, noAssert) {
+Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
value = +value
offset = offset >>> 0
- if (!noAssert)
- checkInt(this, value, offset, 2, 0x7fff, -0x8000)
+ if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = value
this[offset + 1] = (value >>> 8)
- } else objectWriteUInt16(this, value, offset, true)
+ } else {
+ objectWriteUInt16(this, value, offset, true)
+ }
return offset + 2
}
-Buffer.prototype.writeInt16BE = function (value, offset, noAssert) {
+Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
value = +value
offset = offset >>> 0
- if (!noAssert)
- checkInt(this, value, offset, 2, 0x7fff, -0x8000)
+ if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = (value >>> 8)
this[offset + 1] = value
- } else objectWriteUInt16(this, value, offset, false)
+ } else {
+ objectWriteUInt16(this, value, offset, false)
+ }
return offset + 2
}
-Buffer.prototype.writeInt32LE = function (value, offset, noAssert) {
+Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
value = +value
offset = offset >>> 0
- if (!noAssert)
- checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
+ if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = value
this[offset + 1] = (value >>> 8)
this[offset + 2] = (value >>> 16)
this[offset + 3] = (value >>> 24)
- } else objectWriteUInt32(this, value, offset, true)
+ } else {
+ objectWriteUInt32(this, value, offset, true)
+ }
return offset + 4
}
-Buffer.prototype.writeInt32BE = function (value, offset, noAssert) {
+Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
value = +value
offset = offset >>> 0
- if (!noAssert)
- checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
+ if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
if (value < 0) value = 0xffffffff + value + 1
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = (value >>> 24)
this[offset + 1] = (value >>> 16)
this[offset + 2] = (value >>> 8)
this[offset + 3] = value
- } else objectWriteUInt32(this, value, offset, false)
+ } else {
+ objectWriteUInt32(this, value, offset, false)
+ }
return offset + 4
}
function checkIEEE754 (buf, value, offset, ext, max, min) {
- if (value > max || value < min) throw new TypeError('value is out of bounds')
- if (offset + ext > buf.length) throw new TypeError('index out of range')
+ if (value > max || value < min) throw new RangeError('value is out of bounds')
+ if (offset + ext > buf.length) throw new RangeError('index out of range')
+ if (offset < 0) throw new RangeError('index out of range')
}
function writeFloat (buf, value, offset, littleEndian, noAssert) {
- if (!noAssert)
+ if (!noAssert) {
checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
+ }
ieee754.write(buf, value, offset, littleEndian, 23, 4)
return offset + 4
}
-Buffer.prototype.writeFloatLE = function (value, offset, noAssert) {
+Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
return writeFloat(this, value, offset, true, noAssert)
}
-Buffer.prototype.writeFloatBE = function (value, offset, noAssert) {
+Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
return writeFloat(this, value, offset, false, noAssert)
}
function writeDouble (buf, value, offset, littleEndian, noAssert) {
- if (!noAssert)
+ if (!noAssert) {
checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)
+ }
ieee754.write(buf, value, offset, littleEndian, 52, 8)
return offset + 8
}
-Buffer.prototype.writeDoubleLE = function (value, offset, noAssert) {
+Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
return writeDouble(this, value, offset, true, noAssert)
}
-Buffer.prototype.writeDoubleBE = function (value, offset, noAssert) {
+Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
return writeDouble(this, value, offset, false, noAssert)
}
// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
-Buffer.prototype.copy = function (target, target_start, start, end) {
- var source = this
+Buffer.prototype.copy = function copy (target, target_start, start, end) {
+ var self = this // source
if (!start) start = 0
if (!end && end !== 0) end = this.length
+ if (target_start >= target.length) target_start = target.length
if (!target_start) target_start = 0
+ if (end > 0 && end < start) end = start
// Copy 0 bytes; we're done
- if (end === start) return
- if (target.length === 0 || source.length === 0) return
+ if (end === start) return 0
+ if (target.length === 0 || self.length === 0) return 0
// Fatal error conditions
- if (end < start) throw new TypeError('sourceEnd < sourceStart')
- if (target_start < 0 || target_start >= target.length)
- throw new TypeError('targetStart out of bounds')
- if (start < 0 || start >= source.length) throw new TypeError('sourceStart out of bounds')
- if (end < 0 || end > source.length) throw new TypeError('sourceEnd out of bounds')
+ if (target_start < 0) {
+ throw new RangeError('targetStart out of bounds')
+ }
+ if (start < 0 || start >= self.length) throw new RangeError('sourceStart out of bounds')
+ if (end < 0) throw new RangeError('sourceEnd out of bounds')
// Are we oob?
- if (end > this.length)
- end = this.length
- if (target.length - target_start < end - start)
+ if (end > this.length) end = this.length
+ if (target.length - target_start < end - start) {
end = target.length - target_start + start
+ }
var len = end - start
if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) {
for (var i = 0; i < len; i++) {
target[i + target_start] = this[i + start]
}
} else {
target._set(this.subarray(start, start + len), target_start)
}
+
+ return len
}
// fill(value, start=0, end=buffer.length)
-Buffer.prototype.fill = function (value, start, end) {
+Buffer.prototype.fill = function fill (value, start, end) {
if (!value) value = 0
if (!start) start = 0
if (!end) end = this.length
- if (end < start) throw new TypeError('end < start')
+ if (end < start) throw new RangeError('end < start')
// Fill 0 bytes; we're done
if (end === start) return
if (this.length === 0) return
- if (start < 0 || start >= this.length) throw new TypeError('start out of bounds')
- if (end < 0 || end > this.length) throw new TypeError('end out of bounds')
+ if (start < 0 || start >= this.length) throw new RangeError('start out of bounds')
+ if (end < 0 || end > this.length) throw new RangeError('end out of bounds')
var i
if (typeof value === 'number') {
for (i = start; i < end; i++) {
this[i] = value
@@ -1224,11 +1527,11 @@
/**
* Creates a new `ArrayBuffer` with the *copied* memory of the buffer instance.
* Added in Node 0.12. Only available in browsers that support ArrayBuffer.
*/
-Buffer.prototype.toArrayBuffer = function () {
+Buffer.prototype.toArrayBuffer = function toArrayBuffer () {
if (typeof Uint8Array !== 'undefined') {
if (Buffer.TYPED_ARRAY_SUPPORT) {
return (new Buffer(this)).buffer
} else {
var buf = new Uint8Array(this.length)
@@ -1248,11 +1551,11 @@
var BP = Buffer.prototype
/**
* Augment a Uint8Array *instance* (not the Uint8Array class!) with Buffer methods
*/
-Buffer._augment = function (arr) {
+Buffer._augment = function _augment (arr) {
arr.constructor = Buffer
arr._isBuffer = true
// save reference to original Uint8Array get/set methods before overwriting
arr._get = arr.get
@@ -1266,31 +1569,40 @@
arr.toString = BP.toString
arr.toLocaleString = BP.toString
arr.toJSON = BP.toJSON
arr.equals = BP.equals
arr.compare = BP.compare
+ arr.indexOf = BP.indexOf
arr.copy = BP.copy
arr.slice = BP.slice
+ arr.readUIntLE = BP.readUIntLE
+ arr.readUIntBE = BP.readUIntBE
arr.readUInt8 = BP.readUInt8
arr.readUInt16LE = BP.readUInt16LE
arr.readUInt16BE = BP.readUInt16BE
arr.readUInt32LE = BP.readUInt32LE
arr.readUInt32BE = BP.readUInt32BE
+ arr.readIntLE = BP.readIntLE
+ arr.readIntBE = BP.readIntBE
arr.readInt8 = BP.readInt8
arr.readInt16LE = BP.readInt16LE
arr.readInt16BE = BP.readInt16BE
arr.readInt32LE = BP.readInt32LE
arr.readInt32BE = BP.readInt32BE
arr.readFloatLE = BP.readFloatLE
arr.readFloatBE = BP.readFloatBE
arr.readDoubleLE = BP.readDoubleLE
arr.readDoubleBE = BP.readDoubleBE
arr.writeUInt8 = BP.writeUInt8
+ arr.writeUIntLE = BP.writeUIntLE
+ arr.writeUIntBE = BP.writeUIntBE
arr.writeUInt16LE = BP.writeUInt16LE
arr.writeUInt16BE = BP.writeUInt16BE
arr.writeUInt32LE = BP.writeUInt32LE
arr.writeUInt32BE = BP.writeUInt32BE
+ arr.writeIntLE = BP.writeIntLE
+ arr.writeIntBE = BP.writeIntBE
arr.writeInt8 = BP.writeInt8
arr.writeInt16LE = BP.writeInt16LE
arr.writeInt16BE = BP.writeInt16BE
arr.writeInt32LE = BP.writeInt32LE
arr.writeInt32BE = BP.writeInt32BE
@@ -1303,15 +1615,17 @@
arr.toArrayBuffer = BP.toArrayBuffer
return arr
}
-var INVALID_BASE64_RE = /[^+\/0-9A-z]/g
+var INVALID_BASE64_RE = /[^+\/0-9A-z\-]/g
function base64clean (str) {
// Node strips out invalid characters like \n and \t from the string, base64-js does not
str = stringtrim(str).replace(INVALID_BASE64_RE, '')
+ // Node converts strings with length < 2 to ''
+ if (str.length < 2) return ''
// Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
while (str.length % 4 !== 0) {
str = str + '='
}
return str
@@ -1331,26 +1645,89 @@
function toHex (n) {
if (n < 16) return '0' + n.toString(16)
return n.toString(16)
}
-function utf8ToBytes (str) {
- var byteArray = []
- for (var i = 0; i < str.length; i++) {
- var b = str.charCodeAt(i)
- if (b <= 0x7F) {
- byteArray.push(b)
- } else {
- var start = i
- if (b >= 0xD800 && b <= 0xDFFF) i++
- var h = encodeURIComponent(str.slice(start, i+1)).substr(1).split('%')
- for (var j = 0; j < h.length; j++) {
- byteArray.push(parseInt(h[j], 16))
+function utf8ToBytes (string, units) {
+ units = units || Infinity
+ var codePoint
+ var length = string.length
+ var leadSurrogate = null
+ var bytes = []
+ var i = 0
+
+ for (; i < length; i++) {
+ codePoint = string.charCodeAt(i)
+
+ // is surrogate component
+ if (codePoint > 0xD7FF && codePoint < 0xE000) {
+ // last char was a lead
+ if (leadSurrogate) {
+ // 2 leads in a row
+ if (codePoint < 0xDC00) {
+ if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
+ leadSurrogate = codePoint
+ continue
+ } else {
+ // valid surrogate pair
+ codePoint = leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00 | 0x10000
+ leadSurrogate = null
+ }
+ } else {
+ // no lead yet
+
+ if (codePoint > 0xDBFF) {
+ // unexpected trail
+ if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
+ continue
+ } else if (i + 1 === length) {
+ // unpaired lead
+ if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
+ continue
+ } else {
+ // valid lead
+ leadSurrogate = codePoint
+ continue
+ }
}
+ } else if (leadSurrogate) {
+ // valid bmp char, but last char was a lead
+ if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
+ leadSurrogate = null
}
+
+ // encode utf8
+ if (codePoint < 0x80) {
+ if ((units -= 1) < 0) break
+ bytes.push(codePoint)
+ } else if (codePoint < 0x800) {
+ if ((units -= 2) < 0) break
+ bytes.push(
+ codePoint >> 0x6 | 0xC0,
+ codePoint & 0x3F | 0x80
+ )
+ } else if (codePoint < 0x10000) {
+ if ((units -= 3) < 0) break
+ bytes.push(
+ codePoint >> 0xC | 0xE0,
+ codePoint >> 0x6 & 0x3F | 0x80,
+ codePoint & 0x3F | 0x80
+ )
+ } else if (codePoint < 0x200000) {
+ if ((units -= 4) < 0) break
+ bytes.push(
+ codePoint >> 0x12 | 0xF0,
+ codePoint >> 0xC & 0x3F | 0x80,
+ codePoint >> 0x6 & 0x3F | 0x80,
+ codePoint & 0x3F | 0x80
+ )
+ } else {
+ throw new Error('Invalid code point')
+ }
}
- return byteArray
+
+ return bytes
}
function asciiToBytes (str) {
var byteArray = []
for (var i = 0; i < str.length; i++) {
@@ -1358,14 +1735,16 @@
byteArray.push(str.charCodeAt(i) & 0xFF)
}
return byteArray
}
-function utf16leToBytes (str) {
+function utf16leToBytes (str, units) {
var c, hi, lo
var byteArray = []
for (var i = 0; i < str.length; i++) {
+ if ((units -= 2) < 0) break
+
c = str.charCodeAt(i)
hi = c >> 8
lo = c % 256
byteArray.push(lo)
byteArray.push(hi)
@@ -1373,17 +1752,16 @@
return byteArray
}
function base64ToBytes (str) {
- return base64.toByteArray(str)
+ return base64.toByteArray(base64clean(str))
}
function blitBuffer (src, dst, offset, length) {
for (var i = 0; i < length; i++) {
- if ((i + offset >= dst.length) || (i >= src.length))
- break
+ if ((i + offset >= dst.length) || (i >= src.length)) break
dst[i + offset] = src[i]
}
return i
}
@@ -1393,11 +1771,11 @@
} catch (err) {
return String.fromCharCode(0xFFFD) // UTF 8 invalid char
}
}
-},{"base64-js":3,"ieee754":4,"is-array":5}],3:[function(_dereq_,module,exports){
+},{"base64-js":4,"ieee754":5,"is-array":6}],4:[function(_dereq_,module,exports){
var lookup = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
;(function (exports) {
'use strict';
@@ -1408,16 +1786,20 @@
var PLUS = '+'.charCodeAt(0)
var SLASH = '/'.charCodeAt(0)
var NUMBER = '0'.charCodeAt(0)
var LOWER = 'a'.charCodeAt(0)
var UPPER = 'A'.charCodeAt(0)
+ var PLUS_URL_SAFE = '-'.charCodeAt(0)
+ var SLASH_URL_SAFE = '_'.charCodeAt(0)
function decode (elt) {
var code = elt.charCodeAt(0)
- if (code === PLUS)
+ if (code === PLUS ||
+ code === PLUS_URL_SAFE)
return 62 // '+'
- if (code === SLASH)
+ if (code === SLASH ||
+ code === SLASH_URL_SAFE)
return 63 // '/'
if (code < NUMBER)
return -1 //no match
if (code < NUMBER + 10)
return code - NUMBER + 26 + 26
@@ -1515,11 +1897,11 @@
exports.toByteArray = b64ToByteArray
exports.fromByteArray = uint8ToBase64
}(typeof exports === 'undefined' ? (this.base64js = {}) : exports))
-},{}],4:[function(_dereq_,module,exports){
+},{}],5:[function(_dereq_,module,exports){
exports.read = function(buffer, offset, isLE, mLen, nBytes) {
var e, m,
eLen = nBytes * 8 - mLen - 1,
eMax = (1 << eLen) - 1,
eBias = eMax >> 1,
@@ -1601,11 +1983,11 @@
for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8);
buffer[offset + i - d] |= s * 128;
};
-},{}],5:[function(_dereq_,module,exports){
+},{}],6:[function(_dereq_,module,exports){
/**
* isArray
*/
@@ -1636,11 +2018,11 @@
module.exports = isArray || function (val) {
return !! val && '[object Array]' == str.call(val);
};
-},{}],6:[function(_dereq_,module,exports){
+},{}],7:[function(_dereq_,module,exports){
(function (process){
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
@@ -1864,77 +2246,48 @@
return str.substr(start, len);
}
;
}).call(this,_dereq_('_process'))
-},{"_process":7}],7:[function(_dereq_,module,exports){
+},{"_process":8}],8:[function(_dereq_,module,exports){
// shim for using process in browser
var process = module.exports = {};
+var queue = [];
+var draining = false;
-process.nextTick = (function () {
- var canSetImmediate = typeof window !== 'undefined'
- && window.setImmediate;
- var canMutationObserver = typeof window !== 'undefined'
- && window.MutationObserver;
- var canPost = typeof window !== 'undefined'
- && window.postMessage && window.addEventListener
- ;
-
- if (canSetImmediate) {
- return function (f) { return window.setImmediate(f) };
+function drainQueue() {
+ if (draining) {
+ return;
}
-
- var queue = [];
-
- if (canMutationObserver) {
- var hiddenDiv = document.createElement("div");
- var observer = new MutationObserver(function () {
- var queueList = queue.slice();
- queue.length = 0;
- queueList.forEach(function (fn) {
- fn();
- });
- });
-
- observer.observe(hiddenDiv, { attributes: true });
-
- return function nextTick(fn) {
- if (!queue.length) {
- hiddenDiv.setAttribute('yes', 'no');
- }
- queue.push(fn);
- };
+ draining = true;
+ var currentQueue;
+ var len = queue.length;
+ while(len) {
+ currentQueue = queue;
+ queue = [];
+ var i = -1;
+ while (++i < len) {
+ currentQueue[i]();
+ }
+ len = queue.length;
}
-
- if (canPost) {
- window.addEventListener('message', function (ev) {
- var source = ev.source;
- if ((source === window || source === null) && ev.data === 'process-tick') {
- ev.stopPropagation();
- if (queue.length > 0) {
- var fn = queue.shift();
- fn();
- }
- }
- }, true);
-
- return function nextTick(fn) {
- queue.push(fn);
- window.postMessage('process-tick', '*');
- };
+ draining = false;
+}
+process.nextTick = function (fun) {
+ queue.push(fun);
+ if (!draining) {
+ setTimeout(drainQueue, 0);
}
+};
- return function nextTick(fn) {
- setTimeout(fn, 0);
- };
-})();
-
process.title = 'browser';
process.browser = true;
process.env = {};
process.argv = [];
+process.version = ''; // empty string to avoid regexp issues
+process.versions = {};
function noop() {}
process.on = noop;
process.addListener = noop;
@@ -1951,39 +2304,12 @@
// TODO(shtylman)
process.cwd = function () { return '/' };
process.chdir = function (dir) {
throw new Error('process.chdir is not supported');
};
+process.umask = function() { return 0; };
-},{}],8:[function(_dereq_,module,exports){
-var Base62 = (function (my) {
- 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"]
-
- my.encode = function(i){
- if (i === 0) {return '0'}
- var s = ''
- while (i > 0) {
- s = this.chars[i % 62] + s
- i = Math.floor(i/62)
- }
- return s
- };
- my.decode = function(a,b,c,d){
- for (
- b = c = (
- a === (/\W|_|^$/.test(a += "") || a)
- ) - 1;
- d = a.charCodeAt(c++);
- )
- b = b * 62 + d - [, 48, 29, 87][d >> 5];
- return b
- };
-
- return my;
-}({}));
-
-module.exports = Base62
},{}],9:[function(_dereq_,module,exports){
/*
Copyright (C) 2013 Ariya Hidayat <ariya.hidayat@gmail.com>
Copyright (C) 2013 Thaddee Tyl <thaddee.tyl@gmail.com>
Copyright (C) 2012 Ariya Hidayat <ariya.hidayat@gmail.com>
@@ -2013,39 +2339,17 @@
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-/*jslint bitwise:true plusplus:true */
-/*global esprima:true, define:true, exports:true, window: true,
-throwError: true, generateStatement: true, peek: true,
-parseAssignmentExpression: true, parseBlock: true,
-parseClassExpression: true, parseClassDeclaration: true, parseExpression: true,
-parseDeclareClass: true, parseDeclareFunction: true,
-parseDeclareModule: true, parseDeclareVariable: true,
-parseForStatement: true,
-parseFunctionDeclaration: true, parseFunctionExpression: true,
-parseFunctionSourceElements: true, parseVariableIdentifier: true,
-parseImportSpecifier: true, parseInterface: true,
-parseLeftHandSideExpression: true, parseParams: true, validateParam: true,
-parseSpreadOrAssignmentExpression: true,
-parseStatement: true, parseSourceElement: true, parseConciseBody: true,
-advanceXJSChild: true, isXJSIdentifierStart: true, isXJSIdentifierPart: true,
-scanXJSStringLiteral: true, scanXJSIdentifier: true,
-parseXJSAttributeValue: true, parseXJSChild: true, parseXJSElement: true, parseXJSExpressionContainer: true, parseXJSEmptyExpression: true,
-parseFunctionTypeParam: true,
-parsePrimaryType: true,
-parseTypeAlias: true,
-parseType: true, parseTypeAnnotatableIdentifier: true, parseTypeAnnotation: true,
-parseYieldExpression: true, parseAwaitExpression: true
-*/
-
(function (root, factory) {
'use strict';
// Universal Module Definition (UMD) to support AMD, CommonJS/Node.js,
// Rhino, and plain browser loading.
+
+ /* istanbul ignore next */
if (typeof define === 'function' && define.amd) {
define(['exports'], factory);
} else if (typeof exports !== 'undefined') {
factory(exports);
} else {
@@ -2084,12 +2388,12 @@
NumericLiteral: 6,
Punctuator: 7,
StringLiteral: 8,
RegularExpression: 9,
Template: 10,
- XJSIdentifier: 11,
- XJSText: 12
+ JSXIdentifier: 11,
+ JSXText: 12
};
TokenName = {};
TokenName[Token.BooleanLiteral] = 'Boolean';
TokenName[Token.EOF] = '<end>';
@@ -2097,12 +2401,12 @@
TokenName[Token.Keyword] = 'Keyword';
TokenName[Token.NullLiteral] = 'Null';
TokenName[Token.NumericLiteral] = 'Numeric';
TokenName[Token.Punctuator] = 'Punctuator';
TokenName[Token.StringLiteral] = 'String';
- TokenName[Token.XJSIdentifier] = 'XJSIdentifier';
- TokenName[Token.XJSText] = 'XJSText';
+ TokenName[Token.JSXIdentifier] = 'JSXIdentifier';
+ TokenName[Token.JSXText] = 'JSXText';
TokenName[Token.RegularExpression] = 'RegularExpression';
// A function following one of those tokens is an expression.
FnExprTokens = ['(', '{', '[', 'in', 'typeof', 'instanceof', 'new',
'return', 'case', 'delete', 'throw', 'void',
@@ -2197,10 +2501,11 @@
ThrowStatement: 'ThrowStatement',
TupleTypeAnnotation: 'TupleTypeAnnotation',
TryStatement: 'TryStatement',
TypeAlias: 'TypeAlias',
TypeAnnotation: 'TypeAnnotation',
+ TypeCastExpression: 'TypeCastExpression',
TypeofTypeAnnotation: 'TypeofTypeAnnotation',
TypeParameterDeclaration: 'TypeParameterDeclaration',
TypeParameterInstantiation: 'TypeParameterInstantiation',
UnaryExpression: 'UnaryExpression',
UnionTypeAnnotation: 'UnionTypeAnnotation',
@@ -2208,21 +2513,21 @@
VariableDeclaration: 'VariableDeclaration',
VariableDeclarator: 'VariableDeclarator',
VoidTypeAnnotation: 'VoidTypeAnnotation',
WhileStatement: 'WhileStatement',
WithStatement: 'WithStatement',
- XJSIdentifier: 'XJSIdentifier',
- XJSNamespacedName: 'XJSNamespacedName',
- XJSMemberExpression: 'XJSMemberExpression',
- XJSEmptyExpression: 'XJSEmptyExpression',
- XJSExpressionContainer: 'XJSExpressionContainer',
- XJSElement: 'XJSElement',
- XJSClosingElement: 'XJSClosingElement',
- XJSOpeningElement: 'XJSOpeningElement',
- XJSAttribute: 'XJSAttribute',
- XJSSpreadAttribute: 'XJSSpreadAttribute',
- XJSText: 'XJSText',
+ JSXIdentifier: 'JSXIdentifier',
+ JSXNamespacedName: 'JSXNamespacedName',
+ JSXMemberExpression: 'JSXMemberExpression',
+ JSXEmptyExpression: 'JSXEmptyExpression',
+ JSXExpressionContainer: 'JSXExpressionContainer',
+ JSXElement: 'JSXElement',
+ JSXClosingElement: 'JSXClosingElement',
+ JSXOpeningElement: 'JSXOpeningElement',
+ JSXAttribute: 'JSXAttribute',
+ JSXSpreadAttribute: 'JSXSpreadAttribute',
+ JSXText: 'JSXText',
YieldExpression: 'YieldExpression',
AwaitExpression: 'AwaitExpression'
};
PropertyKind = {
@@ -2236,63 +2541,66 @@
prototype: 'prototype'
};
// Error messages should be identical to V8.
Messages = {
- UnexpectedToken: 'Unexpected token %0',
- UnexpectedNumber: 'Unexpected number',
- UnexpectedString: 'Unexpected string',
- UnexpectedIdentifier: 'Unexpected identifier',
- UnexpectedReserved: 'Unexpected reserved word',
- UnexpectedTemplate: 'Unexpected quasi %0',
- UnexpectedEOS: 'Unexpected end of input',
- NewlineAfterThrow: 'Illegal newline after throw',
+ UnexpectedToken: 'Unexpected token %0',
+ UnexpectedNumber: 'Unexpected number',
+ UnexpectedString: 'Unexpected string',
+ UnexpectedIdentifier: 'Unexpected identifier',
+ UnexpectedReserved: 'Unexpected reserved word',
+ UnexpectedTemplate: 'Unexpected quasi %0',
+ UnexpectedEOS: 'Unexpected end of input',
+ NewlineAfterThrow: 'Illegal newline after throw',
InvalidRegExp: 'Invalid regular expression',
- UnterminatedRegExp: 'Invalid regular expression: missing /',
- InvalidLHSInAssignment: 'Invalid left-hand side in assignment',
- InvalidLHSInFormalsList: 'Invalid left-hand side in formals list',
- InvalidLHSInForIn: 'Invalid left-hand side in for-in',
+ UnterminatedRegExp: 'Invalid regular expression: missing /',
+ InvalidLHSInAssignment: 'Invalid left-hand side in assignment',
+ InvalidLHSInFormalsList: 'Invalid left-hand side in formals list',
+ InvalidLHSInForIn: 'Invalid left-hand side in for-in',
MultipleDefaultsInSwitch: 'More than one default clause in switch statement',
- NoCatchOrFinally: 'Missing catch or finally after try',
+ NoCatchOrFinally: 'Missing catch or finally after try',
UnknownLabel: 'Undefined label \'%0\'',
Redeclaration: '%0 \'%1\' has already been declared',
IllegalContinue: 'Illegal continue statement',
IllegalBreak: 'Illegal break statement',
IllegalDuplicateClassProperty: 'Illegal duplicate property in class definition',
+ IllegalClassConstructorProperty: 'Illegal constructor property in class definition',
IllegalReturn: 'Illegal return statement',
IllegalSpread: 'Illegal spread element',
- StrictModeWith: 'Strict mode code may not include a with statement',
- StrictCatchVariable: 'Catch variable may not be eval or arguments in strict mode',
- StrictVarName: 'Variable name may not be eval or arguments in strict mode',
- StrictParamName: 'Parameter name eval or arguments is not allowed in strict mode',
+ StrictModeWith: 'Strict mode code may not include a with statement',
+ StrictCatchVariable: 'Catch variable may not be eval or arguments in strict mode',
+ StrictVarName: 'Variable name may not be eval or arguments in strict mode',
+ StrictParamName: 'Parameter name eval or arguments is not allowed in strict mode',
StrictParamDupe: 'Strict mode function may not have duplicate parameter names',
ParameterAfterRestParameter: 'Rest parameter must be final parameter of an argument list',
DefaultRestParameter: 'Rest parameter can not have a default value',
ElementAfterSpreadElement: 'Spread must be the final element of an element list',
PropertyAfterSpreadProperty: 'A rest property must be the final property of an object literal',
ObjectPatternAsRestParameter: 'Invalid rest parameter',
ObjectPatternAsSpread: 'Invalid spread argument',
- StrictFunctionName: 'Function name may not be eval or arguments in strict mode',
- StrictOctalLiteral: 'Octal literals are not allowed in strict mode.',
- StrictDelete: 'Delete of an unqualified identifier in strict mode.',
- StrictDuplicateProperty: 'Duplicate data property in object literal not allowed in strict mode',
- AccessorDataProperty: 'Object literal may not have data and accessor property with the same name',
- AccessorGetSet: 'Object literal may not have multiple get/set accessors with the same name',
- StrictLHSAssignment: 'Assignment to eval or arguments is not allowed in strict mode',
- StrictLHSPostfix: 'Postfix increment/decrement may not have eval or arguments operand in strict mode',
- StrictLHSPrefix: 'Prefix increment/decrement may not have eval or arguments operand in strict mode',
- StrictReservedWord: 'Use of future reserved word in strict mode',
+ StrictFunctionName: 'Function name may not be eval or arguments in strict mode',
+ StrictOctalLiteral: 'Octal literals are not allowed in strict mode.',
+ StrictDelete: 'Delete of an unqualified identifier in strict mode.',
+ StrictDuplicateProperty: 'Duplicate data property in object literal not allowed in strict mode',
+ AccessorDataProperty: 'Object literal may not have data and accessor property with the same name',
+ AccessorGetSet: 'Object literal may not have multiple get/set accessors with the same name',
+ StrictLHSAssignment: 'Assignment to eval or arguments is not allowed in strict mode',
+ StrictLHSPostfix: 'Postfix increment/decrement may not have eval or arguments operand in strict mode',
+ StrictLHSPrefix: 'Prefix increment/decrement may not have eval or arguments operand in strict mode',
+ StrictReservedWord: 'Use of future reserved word in strict mode',
MissingFromClause: 'Missing from clause',
NoAsAfterImportNamespace: 'Missing as after import *',
InvalidModuleSpecifier: 'Invalid module specifier',
- NoUnintializedConst: 'Const must be initialized',
+ IllegalImportDeclaration: 'Illegal import declaration',
+ IllegalExportDeclaration: 'Illegal export declaration',
+ NoUninitializedConst: 'Const must be initialized',
ComprehensionRequiresBlock: 'Comprehension must have at least one block',
- ComprehensionError: 'Comprehension Error',
- EachNotAllowed: 'Each is not supported',
- InvalidXJSAttributeValue: 'XJS value should be either an expression or a quoted XJS text',
- ExpectedXJSClosingTag: 'Expected corresponding XJS closing tag for %0',
- AdjacentXJSElements: 'Adjacent XJS elements must be wrapped in an enclosing tag',
+ ComprehensionError: 'Comprehension Error',
+ EachNotAllowed: 'Each is not supported',
+ InvalidJSXAttributeValue: 'JSX value should be either an expression or a quoted JSX text',
+ ExpectedJSXClosingTag: 'Expected corresponding JSX closing tag for %0',
+ AdjacentJSXElements: 'Adjacent JSX elements must be wrapped in an enclosing tag',
ConfusedAboutFunctionType: 'Unexpected token =>. It looks like ' +
'you are trying to write a function type, but you ended up ' +
'writing a grouped type followed by an =>, which is a syntax ' +
'error. Remember, function type parameters are named so function ' +
'types look like (name1: type1, name2: type2) => returnType. You ' +
@@ -2310,15 +2618,41 @@
// This is only to have a better contract semantic, i.e. another safety net
// to catch a logic error. The condition shall be fulfilled in normal case.
// Do NOT use this to enforce a certain condition on any user input.
function assert(condition, message) {
+ /* istanbul ignore if */
if (!condition) {
throw new Error('ASSERT: ' + message);
}
}
+ function StringMap() {
+ this.$data = {};
+ }
+
+ StringMap.prototype.get = function (key) {
+ key = '$' + key;
+ return this.$data[key];
+ };
+
+ StringMap.prototype.set = function (key, value) {
+ key = '$' + key;
+ this.$data[key] = value;
+ return this;
+ };
+
+ StringMap.prototype.has = function (key) {
+ key = '$' + key;
+ return Object.prototype.hasOwnProperty.call(this.$data, key);
+ };
+
+ StringMap.prototype["delete"] = function (key) {
+ key = '$' + key;
+ return delete this.$data[key];
+ };
+
function isDecimalDigit(ch) {
return (ch >= 48 && ch <= 57); // 0..9
}
function isHexDigit(ch) {
@@ -2442,81 +2776,159 @@
}
}
// 7.4 Comments
- function skipComment() {
- var ch, blockComment, lineComment;
+ function addComment(type, value, start, end, loc) {
+ var comment;
+ assert(typeof start === 'number', 'Comment must have valid position');
- blockComment = false;
- lineComment = false;
+ // Because the way the actual token is scanned, often the comments
+ // (if any) are skipped twice during the lexical analysis.
+ // Thus, we need to skip adding a comment if the comment array already
+ // handled it.
+ if (state.lastCommentStart >= start) {
+ return;
+ }
+ state.lastCommentStart = start;
+ comment = {
+ type: type,
+ value: value
+ };
+ if (extra.range) {
+ comment.range = [start, end];
+ }
+ if (extra.loc) {
+ comment.loc = loc;
+ }
+ extra.comments.push(comment);
+ if (extra.attachComment) {
+ extra.leadingComments.push(comment);
+ extra.trailingComments.push(comment);
+ }
+ }
+
+ function skipSingleLineComment() {
+ var start, loc, ch, comment;
+
+ start = index - 2;
+ loc = {
+ start: {
+ line: lineNumber,
+ column: index - lineStart - 2
+ }
+ };
+
while (index < length) {
ch = source.charCodeAt(index);
+ ++index;
+ if (isLineTerminator(ch)) {
+ if (extra.comments) {
+ comment = source.slice(start + 2, index - 1);
+ loc.end = {
+ line: lineNumber,
+ column: index - lineStart - 1
+ };
+ addComment('Line', comment, start, index - 1, loc);
+ }
+ if (ch === 13 && source.charCodeAt(index) === 10) {
+ ++index;
+ }
+ ++lineNumber;
+ lineStart = index;
+ return;
+ }
+ }
- if (lineComment) {
+ if (extra.comments) {
+ comment = source.slice(start + 2, index);
+ loc.end = {
+ line: lineNumber,
+ column: index - lineStart
+ };
+ addComment('Line', comment, start, index, loc);
+ }
+ }
+
+ function skipMultiLineComment() {
+ var start, loc, ch, comment;
+
+ if (extra.comments) {
+ start = index - 2;
+ loc = {
+ start: {
+ line: lineNumber,
+ column: index - lineStart - 2
+ }
+ };
+ }
+
+ while (index < length) {
+ ch = source.charCodeAt(index);
+ if (isLineTerminator(ch)) {
+ if (ch === 13 && source.charCodeAt(index + 1) === 10) {
+ ++index;
+ }
+ ++lineNumber;
++index;
- if (isLineTerminator(ch)) {
- lineComment = false;
- if (ch === 13 && source.charCodeAt(index) === 10) {
- ++index;
- }
- ++lineNumber;
- lineStart = index;
+ lineStart = index;
+ if (index >= length) {
+ throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
}
- } else if (blockComment) {
- if (isLineTerminator(ch)) {
- if (ch === 13) {
- ++index;
+ } else if (ch === 42) {
+ // Block comment ends with '*/' (char #42, char #47).
+ if (source.charCodeAt(index + 1) === 47) {
+ ++index;
+ ++index;
+ if (extra.comments) {
+ comment = source.slice(start + 2, index - 2);
+ loc.end = {
+ line: lineNumber,
+ column: index - lineStart
+ };
+ addComment('Block', comment, start, index, loc);
}
- if (ch !== 13 || source.charCodeAt(index) === 10) {
- ++lineNumber;
- ++index;
- lineStart = index;
- if (index >= length) {
- throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
- }
- }
- } else {
- ch = source.charCodeAt(index++);
- if (index >= length) {
- throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
- }
- // Block comment ends with '*/' (char #42, char #47).
- if (ch === 42) {
- ch = source.charCodeAt(index);
- if (ch === 47) {
- ++index;
- blockComment = false;
- }
- }
+ return;
}
- } else if (ch === 47) {
- ch = source.charCodeAt(index + 1);
- // Line comment starts with '//' (char #47, char #47).
- if (ch === 47) {
- index += 2;
- lineComment = true;
- } else if (ch === 42) {
- // Block comment starts with '/*' (char #47, char #42).
- index += 2;
- blockComment = true;
- if (index >= length) {
- throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
- }
- } else {
- break;
- }
- } else if (isWhiteSpace(ch)) {
++index;
+ } else {
+ ++index;
+ }
+ }
+
+ throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
+ }
+
+ function skipComment() {
+ var ch;
+
+ while (index < length) {
+ ch = source.charCodeAt(index);
+
+ if (isWhiteSpace(ch)) {
+ ++index;
} else if (isLineTerminator(ch)) {
++index;
if (ch === 13 && source.charCodeAt(index) === 10) {
++index;
}
++lineNumber;
lineStart = index;
+ } else if (ch === 47) { // 47 is '/'
+ ch = source.charCodeAt(index + 1);
+ if (ch === 47) {
+ ++index;
+ ++index;
+ skipSingleLineComment();
+ } else if (ch === 42) { // 42 is '*'
+ ++index;
+ ++index;
+ skipMultiLineComment();
+ } else {
+ break;
+ }
} else {
break;
}
}
}
@@ -2675,10 +3087,27 @@
ch1 = source[index],
ch2,
ch3,
ch4;
+ if (state.inJSXTag || state.inJSXChild) {
+ // Don't need to check for '{' and '}' as it's already handled
+ // correctly by default.
+ switch (code) {
+ case 60: // <
+ case 62: // >
+ ++index;
+ return {
+ type: Token.Punctuator,
+ value: String.fromCharCode(code),
+ lineNumber: lineNumber,
+ lineStart: lineStart,
+ range: [start, index]
+ };
+ }
+ }
+
switch (code) {
// Check for most common single-character punctuators.
case 40: // ( open bracket
case 41: // ) close bracket
case 59: // ; semicolon
@@ -2774,11 +3203,11 @@
}
}
// 3-character punctuators: === !== >>> <<= >>=
- if (ch1 === '>' && ch2 === '>' && ch3 === '>') {
+ if (ch1 === '>' && ch2 === '>' && ch3 === '>' && !state.inType) {
index += 3;
return {
type: Token.Punctuator,
value: '>>>',
lineNumber: lineNumber,
@@ -2898,10 +3327,45 @@
lineStart: lineStart,
range: [start, index]
};
}
+ function scanBinaryLiteral(start) {
+ var ch, number;
+
+ number = '';
+
+ while (index < length) {
+ ch = source[index];
+ if (ch !== '0' && ch !== '1') {
+ break;
+ }
+ number += source[index++];
+ }
+
+ if (number.length === 0) {
+ // only 0b or 0B
+ throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
+ }
+
+ if (index < length) {
+ ch = source.charCodeAt(index);
+ /* istanbul ignore else */
+ if (isIdentifierStart(ch) || isDecimalDigit(ch)) {
+ throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
+ }
+ }
+
+ return {
+ type: Token.NumericLiteral,
+ value: parseInt(number, 2),
+ lineNumber: lineNumber,
+ lineStart: lineStart,
+ range: [start, index]
+ };
+ }
+
function scanOctalLiteral(prefix, start) {
var number, octal;
if (isOctalDigit(prefix)) {
octal = true;
@@ -2937,11 +3401,11 @@
range: [start, index]
};
}
function scanNumericLiteral() {
- var number, start, ch, octal;
+ var number, start, ch;
ch = source[index];
assert(isDecimalDigit(ch.charCodeAt(0)) || (ch === '.'),
'Numeric literal must start with a decimal digit or a decimal point');
@@ -2960,38 +3424,11 @@
++index;
return scanHexLiteral(start);
}
if (ch === 'b' || ch === 'B') {
++index;
- number = '';
-
- while (index < length) {
- ch = source[index];
- if (ch !== '0' && ch !== '1') {
- break;
- }
- number += source[index++];
- }
-
- if (number.length === 0) {
- // only 0b or 0B
- throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
- }
-
- if (index < length) {
- ch = source.charCodeAt(index);
- if (isIdentifierStart(ch) || isDecimalDigit(ch)) {
- throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
- }
- }
- return {
- type: Token.NumericLiteral,
- value: parseInt(number, 2),
- lineNumber: lineNumber,
- lineStart: lineStart,
- range: [start, index]
- };
+ return scanBinaryLiteral(start);
}
if (ch === 'o' || ch === 'O' || isOctalDigit(ch)) {
return scanOctalLiteral(ch, start);
}
// decimal number starts with '0' such as '09' is illegal.
@@ -3107,10 +3544,11 @@
// \0 is not octal escape sequence
if (code !== 0) {
octal = true;
}
+ /* istanbul ignore else */
if (index < length && isOctalDigit(source[index])) {
octal = true;
code = code * 8 + '01234567'.indexOf(source[index++]);
// 3 digits are only allowed when string starts
@@ -3127,11 +3565,11 @@
}
break;
}
} else {
++lineNumber;
- if (ch === '\r' && source[index] === '\n') {
+ if (ch === '\r' && source[index] === '\n') {
++index;
}
lineStart = index;
}
} else if (isLineTerminator(ch.charCodeAt(0))) {
@@ -3223,10 +3661,11 @@
// \0 is not octal escape sequence
if (code !== 0) {
octal = true;
}
+ /* istanbul ignore else */
if (index < length && isOctalDigit(source[index])) {
octal = true;
code = code * 8 + '01234567'.indexOf(source[index++]);
// 3 digits are only allowed when string starts
@@ -3243,18 +3682,18 @@
}
break;
}
} else {
++lineNumber;
- if (ch === '\r' && source[index] === '\n') {
+ if (ch === '\r' && source[index] === '\n') {
++index;
}
lineStart = index;
}
} else if (isLineTerminator(ch.charCodeAt(0))) {
++lineNumber;
- if (ch === '\r' && source[index] === '\n') {
+ if (ch === '\r' && source[index] === '\n') {
++index;
}
lineStart = index;
cooked += '\n';
} else {
@@ -3297,54 +3736,101 @@
peek();
return template;
}
- function scanRegExp() {
- var str, ch, start, pattern, flags, value, classMarker = false, restore, terminated = false, tmp;
+ function testRegExp(pattern, flags) {
+ var tmp = pattern,
+ value;
- lookahead = null;
- skipComment();
+ if (flags.indexOf('u') >= 0) {
+ // Replace each astral symbol and every Unicode code point
+ // escape sequence with a single ASCII symbol to avoid throwing on
+ // regular expressions that are only valid in combination with the
+ // `/u` flag.
+ // Note: replacing with the ASCII symbol `x` might cause false
+ // negatives in unlikely scenarios. For example, `[\u{61}-b]` is a
+ // perfectly valid pattern that is equivalent to `[a-b]`, but it
+ // would be replaced by `[x-b]` which throws an error.
+ tmp = tmp
+ .replace(/\\u\{([0-9a-fA-F]+)\}/g, function ($0, $1) {
+ if (parseInt($1, 16) <= 0x10FFFF) {
+ return 'x';
+ }
+ throwError({}, Messages.InvalidRegExp);
+ })
+ .replace(/[\uD800-\uDBFF][\uDC00-\uDFFF]/g, 'x');
+ }
- start = index;
+ // First, detect invalid regular expressions.
+ try {
+ value = new RegExp(tmp);
+ } catch (e) {
+ throwError({}, Messages.InvalidRegExp);
+ }
+
+ // Return a regular expression object for this pattern-flag pair, or
+ // `null` in case the current environment doesn't support the flags it
+ // uses.
+ try {
+ return new RegExp(pattern, flags);
+ } catch (exception) {
+ return null;
+ }
+ }
+
+ function scanRegExpBody() {
+ var ch, str, classMarker, terminated, body;
+
ch = source[index];
assert(ch === '/', 'Regular expression literal must start with a slash');
str = source[index++];
+ classMarker = false;
+ terminated = false;
while (index < length) {
ch = source[index++];
str += ch;
- if (classMarker) {
+ if (ch === '\\') {
+ ch = source[index++];
+ // ECMA-262 7.8.5
+ if (isLineTerminator(ch.charCodeAt(0))) {
+ throwError({}, Messages.UnterminatedRegExp);
+ }
+ str += ch;
+ } else if (isLineTerminator(ch.charCodeAt(0))) {
+ throwError({}, Messages.UnterminatedRegExp);
+ } else if (classMarker) {
if (ch === ']') {
classMarker = false;
}
} else {
- if (ch === '\\') {
- ch = source[index++];
- // ECMA-262 7.8.5
- if (isLineTerminator(ch.charCodeAt(0))) {
- throwError({}, Messages.UnterminatedRegExp);
- }
- str += ch;
- } else if (ch === '/') {
+ if (ch === '/') {
terminated = true;
break;
} else if (ch === '[') {
classMarker = true;
- } else if (isLineTerminator(ch.charCodeAt(0))) {
- throwError({}, Messages.UnterminatedRegExp);
}
}
}
if (!terminated) {
throwError({}, Messages.UnterminatedRegExp);
}
// Exclude leading and trailing slash.
- pattern = str.substr(1, str.length - 2);
+ body = str.substr(1, str.length - 2);
+ return {
+ value: body,
+ literal: str
+ };
+ }
+ function scanRegExpFlags() {
+ var ch, str, flags, restore;
+
+ str = '';
flags = '';
while (index < length) {
ch = source[index];
if (!isIdentifierPart(ch.charCodeAt(0))) {
break;
@@ -3365,67 +3851,58 @@
} else {
index = restore;
flags += 'u';
str += '\\u';
}
+ throwErrorTolerant({}, Messages.UnexpectedToken, 'ILLEGAL');
} else {
str += '\\';
+ throwErrorTolerant({}, Messages.UnexpectedToken, 'ILLEGAL');
}
} else {
flags += ch;
str += ch;
}
}
- tmp = pattern;
- if (flags.indexOf('u') >= 0) {
- // Replace each astral symbol and every Unicode code point
- // escape sequence that represents such a symbol with a single
- // ASCII symbol to avoid throwing on regular expressions that
- // are only valid in combination with the `/u` flag.
- tmp = tmp
- .replace(/\\u\{([0-9a-fA-F]{5,6})\}/g, 'x')
- .replace(/[\uD800-\uDBFF][\uDC00-\uDFFF]/g, 'x');
- }
+ return {
+ value: flags,
+ literal: str
+ };
+ }
- // First, detect invalid regular expressions.
- try {
- value = new RegExp(tmp);
- } catch (e) {
- throwError({}, Messages.InvalidRegExp);
- }
+ function scanRegExp() {
+ var start, body, flags, value;
- // Return a regular expression object for this pattern-flag pair, or
- // `null` in case the current environment doesn't support the flags it
- // uses.
- try {
- value = new RegExp(pattern, flags);
- } catch (exception) {
- value = null;
- }
+ lookahead = null;
+ skipComment();
+ start = index;
- peek();
+ body = scanRegExpBody();
+ flags = scanRegExpFlags();
+ value = testRegExp(body.value, flags.value);
if (extra.tokenize) {
return {
type: Token.RegularExpression,
value: value,
regex: {
- pattern: pattern,
- flags: flags
+ pattern: body.value,
+ flags: flags.value
},
lineNumber: lineNumber,
lineStart: lineStart,
range: [start, index]
};
}
+
return {
- literal: str,
+ literal: body.literal + flags.literal,
value: value,
regex: {
- pattern: pattern,
- flags: flags
+ pattern: body.value,
+ flags: flags.value
},
range: [start, index]
};
}
@@ -3488,20 +3965,20 @@
// It is a declaration.
return scanRegExp();
}
return scanRegExp();
}
- if (prevToken.type === 'Keyword') {
+ if (prevToken.type === 'Keyword' && prevToken.value !== 'this') {
return scanRegExp();
}
return scanPunctuator();
}
function advance() {
var ch;
- if (!state.inXJSChild) {
+ if (!state.inJSXChild) {
skipComment();
}
if (index >= length) {
return {
@@ -3510,12 +3987,12 @@
lineStart: lineStart,
range: [index, index]
};
}
- if (state.inXJSChild) {
- return advanceXJSChild();
+ if (state.inJSXChild) {
+ return advanceJSXChild();
}
ch = source.charCodeAt(index);
// Very common: ( and ) and ;
@@ -3523,18 +4000,18 @@
return scanPunctuator();
}
// String literal starts with single quote (#39) or double quote (#34).
if (ch === 39 || ch === 34) {
- if (state.inXJSTag) {
- return scanXJSStringLiteral();
+ if (state.inJSXTag) {
+ return scanJSXStringLiteral();
}
return scanStringLiteral();
}
- if (state.inXJSTag && isXJSIdentifierStart(ch)) {
- return scanXJSIdentifier();
+ if (state.inJSXTag && isJSXIdentifierStart(ch)) {
+ return scanJSXIdentifier();
}
if (ch === 96) {
return scanTemplate();
}
@@ -3594,17 +4071,19 @@
function lookahead2() {
var adv, pos, line, start, result;
// If we are collecting the tokens, don't grab the next one yet.
+ /* istanbul ignore next */
adv = (typeof extra.advance === 'function') ? extra.advance : advance;
pos = index;
line = lineNumber;
start = lineStart;
// Scan for the next immediate token.
+ /* istanbul ignore if */
if (lookahead === null) {
lookahead = adv();
}
index = lookahead.range[1];
lineNumber = lookahead.lineNumber;
@@ -3646,10 +4125,11 @@
trailingComments,
bottomRight = extra.bottomRightStack,
last = bottomRight[bottomRight.length - 1];
if (node.type === Syntax.Program) {
+ /* istanbul ignore else */
if (node.body.length > 0) {
return;
}
}
@@ -3915,10 +4395,18 @@
type: Syntax.TypeAnnotation,
typeAnnotation: typeAnnotation
};
},
+ createTypeCast: function (expression, typeAnnotation) {
+ return {
+ type: Syntax.TypeCastExpression,
+ expression: expression,
+ typeAnnotation: typeAnnotation
+ };
+ },
+
createFunctionTypeAnnotation: function (params, returnType, rest, typeParameters) {
return {
type: Syntax.FunctionTypeAnnotation,
params: params,
returnType: returnType,
@@ -4130,82 +4618,82 @@
id: id,
body: body
};
},
- createXJSAttribute: function (name, value) {
+ createJSXAttribute: function (name, value) {
return {
- type: Syntax.XJSAttribute,
+ type: Syntax.JSXAttribute,
name: name,
value: value || null
};
},
- createXJSSpreadAttribute: function (argument) {
+ createJSXSpreadAttribute: function (argument) {
return {
- type: Syntax.XJSSpreadAttribute,
+ type: Syntax.JSXSpreadAttribute,
argument: argument
};
},
- createXJSIdentifier: function (name) {
+ createJSXIdentifier: function (name) {
return {
- type: Syntax.XJSIdentifier,
+ type: Syntax.JSXIdentifier,
name: name
};
},
- createXJSNamespacedName: function (namespace, name) {
+ createJSXNamespacedName: function (namespace, name) {
return {
- type: Syntax.XJSNamespacedName,
+ type: Syntax.JSXNamespacedName,
namespace: namespace,
name: name
};
},
- createXJSMemberExpression: function (object, property) {
+ createJSXMemberExpression: function (object, property) {
return {
- type: Syntax.XJSMemberExpression,
+ type: Syntax.JSXMemberExpression,
object: object,
property: property
};
},
- createXJSElement: function (openingElement, closingElement, children) {
+ createJSXElement: function (openingElement, closingElement, children) {
return {
- type: Syntax.XJSElement,
+ type: Syntax.JSXElement,
openingElement: openingElement,
closingElement: closingElement,
children: children
};
},
- createXJSEmptyExpression: function () {
+ createJSXEmptyExpression: function () {
return {
- type: Syntax.XJSEmptyExpression
+ type: Syntax.JSXEmptyExpression
};
},
- createXJSExpressionContainer: function (expression) {
+ createJSXExpressionContainer: function (expression) {
return {
- type: Syntax.XJSExpressionContainer,
+ type: Syntax.JSXExpressionContainer,
expression: expression
};
},
- createXJSOpeningElement: function (name, attributes, selfClosing) {
+ createJSXOpeningElement: function (name, attributes, selfClosing) {
return {
- type: Syntax.XJSOpeningElement,
+ type: Syntax.JSXOpeningElement,
name: name,
selfClosing: selfClosing,
attributes: attributes
};
},
- createXJSClosingElement: function (name) {
+ createJSXClosingElement: function (name) {
return {
- type: Syntax.XJSClosingElement,
+ type: Syntax.JSXClosingElement,
name: name
};
},
createIfStatement: function (test, consequent, alternate) {
@@ -4446,17 +4934,18 @@
}
return arrowExpr;
},
- createMethodDefinition: function (propertyType, kind, key, value) {
+ createMethodDefinition: function (propertyType, kind, key, value, computed) {
return {
type: Syntax.MethodDefinition,
key: key,
value: value,
kind: kind,
- 'static': propertyType === ClassPropertyType["static"]
+ 'static': propertyType === ClassPropertyType["static"],
+ computed: computed
};
},
createClassProperty: function (key, typeAnnotation, computed, isStatic) {
return {
@@ -4541,17 +5030,17 @@
type: Syntax.ImportNamespaceSpecifier,
id: id
};
},
- createExportDeclaration: function (isDefault, declaration, specifiers, source) {
+ createExportDeclaration: function (isDefault, declaration, specifiers, src) {
return {
type: Syntax.ExportDeclaration,
'default': !!isDefault,
declaration: declaration,
specifiers: specifiers,
- source: source
+ source: src
};
},
createImportSpecifier: function (id, name) {
return {
@@ -4559,23 +5048,24 @@
id: id,
name: name
};
},
- createImportDeclaration: function (specifiers, source) {
+ createImportDeclaration: function (specifiers, src, isType) {
return {
type: Syntax.ImportDeclaration,
specifiers: specifiers,
- source: source
+ source: src,
+ isType: isType
};
},
- createYieldExpression: function (argument, delegate) {
+ createYieldExpression: function (argument, dlg) {
return {
type: Syntax.YieldExpression,
argument: argument,
- delegate: delegate
+ delegate: dlg
};
},
createAwaitExpression: function (argument) {
return {
@@ -4617,13 +5107,13 @@
function throwError(token, messageFormat) {
var error,
args = Array.prototype.slice.call(arguments, 2),
msg = messageFormat.replace(
/%(\d)/g,
- function (whole, index) {
- assert(index < args.length, 'Message reference must be in range');
- return args[index];
+ function (whole, idx) {
+ assert(idx < args.length, 'Message reference must be in range');
+ return args[idx];
}
);
if (typeof token.lineNumber === 'number') {
error = new Error('Line ' + token.lineNumber + ': ' + msg);
@@ -4663,11 +5153,11 @@
if (token.type === Token.NumericLiteral) {
throwError(token, Messages.UnexpectedNumber);
}
- if (token.type === Token.StringLiteral || token.type === Token.XJSText) {
+ if (token.type === Token.StringLiteral || token.type === Token.JSXText) {
throwError(token, Messages.UnexpectedString);
}
if (token.type === Token.Identifier) {
throwError(token, Messages.UnexpectedIdentifier);
@@ -4826,11 +5316,11 @@
}
// 11.1.4 Array Initialiser
function parseArrayInitialiser() {
- var elements = [], blocks = [], filter = null, tmp, possiblecomprehension = true, body,
+ var elements = [], blocks = [], filter = null, tmp, possiblecomprehension = true,
marker = markerCreate();
expect('[');
while (!match(']')) {
if (lookahead.value === 'for' &&
@@ -4982,15 +5472,15 @@
return markerApply(marker, delegate.createIdentifier(token.value));
}
function parseObjectProperty() {
- var token, key, id, value, param, expr, computed,
- marker = markerCreate(), returnType;
+ var token, key, id, param, computed,
+ marker = markerCreate(), returnType, typeParameters;
token = lookahead;
- computed = (token.value === '[');
+ computed = (token.value === '[' && token.type === Token.Punctuator);
if (token.type === Token.Identifier || computed || matchAsync()) {
id = parseObjectPropertyKey();
if (match(':')) {
@@ -5007,19 +5497,23 @@
computed
)
);
}
- if (match('(')) {
+ if (match('(') || match('<')) {
+ if (match('<')) {
+ typeParameters = parseTypeParameterDeclaration();
+ }
return markerApply(
marker,
delegate.createProperty(
'init',
id,
parsePropertyMethodFunction({
generator: false,
- async: false
+ async: false,
+ typeParameters: typeParameters
}),
true,
false,
computed
)
@@ -5088,18 +5582,23 @@
if (token.value === 'async') {
computed = (lookahead.value === '[');
key = parseObjectPropertyKey();
+ if (match('<')) {
+ typeParameters = parseTypeParameterDeclaration();
+ }
+
return markerApply(
marker,
delegate.createProperty(
'init',
key,
parsePropertyMethodFunction({
generator: false,
- async: true
+ async: true,
+ typeParameters: typeParameters
}),
true,
false,
computed
)
@@ -5125,36 +5624,71 @@
computed = (lookahead.type === Token.Punctuator && lookahead.value === '[');
id = parseObjectPropertyKey();
+ if (match('<')) {
+ typeParameters = parseTypeParameterDeclaration();
+ }
+
if (!match('(')) {
throwUnexpected(lex());
}
- return markerApply(marker, delegate.createProperty('init', id, parsePropertyMethodFunction({ generator: true }), true, false, computed));
+ return markerApply(marker, delegate.createProperty(
+ 'init',
+ id,
+ parsePropertyMethodFunction({
+ generator: true,
+ typeParameters: typeParameters
+ }),
+ true,
+ false,
+ computed
+ ));
}
key = parseObjectPropertyKey();
if (match(':')) {
lex();
return markerApply(marker, delegate.createProperty('init', key, parseAssignmentExpression(), false, false, false));
}
- if (match('(')) {
- return markerApply(marker, delegate.createProperty('init', key, parsePropertyMethodFunction({ generator: false }), true, false, false));
+ if (match('(') || match('<')) {
+ if (match('<')) {
+ typeParameters = parseTypeParameterDeclaration();
+ }
+ return markerApply(marker, delegate.createProperty(
+ 'init',
+ key,
+ parsePropertyMethodFunction({
+ generator: false,
+ typeParameters: typeParameters
+ }),
+ true,
+ false,
+ false
+ ));
}
throwUnexpected(lex());
}
function parseObjectSpreadProperty() {
var marker = markerCreate();
expect('...');
return markerApply(marker, delegate.createSpreadProperty(parseAssignmentExpression()));
}
+ function getFieldName(key) {
+ var toString = String;
+ if (key.type === Syntax.Identifier) {
+ return key.name;
+ }
+ return toString(key.value);
+ }
+
function parseObjectInitialiser() {
- var properties = [], property, name, key, kind, map = {}, toString = String,
- marker = markerCreate();
+ var properties = [], property, name, kind, storedKind, map = new StringMap(),
+ marker = markerCreate(), toString = String;
expect('{');
while (!match('}')) {
if (match('...')) {
@@ -5167,28 +5701,28 @@
} else {
name = toString(property.key.value);
}
kind = (property.kind === 'init') ? PropertyKind.Data : (property.kind === 'get') ? PropertyKind.Get : PropertyKind.Set;
- key = '$' + name;
- if (Object.prototype.hasOwnProperty.call(map, key)) {
- if (map[key] === PropertyKind.Data) {
+ if (map.has(name)) {
+ storedKind = map.get(name);
+ if (storedKind === PropertyKind.Data) {
if (strict && kind === PropertyKind.Data) {
throwErrorTolerant({}, Messages.StrictDuplicateProperty);
} else if (kind !== PropertyKind.Data) {
throwErrorTolerant({}, Messages.AccessorDataProperty);
}
} else {
if (kind === PropertyKind.Data) {
throwErrorTolerant({}, Messages.AccessorDataProperty);
- } else if (map[key] & kind) {
+ } else if (storedKind & kind) {
throwErrorTolerant({}, Messages.AccessorGetSet);
}
}
- map[key] |= kind;
+ map.set(name, storedKind | kind);
} else {
- map[key] = kind;
+ map.set(name, kind);
}
}
properties.push(property);
@@ -5228,18 +5762,28 @@
}
// 11.1.6 The Grouping Operator
function parseGroupExpression() {
- var expr;
+ var expr, marker, typeAnnotation;
expect('(');
++state.parenthesizedCount;
+ marker = markerCreate();
+
expr = parseExpression();
+ if (match(':')) {
+ typeAnnotation = parseTypeAnnotation();
+ expr = markerApply(marker, delegate.createTypeCast(
+ expr,
+ typeAnnotation
+ ));
+ }
+
expect(')');
return expr;
}
@@ -5324,19 +5868,21 @@
return parseGroupExpression();
}
if (match('/') || match('/=')) {
marker = markerCreate();
- return markerApply(marker, delegate.createLiteral(scanRegExp()));
+ expr = delegate.createLiteral(scanRegExp());
+ peek();
+ return markerApply(marker, expr);
}
if (type === Token.Template) {
return parseTemplateLiteral();
}
if (match('<')) {
- return parseXJSElement();
+ return parseJSXElement();
}
throwUnexpected(lex());
}
@@ -5692,10 +6238,12 @@
return expr;
}
// 11.13 Assignment Operators
+ // 12.14.5 AssignmentPattern
+
function reinterpretAsAssignmentBindingPattern(expr) {
var i, len, property, element;
if (expr.type === Syntax.ObjectExpression) {
expr.type = Syntax.ObjectPattern;
@@ -5715,10 +6263,11 @@
}
} else if (expr.type === Syntax.ArrayExpression) {
expr.type = Syntax.ArrayPattern;
for (i = 0, len = expr.elements.length; i < len; i += 1) {
element = expr.elements[i];
+ /* istanbul ignore else */
if (element) {
reinterpretAsAssignmentBindingPattern(element);
}
}
} else if (expr.type === Syntax.Identifier) {
@@ -5729,16 +6278,18 @@
reinterpretAsAssignmentBindingPattern(expr.argument);
if (expr.argument.type === Syntax.ObjectPattern) {
throwError({}, Messages.ObjectPatternAsSpread);
}
} else {
+ /* istanbul ignore else */
if (expr.type !== Syntax.MemberExpression && expr.type !== Syntax.CallExpression && expr.type !== Syntax.NewExpression) {
throwError({}, Messages.InvalidLHSInAssignment);
}
}
}
+ // 13.2.3 BindingPattern
function reinterpretAsDestructuredParameter(options, expr) {
var i, len, property, element;
if (expr.type === Syntax.ObjectExpression) {
@@ -5765,14 +6316,18 @@
reinterpretAsDestructuredParameter(options, element);
}
}
} else if (expr.type === Syntax.Identifier) {
validateParam(options, expr, expr.name);
- } else {
- if (expr.type !== Syntax.MemberExpression) {
+ } else if (expr.type === Syntax.SpreadElement) {
+ // BindingRestElement only allows BindingIdentifier
+ if (expr.argument.type !== Syntax.Identifier) {
throwError({}, Messages.InvalidLHSInFormalsList);
}
+ validateParam(options, expr.argument, expr.argument.name);
+ } else {
+ throwError({}, Messages.InvalidLHSInFormalsList);
}
}
function reinterpretAsCoverFormalsList(expressions) {
var i, len, param, params, defaults, defaultCount, options, rest;
@@ -5780,11 +6335,11 @@
params = [];
defaults = [];
defaultCount = 0;
rest = null;
options = {
- paramSet: {}
+ paramSet: new StringMap()
};
for (i = 0, len = expressions.length; i < len; i += 1) {
param = expressions[i];
if (param.type === Syntax.Identifier) {
@@ -5795,10 +6350,13 @@
reinterpretAsDestructuredParameter(options, param);
params.push(param);
defaults.push(null);
} else if (param.type === Syntax.SpreadElement) {
assert(i === len - 1, 'It is guaranteed that SpreadElement is last element by parseExpression');
+ if (param.argument.type !== Syntax.Identifier) {
+ throwError({}, Messages.InvalidLHSInFormalsList);
+ }
reinterpretAsDestructuredParameter(options, param.argument);
rest = param.argument;
} else if (param.type === Syntax.AssignmentExpression) {
params.push(param.left);
defaults.push(param.right);
@@ -5863,11 +6421,12 @@
));
}
function parseAssignmentExpression() {
var marker, expr, token, params, oldParenthesizedCount,
- backtrackToken = lookahead, possiblyAsync = false;
+ startsWithParen = false, backtrackToken = lookahead,
+ possiblyAsync = false;
if (matchYield()) {
return parseYieldExpression();
}
@@ -5900,10 +6459,11 @@
throwUnexpected(lex());
}
params.async = possiblyAsync;
return parseArrowFunctionExpression(params, marker);
}
+ startsWithParen = true;
}
token = lookahead;
// If the 'async' keyword is not followed by a '(' character or an
@@ -5919,10 +6479,17 @@
if (match('=>') &&
(state.parenthesizedCount === oldParenthesizedCount ||
state.parenthesizedCount === (oldParenthesizedCount + 1))) {
if (expr.type === Syntax.Identifier) {
params = reinterpretAsCoverFormalsList([ expr ]);
+ } else if (expr.type === Syntax.AssignmentExpression ||
+ expr.type === Syntax.ArrayExpression ||
+ expr.type === Syntax.ObjectExpression) {
+ if (!startsWithParen) {
+ throwUnexpected(lex());
+ }
+ params = reinterpretAsCoverFormalsList([ expr ]);
} else if (expr.type === Syntax.SequenceExpression) {
params = reinterpretAsCoverFormalsList(expr.expressions);
}
if (params) {
params.async = possiblyAsync;
@@ -5959,14 +6526,12 @@
}
// 11.14 Comma Operator
function parseExpression() {
- var marker, expr, expressions, sequence, coverFormalsList, spreadFound, oldParenthesizedCount;
+ var marker, expr, expressions, sequence, spreadFound;
- oldParenthesizedCount = state.parenthesizedCount;
-
marker = markerCreate();
expr = parseAssignmentExpression();
expressions = [ expr ];
if (match(',')) {
@@ -5989,22 +6554,10 @@
}
sequence = markerApply(marker, delegate.createSequenceExpression(expressions));
}
- if (match('=>')) {
- // Do not allow nested parentheses on the LHS of the =>.
- if (state.parenthesizedCount === oldParenthesizedCount || state.parenthesizedCount === (oldParenthesizedCount + 1)) {
- expr = expr.type === Syntax.SequenceExpression ? expr.expressions : expressions;
- coverFormalsList = reinterpretAsCoverFormalsList(expr);
- if (coverFormalsList) {
- return parseArrowFunctionExpression(coverFormalsList, marker);
- }
- }
- throwUnexpected(lex());
- }
-
if (spreadFound && lookahead2().value !== '=>') {
throwError({}, Messages.IllegalSpread);
}
return sequence || expr;
@@ -6047,11 +6600,11 @@
function parseTypeParameterDeclaration() {
var marker = markerCreate(), paramTypes = [];
expect('<');
while (!match('>')) {
- paramTypes.push(parseVariableIdentifier());
+ paramTypes.push(parseTypeAnnotatableIdentifier());
if (!match('>')) {
expect(',');
}
}
expect('>');
@@ -6151,18 +6704,23 @@
));
}
function parseObjectType(allowStatic) {
var callProperties = [], indexers = [], marker, optional = false,
- properties = [], property, propertyKey, propertyTypeAnnotation,
- token, isStatic;
+ properties = [], propertyKey, propertyTypeAnnotation,
+ token, isStatic, matchStatic;
expect('{');
while (!match('}')) {
marker = markerCreate();
- if (allowStatic && matchContextualKeyword('static')) {
+ matchStatic =
+ strict
+ ? matchKeyword('static')
+ : matchContextualKeyword('static');
+
+ if (allowStatic && matchStatic) {
token = lex();
isStatic = true;
}
if (match('[')) {
@@ -6210,13 +6768,12 @@
callProperties
);
}
function parseGenericType() {
- var marker = markerCreate(), returnType = null,
- typeParameters = null, typeIdentifier,
- typeIdentifierMarker = markerCreate;
+ var marker = markerCreate(),
+ typeParameters = null, typeIdentifier;
typeIdentifier = parseVariableIdentifier();
while (match('.')) {
expect('.');
@@ -6302,11 +6859,11 @@
// The parsing of types roughly parallels the parsing of expressions, and
// primary types are kind of like primary expressions...they're the
// primitives with which other types are constructed.
function parsePrimaryType() {
- var typeIdentifier = null, params = null, returnType = null,
+ var params = null, returnType = null,
marker = markerCreate(), rest = null, tmp,
typeParameters, token, type, isGroupedType = false;
switch (lookahead.type) {
case Token.Identifier:
@@ -6538,20 +7095,21 @@
if (match(':')) {
id.typeAnnotation = parseTypeAnnotation();
markerApply(typeAnnotationMarker, id);
}
} else {
+ /* istanbul ignore next */
id = state.allowKeyword ? parseNonComputedProperty() : parseTypeAnnotatableIdentifier();
// 12.2.1
if (strict && isRestrictedWord(id.name)) {
throwErrorTolerant({}, Messages.StrictVarName);
}
}
if (kind === 'const') {
if (!match('=')) {
- throwError({}, Messages.NoUnintializedConst);
+ throwError({}, Messages.NoUninitializedConst);
}
expect('=');
init = parseAssignmentExpression();
} else if (match('=')) {
lex();
@@ -6639,11 +7197,12 @@
return markerApply(marker, delegate.createExportSpecifier(id, name));
}
function parseExportDeclaration() {
- var backtrackToken, id, previousAllowKeyword, declaration = null,
+ var declaration = null,
+ possibleIdentifierToken, sourceElement,
isExportFromIdentifier,
src = null, specifiers = [],
marker = markerCreate();
expectKeyword('export');
@@ -6651,24 +7210,21 @@
if (matchKeyword('default')) {
// covers:
// export default ...
lex();
if (matchKeyword('function') || matchKeyword('class')) {
- backtrackToken = lookahead;
- lex();
- if (isIdentifierName(lookahead)) {
+ possibleIdentifierToken = lookahead2();
+ if (isIdentifierName(possibleIdentifierToken)) {
// covers:
// export default function foo () {}
// export default class foo {}
- id = parseNonComputedProperty();
- rewind(backtrackToken);
- return markerApply(marker, delegate.createExportDeclaration(true, parseSourceElement(), [id], null));
+ sourceElement = parseSourceElement();
+ return markerApply(marker, delegate.createExportDeclaration(true, sourceElement, [sourceElement.id], null));
}
// covers:
// export default function () {}
// export default class {}
- rewind(backtrackToken);
switch (lookahead.value) {
case 'class':
return markerApply(marker, delegate.createExportDeclaration(true, parseClassExpression(), [], null));
case 'function':
return markerApply(marker, delegate.createExportDeclaration(true, parseFunctionExpression(), [], null));
@@ -6692,14 +7248,15 @@
consumeSemicolon();
return markerApply(marker, delegate.createExportDeclaration(true, declaration, [], null));
}
// non-default export
- if (lookahead.type === Token.Keyword) {
+ if (lookahead.type === Token.Keyword || matchContextualKeyword('type')) {
// covers:
// export var f = 1;
switch (lookahead.value) {
+ case 'type':
case 'let':
case 'const':
case 'var':
case 'class':
case 'function':
@@ -6722,14 +7279,16 @@
return markerApply(marker, delegate.createExportDeclaration(false, null, specifiers, src));
}
expect('{');
- do {
- isExportFromIdentifier = isExportFromIdentifier || matchKeyword('default');
- specifiers.push(parseExportSpecifier());
- } while (match(',') && lex());
+ if (!match('}')) {
+ do {
+ isExportFromIdentifier = isExportFromIdentifier || matchKeyword('default');
+ specifiers.push(parseExportSpecifier());
+ } while (match(',') && lex());
+ }
expect('}');
if (matchContextualKeyword('from')) {
// covering:
// export {default} from "foo";
@@ -6766,13 +7325,15 @@
function parseNamedImports() {
var specifiers = [];
// {foo, bar as bas}
expect('{');
- do {
- specifiers.push(parseImportSpecifier());
- } while (match(',') && lex());
+ if (!match('}')) {
+ do {
+ specifiers.push(parseImportSpecifier());
+ } while (match(',') && lex());
+ }
expect('}');
return specifiers;
}
function parseImportDefaultSpecifier() {
@@ -6797,21 +7358,32 @@
return markerApply(marker, delegate.createImportNamespaceSpecifier(id));
}
function parseImportDeclaration() {
- var specifiers, src, marker = markerCreate();
+ var specifiers, src, marker = markerCreate(), isType = false, token2;
expectKeyword('import');
+
+ if (matchContextualKeyword('type')) {
+ token2 = lookahead2();
+ if ((token2.type === Token.Identifier && token2.value !== 'from') ||
+ (token2.type === Token.Punctuator &&
+ (token2.value === '{' || token2.value === '*'))) {
+ isType = true;
+ lex();
+ }
+ }
+
specifiers = [];
if (lookahead.type === Token.StringLiteral) {
// covers:
// import "foo";
src = parseModuleSpecifier();
consumeSemicolon();
- return markerApply(marker, delegate.createImportDeclaration(specifiers, src));
+ return markerApply(marker, delegate.createImportDeclaration(specifiers, src, isType));
}
if (!matchKeyword('default') && isIdentifierName(lookahead)) {
// covers:
// import foo
@@ -6839,11 +7411,11 @@
}
lex();
src = parseModuleSpecifier();
consumeSemicolon();
- return markerApply(marker, delegate.createImportDeclaration(specifiers, src));
+ return markerApply(marker, delegate.createImportDeclaration(specifiers, src, isType));
}
// 12.3 Empty Statement
function parseEmptyStatement() {
@@ -7036,11 +7608,11 @@
}
// 12.7 The continue statement
function parseContinueStatement() {
- var label = null, key, marker = markerCreate();
+ var label = null, marker = markerCreate();
expectKeyword('continue');
// Optimize the most common form: 'continue;'.
if (source.charCodeAt(index) === 59) {
@@ -7062,12 +7634,11 @@
}
if (lookahead.type === Token.Identifier) {
label = parseVariableIdentifier();
- key = '$' + label.name;
- if (!Object.prototype.hasOwnProperty.call(state.labelSet, key)) {
+ if (!state.labelSet.has(label.name)) {
throwError({}, Messages.UnknownLabel, label.name);
}
}
consumeSemicolon();
@@ -7080,11 +7651,11 @@
}
// 12.8 The break statement
function parseBreakStatement() {
- var label = null, key, marker = markerCreate();
+ var label = null, marker = markerCreate();
expectKeyword('break');
// Catch the very common case first: immediately a semicolon (char #59).
if (source.charCodeAt(index) === 59) {
@@ -7106,12 +7677,11 @@
}
if (lookahead.type === Token.Identifier) {
label = parseVariableIdentifier();
- key = '$' + label.name;
- if (!Object.prototype.hasOwnProperty.call(state.labelSet, key)) {
+ if (!state.labelSet.has(label.name)) {
throwError({}, Messages.UnknownLabel, label.name);
}
}
consumeSemicolon();
@@ -7335,12 +7905,11 @@
function parseStatement() {
var type = lookahead.type,
marker,
expr,
- labeledBody,
- key;
+ labeledBody;
if (type === Token.EOF) {
throwUnexpected(lookahead);
}
@@ -7403,18 +7972,17 @@
// 12.12 Labelled Statements
if ((expr.type === Syntax.Identifier) && match(':')) {
lex();
- key = '$' + expr.name;
- if (Object.prototype.hasOwnProperty.call(state.labelSet, key)) {
+ if (state.labelSet.has(expr.name)) {
throwError({}, Messages.Redeclaration, 'Label', expr.name);
}
- state.labelSet[key] = true;
+ state.labelSet.set(expr.name, true);
labeledBody = parseStatement();
- delete state.labelSet[key];
+ state.labelSet["delete"](expr.name);
return markerApply(marker, delegate.createLabeledStatement(expr, labeledBody));
}
consumeSemicolon();
@@ -7466,11 +8034,11 @@
oldInIteration = state.inIteration;
oldInSwitch = state.inSwitch;
oldInFunctionBody = state.inFunctionBody;
oldParenthesizedCount = state.parenthesizedCount;
- state.labelSet = {};
+ state.labelSet = new StringMap();
state.inIteration = false;
state.inSwitch = false;
state.inFunctionBody = true;
state.parenthesizedCount = 0;
@@ -7495,33 +8063,32 @@
return markerApply(marker, delegate.createBlockStatement(sourceElements));
}
function validateParam(options, param, name) {
- var key = '$' + name;
if (strict) {
if (isRestrictedWord(name)) {
options.stricted = param;
options.message = Messages.StrictParamName;
}
- if (Object.prototype.hasOwnProperty.call(options.paramSet, key)) {
+ if (options.paramSet.has(name)) {
options.stricted = param;
options.message = Messages.StrictParamDupe;
}
} else if (!options.firstRestricted) {
if (isRestrictedWord(name)) {
options.firstRestricted = param;
options.message = Messages.StrictParamName;
} else if (isStrictModeReservedWord(name)) {
options.firstRestricted = param;
options.message = Messages.StrictReservedWord;
- } else if (Object.prototype.hasOwnProperty.call(options.paramSet, key)) {
+ } else if (options.paramSet.has(name)) {
options.firstRestricted = param;
options.message = Messages.StrictParamDupe;
}
}
- options.paramSet[key] = true;
+ options.paramSet.set(name, true);
}
function parseParam(options) {
var marker, token, rest, param, def;
@@ -7599,11 +8166,11 @@
};
expect('(');
if (!match(')')) {
- options.paramSet = {};
+ options.paramSet = new StringMap();
while (index < length) {
if (!parseParam(options)) {
break;
}
expect(',');
@@ -7812,84 +8379,60 @@
expectContextualKeyword('await');
expr = parseAssignmentExpression();
return markerApply(marker, delegate.createAwaitExpression(expr));
}
- // 14 Classes
+ // 14 Functions and classes
- function parseMethodDefinition(existingPropNames, key, isStatic, generator, computed) {
- var token, param, propType, isValidDuplicateProp = false,
- isAsync, typeParameters, tokenValue, returnType,
- annotationMarker;
+ // 14.1 Functions is defined above (13 in ES5)
+ // 14.2 Arrow Functions Definitions is defined in (7.3 assignments)
+ // 14.3 Method Definitions
+ // 14.3.7
+ function specialMethod(methodDefinition) {
+ return methodDefinition.kind === 'get' ||
+ methodDefinition.kind === 'set' ||
+ methodDefinition.value.generator;
+ }
+
+ function parseMethodDefinition(key, isStatic, generator, computed) {
+ var token, param, propType,
+ isAsync, typeParameters, tokenValue, returnType;
+
propType = isStatic ? ClassPropertyType["static"] : ClassPropertyType.prototype;
if (generator) {
return delegate.createMethodDefinition(
propType,
'',
key,
- parsePropertyMethodFunction({ generator: true })
+ parsePropertyMethodFunction({ generator: true }),
+ computed
);
}
tokenValue = key.type === 'Identifier' && key.name;
if (tokenValue === 'get' && !match('(')) {
key = parseObjectPropertyKey();
- // It is a syntax error if any other properties have a name
- // duplicating this one unless they are a setter
- if (existingPropNames[propType].hasOwnProperty(key.name)) {
- isValidDuplicateProp =
- // There isn't already a getter for this prop
- existingPropNames[propType][key.name].get === undefined
- // There isn't already a data prop by this name
- && existingPropNames[propType][key.name].data === undefined
- // The only existing prop by this name is a setter
- && existingPropNames[propType][key.name].set !== undefined;
- if (!isValidDuplicateProp) {
- throwError(key, Messages.IllegalDuplicateClassProperty);
- }
- } else {
- existingPropNames[propType][key.name] = {};
- }
- existingPropNames[propType][key.name].get = true;
-
expect('(');
expect(')');
if (match(':')) {
returnType = parseTypeAnnotation();
}
return delegate.createMethodDefinition(
propType,
'get',
key,
- parsePropertyFunction({ generator: false, returnType: returnType })
+ parsePropertyFunction({ generator: false, returnType: returnType }),
+ computed
);
}
if (tokenValue === 'set' && !match('(')) {
key = parseObjectPropertyKey();
- // It is a syntax error if any other properties have a name
- // duplicating this one unless they are a getter
- if (existingPropNames[propType].hasOwnProperty(key.name)) {
- isValidDuplicateProp =
- // There isn't already a setter for this prop
- existingPropNames[propType][key.name].set === undefined
- // There isn't already a data prop by this name
- && existingPropNames[propType][key.name].data === undefined
- // The only existing prop by this name is a getter
- && existingPropNames[propType][key.name].get !== undefined;
- if (!isValidDuplicateProp) {
- throwError(key, Messages.IllegalDuplicateClassProperty);
- }
- } else {
- existingPropNames[propType][key.name] = {};
- }
- existingPropNames[propType][key.name].set = true;
-
expect('(');
token = lookahead;
param = [ parseTypeAnnotatableIdentifier() ];
expect(')');
if (match(':')) {
@@ -7902,11 +8445,12 @@
parsePropertyFunction({
params: param,
generator: false,
name: token,
returnType: returnType
- })
+ }),
+ computed
);
}
if (match('<')) {
typeParameters = parseTypeParameterDeclaration();
@@ -7915,32 +8459,24 @@
isAsync = tokenValue === 'async' && !match('(');
if (isAsync) {
key = parseObjectPropertyKey();
}
- // It is a syntax error if any other properties have the same name as a
- // non-getter, non-setter method
- if (existingPropNames[propType].hasOwnProperty(key.name)) {
- throwError(key, Messages.IllegalDuplicateClassProperty);
- } else {
- existingPropNames[propType][key.name] = {};
- }
- existingPropNames[propType][key.name].data = true;
-
return delegate.createMethodDefinition(
propType,
'',
key,
parsePropertyMethodFunction({
generator: false,
async: isAsync,
typeParameters: typeParameters
- })
+ }),
+ computed
);
}
- function parseClassProperty(existingPropNames, key, computed, isStatic) {
+ function parseClassProperty(key, computed, isStatic) {
var typeAnnotation;
typeAnnotation = parseTypeAnnotation();
expect(';');
@@ -7950,16 +8486,16 @@
computed,
isStatic
);
}
- function parseClassElement(existingProps) {
- var computed, generator = false, key, marker = markerCreate(),
- isStatic = false;
+ function parseClassElement() {
+ var computed = false, generator = false, key, marker = markerCreate(),
+ isStatic = false, possiblyOpenBracketToken;
if (match(';')) {
lex();
- return;
+ return undefined;
}
if (lookahead.value === 'static') {
lex();
isStatic = true;
@@ -7968,31 +8504,40 @@
if (match('*')) {
lex();
generator = true;
}
- computed = (lookahead.value === '[');
+ possiblyOpenBracketToken = lookahead;
+ if (matchContextualKeyword('get') || matchContextualKeyword('set')) {
+ possiblyOpenBracketToken = lookahead2();
+ }
+
+ if (possiblyOpenBracketToken.type === Token.Punctuator
+ && possiblyOpenBracketToken.value === '[') {
+ computed = true;
+ }
+
key = parseObjectPropertyKey();
if (!generator && lookahead.value === ':') {
- return markerApply(marker, parseClassProperty(existingProps, key, computed, isStatic));
+ return markerApply(marker, parseClassProperty(key, computed, isStatic));
}
return markerApply(marker, parseMethodDefinition(
- existingProps,
key,
isStatic,
generator,
computed
));
}
function parseClassBody() {
- var classElement, classElements = [], existingProps = {}, marker = markerCreate();
+ var classElement, classElements = [], existingProps = {},
+ marker = markerCreate(), propName, propType;
- existingProps[ClassPropertyType["static"]] = {};
- existingProps[ClassPropertyType.prototype] = {};
+ existingProps[ClassPropertyType["static"]] = new StringMap();
+ existingProps[ClassPropertyType.prototype] = new StringMap();
expect('{');
while (index < length) {
if (match('}')) {
@@ -8000,21 +8545,44 @@
}
classElement = parseClassElement(existingProps);
if (typeof classElement !== 'undefined') {
classElements.push(classElement);
+
+ propName = !classElement.computed && getFieldName(classElement.key);
+ if (propName !== false) {
+ propType = classElement["static"] ?
+ ClassPropertyType["static"] :
+ ClassPropertyType.prototype;
+
+ if (classElement.type === Syntax.MethodDefinition) {
+ if (propName === 'constructor' && !classElement["static"]) {
+ if (specialMethod(classElement)) {
+ throwError(classElement, Messages.IllegalClassConstructorProperty);
+ }
+ if (existingProps[ClassPropertyType.prototype].has('constructor')) {
+ throwError(classElement.key, Messages.IllegalDuplicateClassProperty);
+ }
+ }
+ existingProps[propType].set(propName, true);
+ }
+ }
}
}
expect('}');
return markerApply(marker, delegate.createClassBody(classElements));
}
function parseClassImplements() {
var id, implemented = [], marker, typeParameters;
- expectContextualKeyword('implements');
+ if (strict) {
+ expectKeyword('implements');
+ } else {
+ expectContextualKeyword('implements');
+ }
while (index < length) {
marker = markerCreate();
id = parseVariableIdentifier();
if (match('<')) {
typeParameters = parseTypeParameterInstantiation();
@@ -8033,15 +8601,21 @@
return implemented;
}
function parseClassExpression() {
var id, implemented, previousYieldAllowed, superClass = null,
- superTypeParameters, marker = markerCreate(), typeParameters;
+ superTypeParameters, marker = markerCreate(), typeParameters,
+ matchImplements;
expectKeyword('class');
- if (!matchKeyword('extends') && !matchContextualKeyword('implements') && !match('{')) {
+ matchImplements =
+ strict
+ ? matchKeyword('implements')
+ : matchContextualKeyword('implements');
+
+ if (!matchKeyword('extends') && !matchImplements && !match('{')) {
id = parseVariableIdentifier();
}
if (match('<')) {
typeParameters = parseTypeParameterDeclaration();
@@ -8056,11 +8630,11 @@
superTypeParameters = parseTypeParameterInstantiation();
}
state.yieldAllowed = previousYieldAllowed;
}
- if (matchContextualKeyword('implements')) {
+ if (strict ? matchKeyword('implements') : matchContextualKeyword('implements')) {
implemented = parseClassImplements();
}
return markerApply(marker, delegate.createClassExpression(
id,
@@ -8093,11 +8667,11 @@
superTypeParameters = parseTypeParameterInstantiation();
}
state.yieldAllowed = previousYieldAllowed;
}
- if (matchContextualKeyword('implements')) {
+ if (strict ? matchKeyword('implements') : matchContextualKeyword('implements')) {
implemented = parseClassImplements();
}
return markerApply(marker, delegate.createClassDeclaration(
id,
@@ -8118,10 +8692,21 @@
case 'const':
case 'let':
return parseConstLetDeclaration(lookahead.value);
case 'function':
return parseFunctionDeclaration();
+ case 'export':
+ throwErrorTolerant({}, Messages.IllegalExportDeclaration);
+ return parseExportDeclaration();
+ case 'import':
+ throwErrorTolerant({}, Messages.IllegalImportDeclaration);
+ return parseImportDeclaration();
+ case 'interface':
+ if (lookahead2().type === Token.Identifier) {
+ return parseInterface();
+ }
+ return parseStatement();
default:
return parseStatement();
}
}
@@ -8156,11 +8741,13 @@
return parseStatement();
}
}
function parseProgramElement() {
- if (lookahead.type === Token.Keyword) {
+ var isModule = extra.sourceType === 'module' || extra.sourceType === 'nonStrictModule';
+
+ if (isModule && lookahead.type === Token.Keyword) {
switch (lookahead.value) {
case 'export':
return parseExportDeclaration();
case 'import':
return parseImportDeclaration();
@@ -8208,175 +8795,18 @@
return sourceElements;
}
function parseProgram() {
var body, marker = markerCreate();
- strict = false;
+ strict = extra.sourceType === 'module';
peek();
body = parseProgramElements();
return markerApply(marker, delegate.createProgram(body));
}
- // The following functions are needed only when the option to preserve
- // the comments is active.
+ // 16 JSX
- function addComment(type, value, start, end, loc) {
- var comment;
-
- assert(typeof start === 'number', 'Comment must have valid position');
-
- // Because the way the actual token is scanned, often the comments
- // (if any) are skipped twice during the lexical analysis.
- // Thus, we need to skip adding a comment if the comment array already
- // handled it.
- if (state.lastCommentStart >= start) {
- return;
- }
- state.lastCommentStart = start;
-
- comment = {
- type: type,
- value: value
- };
- if (extra.range) {
- comment.range = [start, end];
- }
- if (extra.loc) {
- comment.loc = loc;
- }
- extra.comments.push(comment);
- if (extra.attachComment) {
- extra.leadingComments.push(comment);
- extra.trailingComments.push(comment);
- }
- }
-
- function scanComment() {
- var comment, ch, loc, start, blockComment, lineComment;
-
- comment = '';
- blockComment = false;
- lineComment = false;
-
- while (index < length) {
- ch = source[index];
-
- if (lineComment) {
- ch = source[index++];
- if (isLineTerminator(ch.charCodeAt(0))) {
- loc.end = {
- line: lineNumber,
- column: index - lineStart - 1
- };
- lineComment = false;
- addComment('Line', comment, start, index - 1, loc);
- if (ch === '\r' && source[index] === '\n') {
- ++index;
- }
- ++lineNumber;
- lineStart = index;
- comment = '';
- } else if (index >= length) {
- lineComment = false;
- comment += ch;
- loc.end = {
- line: lineNumber,
- column: length - lineStart
- };
- addComment('Line', comment, start, length, loc);
- } else {
- comment += ch;
- }
- } else if (blockComment) {
- if (isLineTerminator(ch.charCodeAt(0))) {
- if (ch === '\r') {
- ++index;
- comment += '\r';
- }
- if (ch !== '\r' || source[index] === '\n') {
- comment += source[index];
- ++lineNumber;
- ++index;
- lineStart = index;
- if (index >= length) {
- throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
- }
- }
- } else {
- ch = source[index++];
- if (index >= length) {
- throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
- }
- comment += ch;
- if (ch === '*') {
- ch = source[index];
- if (ch === '/') {
- comment = comment.substr(0, comment.length - 1);
- blockComment = false;
- ++index;
- loc.end = {
- line: lineNumber,
- column: index - lineStart
- };
- addComment('Block', comment, start, index, loc);
- comment = '';
- }
- }
- }
- } else if (ch === '/') {
- ch = source[index + 1];
- if (ch === '/') {
- loc = {
- start: {
- line: lineNumber,
- column: index - lineStart
- }
- };
- start = index;
- index += 2;
- lineComment = true;
- if (index >= length) {
- loc.end = {
- line: lineNumber,
- column: index - lineStart
- };
- lineComment = false;
- addComment('Line', comment, start, index, loc);
- }
- } else if (ch === '*') {
- start = index;
- index += 2;
- blockComment = true;
- loc = {
- start: {
- line: lineNumber,
- column: index - lineStart - 2
- }
- };
- if (index >= length) {
- throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
- }
- } else {
- break;
- }
- } else if (isWhiteSpace(ch.charCodeAt(0))) {
- ++index;
- } else if (isLineTerminator(ch.charCodeAt(0))) {
- ++index;
- if (ch === '\r' && source[index] === '\n') {
- ++index;
- }
- ++lineNumber;
- lineStart = index;
- } else {
- break;
- }
- }
- }
-
- // 16 XJS
-
XHTMLEntities = {
quot: '\u0022',
amp: '&',
apos: '\u0027',
lt: '<',
@@ -8629,57 +9059,60 @@
clubs: '\u2663',
hearts: '\u2665',
diams: '\u2666'
};
- function getQualifiedXJSName(object) {
- if (object.type === Syntax.XJSIdentifier) {
+ function getQualifiedJSXName(object) {
+ if (object.type === Syntax.JSXIdentifier) {
return object.name;
}
- if (object.type === Syntax.XJSNamespacedName) {
+ if (object.type === Syntax.JSXNamespacedName) {
return object.namespace.name + ':' + object.name.name;
}
- if (object.type === Syntax.XJSMemberExpression) {
+ /* istanbul ignore else */
+ if (object.type === Syntax.JSXMemberExpression) {
return (
- getQualifiedXJSName(object.object) + '.' +
- getQualifiedXJSName(object.property)
+ getQualifiedJSXName(object.object) + '.' +
+ getQualifiedJSXName(object.property)
);
}
+ /* istanbul ignore next */
+ throwUnexpected(object);
}
- function isXJSIdentifierStart(ch) {
+ function isJSXIdentifierStart(ch) {
// exclude backslash (\)
return (ch !== 92) && isIdentifierStart(ch);
}
- function isXJSIdentifierPart(ch) {
+ function isJSXIdentifierPart(ch) {
// exclude backslash (\) and add hyphen (-)
return (ch !== 92) && (ch === 45 || isIdentifierPart(ch));
}
- function scanXJSIdentifier() {
+ function scanJSXIdentifier() {
var ch, start, value = '';
start = index;
while (index < length) {
ch = source.charCodeAt(index);
- if (!isXJSIdentifierPart(ch)) {
+ if (!isJSXIdentifierPart(ch)) {
break;
}
value += source[index++];
}
return {
- type: Token.XJSIdentifier,
+ type: Token.JSXIdentifier,
value: value,
lineNumber: lineNumber,
lineStart: lineStart,
range: [start, index]
};
}
- function scanXJSEntity() {
+ function scanJSXEntity() {
var ch, str = '', start = index, count = 0, code;
ch = source[index];
assert(ch === '&', 'Entity must start with an ampersand');
index++;
while (index < length && count++ < 10) {
@@ -8702,30 +9135,31 @@
}
if (!isNaN(code)) {
return String.fromCharCode(code);
}
+ /* istanbul ignore else */
} else if (XHTMLEntities[str]) {
return XHTMLEntities[str];
}
}
// Treat non-entity sequences as regular text.
index = start + 1;
return '&';
}
- function scanXJSText(stopChars) {
+ function scanJSXText(stopChars) {
var ch, str = '', start;
start = index;
while (index < length) {
ch = source[index];
if (stopChars.indexOf(ch) !== -1) {
break;
}
if (ch === '&') {
- str += scanXJSEntity();
+ str += scanJSXEntity();
} else {
index++;
if (ch === '\r' && source[index] === '\n') {
str += ch;
ch = source[index];
@@ -8737,29 +9171,29 @@
}
str += ch;
}
}
return {
- type: Token.XJSText,
+ type: Token.JSXText,
value: str,
lineNumber: lineNumber,
lineStart: lineStart,
range: [start, index]
};
}
- function scanXJSStringLiteral() {
+ function scanJSXStringLiteral() {
var innerToken, quote, start;
quote = source[index];
assert((quote === '\'' || quote === '"'),
'String literal must starts with a quote');
start = index;
++index;
- innerToken = scanXJSText([quote]);
+ innerToken = scanJSXText([quote]);
if (quote !== source[index]) {
throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
}
@@ -8769,275 +9203,277 @@
return innerToken;
}
/**
- * Between XJS opening and closing tags (e.g. <foo>HERE</foo>), anything that
- * is not another XJS tag and is not an expression wrapped by {} is text.
+ * Between JSX opening and closing tags (e.g. <foo>HERE</foo>), anything that
+ * is not another JSX tag and is not an expression wrapped by {} is text.
*/
- function advanceXJSChild() {
+ function advanceJSXChild() {
var ch = source.charCodeAt(index);
- // { (123) and < (60)
- if (ch !== 123 && ch !== 60) {
- return scanXJSText(['<', '{']);
+ // '<' 60, '>' 62, '{' 123, '}' 125
+ if (ch !== 60 && ch !== 62 && ch !== 123 && ch !== 125) {
+ return scanJSXText(['<', '>', '{', '}']);
}
return scanPunctuator();
}
- function parseXJSIdentifier() {
+ function parseJSXIdentifier() {
var token, marker = markerCreate();
- if (lookahead.type !== Token.XJSIdentifier) {
+ if (lookahead.type !== Token.JSXIdentifier) {
throwUnexpected(lookahead);
}
token = lex();
- return markerApply(marker, delegate.createXJSIdentifier(token.value));
+ return markerApply(marker, delegate.createJSXIdentifier(token.value));
}
- function parseXJSNamespacedName() {
+ function parseJSXNamespacedName() {
var namespace, name, marker = markerCreate();
- namespace = parseXJSIdentifier();
+ namespace = parseJSXIdentifier();
expect(':');
- name = parseXJSIdentifier();
+ name = parseJSXIdentifier();
- return markerApply(marker, delegate.createXJSNamespacedName(namespace, name));
+ return markerApply(marker, delegate.createJSXNamespacedName(namespace, name));
}
- function parseXJSMemberExpression() {
+ function parseJSXMemberExpression() {
var marker = markerCreate(),
- expr = parseXJSIdentifier();
+ expr = parseJSXIdentifier();
while (match('.')) {
lex();
- expr = markerApply(marker, delegate.createXJSMemberExpression(expr, parseXJSIdentifier()));
+ expr = markerApply(marker, delegate.createJSXMemberExpression(expr, parseJSXIdentifier()));
}
return expr;
}
- function parseXJSElementName() {
+ function parseJSXElementName() {
if (lookahead2().value === ':') {
- return parseXJSNamespacedName();
+ return parseJSXNamespacedName();
}
if (lookahead2().value === '.') {
- return parseXJSMemberExpression();
+ return parseJSXMemberExpression();
}
- return parseXJSIdentifier();
+ return parseJSXIdentifier();
}
- function parseXJSAttributeName() {
+ function parseJSXAttributeName() {
if (lookahead2().value === ':') {
- return parseXJSNamespacedName();
+ return parseJSXNamespacedName();
}
- return parseXJSIdentifier();
+ return parseJSXIdentifier();
}
- function parseXJSAttributeValue() {
+ function parseJSXAttributeValue() {
var value, marker;
if (match('{')) {
- value = parseXJSExpressionContainer();
- if (value.expression.type === Syntax.XJSEmptyExpression) {
+ value = parseJSXExpressionContainer();
+ if (value.expression.type === Syntax.JSXEmptyExpression) {
throwError(
value,
- 'XJS attributes must only be assigned a non-empty ' +
+ 'JSX attributes must only be assigned a non-empty ' +
'expression'
);
}
} else if (match('<')) {
- value = parseXJSElement();
- } else if (lookahead.type === Token.XJSText) {
+ value = parseJSXElement();
+ } else if (lookahead.type === Token.JSXText) {
marker = markerCreate();
value = markerApply(marker, delegate.createLiteral(lex()));
} else {
- throwError({}, Messages.InvalidXJSAttributeValue);
+ throwError({}, Messages.InvalidJSXAttributeValue);
}
return value;
}
- function parseXJSEmptyExpression() {
+ function parseJSXEmptyExpression() {
var marker = markerCreatePreserveWhitespace();
while (source.charAt(index) !== '}') {
index++;
}
- return markerApply(marker, delegate.createXJSEmptyExpression());
+ return markerApply(marker, delegate.createJSXEmptyExpression());
}
- function parseXJSExpressionContainer() {
- var expression, origInXJSChild, origInXJSTag, marker = markerCreate();
+ function parseJSXExpressionContainer() {
+ var expression, origInJSXChild, origInJSXTag, marker = markerCreate();
- origInXJSChild = state.inXJSChild;
- origInXJSTag = state.inXJSTag;
- state.inXJSChild = false;
- state.inXJSTag = false;
+ origInJSXChild = state.inJSXChild;
+ origInJSXTag = state.inJSXTag;
+ state.inJSXChild = false;
+ state.inJSXTag = false;
expect('{');
if (match('}')) {
- expression = parseXJSEmptyExpression();
+ expression = parseJSXEmptyExpression();
} else {
expression = parseExpression();
}
- state.inXJSChild = origInXJSChild;
- state.inXJSTag = origInXJSTag;
+ state.inJSXChild = origInJSXChild;
+ state.inJSXTag = origInJSXTag;
expect('}');
- return markerApply(marker, delegate.createXJSExpressionContainer(expression));
+ return markerApply(marker, delegate.createJSXExpressionContainer(expression));
}
- function parseXJSSpreadAttribute() {
- var expression, origInXJSChild, origInXJSTag, marker = markerCreate();
+ function parseJSXSpreadAttribute() {
+ var expression, origInJSXChild, origInJSXTag, marker = markerCreate();
- origInXJSChild = state.inXJSChild;
- origInXJSTag = state.inXJSTag;
- state.inXJSChild = false;
- state.inXJSTag = false;
+ origInJSXChild = state.inJSXChild;
+ origInJSXTag = state.inJSXTag;
+ state.inJSXChild = false;
+ state.inJSXTag = false;
expect('{');
expect('...');
expression = parseAssignmentExpression();
- state.inXJSChild = origInXJSChild;
- state.inXJSTag = origInXJSTag;
+ state.inJSXChild = origInJSXChild;
+ state.inJSXTag = origInJSXTag;
expect('}');
- return markerApply(marker, delegate.createXJSSpreadAttribute(expression));
+ return markerApply(marker, delegate.createJSXSpreadAttribute(expression));
}
- function parseXJSAttribute() {
+ function parseJSXAttribute() {
var name, marker;
if (match('{')) {
- return parseXJSSpreadAttribute();
+ return parseJSXSpreadAttribute();
}
marker = markerCreate();
- name = parseXJSAttributeName();
+ name = parseJSXAttributeName();
// HTML empty attribute
if (match('=')) {
lex();
- return markerApply(marker, delegate.createXJSAttribute(name, parseXJSAttributeValue()));
+ return markerApply(marker, delegate.createJSXAttribute(name, parseJSXAttributeValue()));
}
- return markerApply(marker, delegate.createXJSAttribute(name));
+ return markerApply(marker, delegate.createJSXAttribute(name));
}
- function parseXJSChild() {
+ function parseJSXChild() {
var token, marker;
if (match('{')) {
- token = parseXJSExpressionContainer();
- } else if (lookahead.type === Token.XJSText) {
+ token = parseJSXExpressionContainer();
+ } else if (lookahead.type === Token.JSXText) {
marker = markerCreatePreserveWhitespace();
token = markerApply(marker, delegate.createLiteral(lex()));
+ } else if (match('<')) {
+ token = parseJSXElement();
} else {
- token = parseXJSElement();
+ throwUnexpected(lookahead);
}
return token;
}
- function parseXJSClosingElement() {
- var name, origInXJSChild, origInXJSTag, marker = markerCreate();
- origInXJSChild = state.inXJSChild;
- origInXJSTag = state.inXJSTag;
- state.inXJSChild = false;
- state.inXJSTag = true;
+ function parseJSXClosingElement() {
+ var name, origInJSXChild, origInJSXTag, marker = markerCreate();
+ origInJSXChild = state.inJSXChild;
+ origInJSXTag = state.inJSXTag;
+ state.inJSXChild = false;
+ state.inJSXTag = true;
expect('<');
expect('/');
- name = parseXJSElementName();
+ name = parseJSXElementName();
// Because advance() (called by lex() called by expect()) expects there
// to be a valid token after >, it needs to know whether to look for a
- // standard JS token or an XJS text node
- state.inXJSChild = origInXJSChild;
- state.inXJSTag = origInXJSTag;
+ // standard JS token or an JSX text node
+ state.inJSXChild = origInJSXChild;
+ state.inJSXTag = origInJSXTag;
expect('>');
- return markerApply(marker, delegate.createXJSClosingElement(name));
+ return markerApply(marker, delegate.createJSXClosingElement(name));
}
- function parseXJSOpeningElement() {
- var name, attribute, attributes = [], selfClosing = false, origInXJSChild, origInXJSTag, marker = markerCreate();
+ function parseJSXOpeningElement() {
+ var name, attributes = [], selfClosing = false, origInJSXChild, origInJSXTag, marker = markerCreate();
- origInXJSChild = state.inXJSChild;
- origInXJSTag = state.inXJSTag;
- state.inXJSChild = false;
- state.inXJSTag = true;
+ origInJSXChild = state.inJSXChild;
+ origInJSXTag = state.inJSXTag;
+ state.inJSXChild = false;
+ state.inJSXTag = true;
expect('<');
- name = parseXJSElementName();
+ name = parseJSXElementName();
while (index < length &&
lookahead.value !== '/' &&
lookahead.value !== '>') {
- attributes.push(parseXJSAttribute());
+ attributes.push(parseJSXAttribute());
}
- state.inXJSTag = origInXJSTag;
+ state.inJSXTag = origInJSXTag;
if (lookahead.value === '/') {
expect('/');
// Because advance() (called by lex() called by expect()) expects
// there to be a valid token after >, it needs to know whether to
- // look for a standard JS token or an XJS text node
- state.inXJSChild = origInXJSChild;
+ // look for a standard JS token or an JSX text node
+ state.inJSXChild = origInJSXChild;
expect('>');
selfClosing = true;
} else {
- state.inXJSChild = true;
+ state.inJSXChild = true;
expect('>');
}
- return markerApply(marker, delegate.createXJSOpeningElement(name, attributes, selfClosing));
+ return markerApply(marker, delegate.createJSXOpeningElement(name, attributes, selfClosing));
}
- function parseXJSElement() {
- var openingElement, closingElement = null, children = [], origInXJSChild, origInXJSTag, marker = markerCreate();
+ function parseJSXElement() {
+ var openingElement, closingElement = null, children = [], origInJSXChild, origInJSXTag, marker = markerCreate();
- origInXJSChild = state.inXJSChild;
- origInXJSTag = state.inXJSTag;
- openingElement = parseXJSOpeningElement();
+ origInJSXChild = state.inJSXChild;
+ origInJSXTag = state.inJSXTag;
+ openingElement = parseJSXOpeningElement();
if (!openingElement.selfClosing) {
while (index < length) {
- state.inXJSChild = false; // Call lookahead2() with inXJSChild = false because </ should not be considered in the child
+ state.inJSXChild = false; // Call lookahead2() with inJSXChild = false because </ should not be considered in the child
if (lookahead.value === '<' && lookahead2().value === '/') {
break;
}
- state.inXJSChild = true;
- children.push(parseXJSChild());
+ state.inJSXChild = true;
+ children.push(parseJSXChild());
}
- state.inXJSChild = origInXJSChild;
- state.inXJSTag = origInXJSTag;
- closingElement = parseXJSClosingElement();
- if (getQualifiedXJSName(closingElement.name) !== getQualifiedXJSName(openingElement.name)) {
- throwError({}, Messages.ExpectedXJSClosingTag, getQualifiedXJSName(openingElement.name));
+ state.inJSXChild = origInJSXChild;
+ state.inJSXTag = origInJSXTag;
+ closingElement = parseJSXClosingElement();
+ if (getQualifiedJSXName(closingElement.name) !== getQualifiedJSXName(openingElement.name)) {
+ throwError({}, Messages.ExpectedJSXClosingTag, getQualifiedJSXName(openingElement.name));
}
}
// When (erroneously) writing two adjacent tags like
//
// var x = <div>one</div><div>two</div>;
//
// the default error message is a bit incomprehensible. Since it's
- // rarely (never?) useful to write a less-than sign after an XJS
+ // rarely (never?) useful to write a less-than sign after an JSX
// element, we disallow it here in the parser in order to provide a
// better error message. (In the rare case that the less-than operator
// was intended, the left tag can be wrapped in parentheses.)
- if (!origInXJSChild && match('<')) {
- throwError(lookahead, Messages.AdjacentXJSElements);
+ if (!origInJSXChild && match('<')) {
+ throwError(lookahead, Messages.AdjacentJSXElements);
}
- return markerApply(marker, delegate.createXJSElement(openingElement, closingElement, children));
+ return markerApply(marker, delegate.createJSXElement(openingElement, closingElement, children));
}
function parseTypeAlias() {
var id, marker = markerCreate(), typeParameters = null, right;
expectContextualKeyword('type');
@@ -9096,14 +9532,18 @@
extended
));
}
function parseInterface() {
- var body, bodyMarker, extended = [], id, marker = markerCreate(),
- typeParameters = null;
+ var marker = markerCreate();
- expectContextualKeyword('interface');
+ if (strict) {
+ expectKeyword('interface');
+ } else {
+ expectContextualKeyword('interface');
+ }
+
return parseInterfaceish(marker, /* allowStatic */false);
}
function parseDeclareClass() {
var marker = markerCreate(), ret;
@@ -9210,17 +9650,17 @@
markerApply(bodyMarker, delegate.createBlockStatement(body))
));
}
function collectToken() {
- var start, loc, token, range, value, entry;
+ var loc, token, range, value, entry;
- if (!state.inXJSChild) {
+ /* istanbul ignore else */
+ if (!state.inJSXChild) {
skipComment();
}
- start = index;
loc = {
start: {
line: lineNumber,
column: index - lineStart
}
@@ -9271,10 +9711,11 @@
line: lineNumber,
column: index - lineStart
};
if (!extra.tokenize) {
+ /* istanbul ignore next */
// Pop the previous token, which is likely '/' or '/='
if (extra.tokens.length > 0) {
token = extra.tokens[extra.tokens.length - 1];
if (token.range[0] === pos && token.type === 'Punctuator') {
if (token.value === '/' || token.value === '/=') {
@@ -9321,29 +9762,20 @@
extra.tokens = tokens;
}
function patch() {
- if (extra.comments) {
- extra.skipComment = skipComment;
- skipComment = scanComment;
- }
-
if (typeof extra.tokens !== 'undefined') {
extra.advance = advance;
extra.scanRegExp = scanRegExp;
advance = collectToken;
scanRegExp = collectRegex;
}
}
function unpatch() {
- if (typeof extra.skipComment === 'function') {
- skipComment = extra.skipComment;
- }
-
if (typeof extra.scanRegExp === 'function') {
advance = extra.advance;
scanRegExp = extra.scanRegExp;
}
}
@@ -9352,16 +9784,18 @@
function extend(object, properties) {
var entry, result = {};
for (entry in object) {
+ /* istanbul ignore else */
if (object.hasOwnProperty(entry)) {
result[entry] = object[entry];
}
}
for (entry in properties) {
+ /* istanbul ignore else */
if (properties.hasOwnProperty(entry)) {
result[entry] = properties[entry];
}
}
@@ -9386,11 +9820,11 @@
length = source.length;
lookahead = null;
state = {
allowKeyword: true,
allowIn: true,
- labelSet: {},
+ labelSet: new StringMap(),
inFunctionBody: false,
inIteration: false,
inSwitch: false,
lastCommentStart: -1
};
@@ -9416,21 +9850,10 @@
}
if (typeof options.tolerant === 'boolean' && options.tolerant) {
extra.errors = [];
}
- if (length > 0) {
- if (typeof source[0] === 'undefined') {
- // Try first to convert to a string. This is good as fast path
- // for old IE which understands string indexing for string
- // literals only and not for string object.
- if (code instanceof String) {
- source = code.valueOf();
- }
- }
- }
-
patch();
try {
peek();
if (lookahead.type === Token.EOF) {
@@ -9487,17 +9910,17 @@
length = source.length;
lookahead = null;
state = {
allowKeyword: false,
allowIn: true,
- labelSet: {},
+ labelSet: new StringMap(),
parenthesizedCount: 0,
inFunctionBody: false,
inIteration: false,
inSwitch: false,
- inXJSChild: false,
- inXJSTag: false,
+ inJSXChild: false,
+ inJSXTag: false,
inType: false,
lastCommentStart: -1,
yieldAllowed: false,
awaitAllowed: false
};
@@ -9515,10 +9938,11 @@
return node;
}
});
}
+ extra.sourceType = options.sourceType;
if (typeof options.tokens === 'boolean' && options.tokens) {
extra.tokens = [];
}
if (typeof options.comment === 'boolean' && options.comment) {
extra.comments = [];
@@ -9533,21 +9957,10 @@
extra.trailingComments = [];
extra.leadingComments = [];
}
}
- if (length > 0) {
- if (typeof source[0] === 'undefined') {
- // Try first to convert to a string. This is good as fast path
- // for old IE which understands string indexing for string
- // literals only and not for string object.
- if (code instanceof String) {
- source = code.valueOf();
- }
- }
- }
-
patch();
try {
program = parseProgram();
if (typeof extra.comments !== 'undefined') {
program.comments = extra.comments;
@@ -9568,17 +9981,18 @@
return program;
}
// Sync with *.json manifests.
- exports.version = '8001.1001.0-dev-harmony-fb';
+ exports.version = '13001.1001.0-dev-harmony-fb';
exports.tokenize = tokenize;
exports.parse = parse;
// Deep copy.
+ /* istanbul ignore next */
exports.Syntax = (function () {
var name, types = {};
if (typeof Object.create === 'function') {
types = Object.create(null);
@@ -9599,20 +10013,48 @@
}));
/* vim: set sw=4 ts=4 et tw=80 : */
},{}],10:[function(_dereq_,module,exports){
+var Base62 = (function (my) {
+ 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"]
+
+ my.encode = function(i){
+ if (i === 0) {return '0'}
+ var s = ''
+ while (i > 0) {
+ s = this.chars[i % 62] + s
+ i = Math.floor(i/62)
+ }
+ return s
+ };
+ my.decode = function(a,b,c,d){
+ for (
+ b = c = (
+ a === (/\W|_|^$/.test(a += "") || a)
+ ) - 1;
+ d = a.charCodeAt(c++);
+ )
+ b = b * 62 + d - [, 48, 29, 87][d >> 5];
+ return b
+ };
+
+ return my;
+}({}));
+
+module.exports = Base62
+},{}],11:[function(_dereq_,module,exports){
/*
* Copyright 2009-2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE.txt or:
* http://opensource.org/licenses/BSD-3-Clause
*/
exports.SourceMapGenerator = _dereq_('./source-map/source-map-generator').SourceMapGenerator;
exports.SourceMapConsumer = _dereq_('./source-map/source-map-consumer').SourceMapConsumer;
exports.SourceNode = _dereq_('./source-map/source-node').SourceNode;
-},{"./source-map/source-map-consumer":15,"./source-map/source-map-generator":16,"./source-map/source-node":17}],11:[function(_dereq_,module,exports){
+},{"./source-map/source-map-consumer":16,"./source-map/source-map-generator":17,"./source-map/source-node":18}],12:[function(_dereq_,module,exports){
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* Copyright 2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE or:
* http://opensource.org/licenses/BSD-3-Clause
@@ -9707,11 +10149,11 @@
exports.ArraySet = ArraySet;
});
-},{"./util":18,"amdefine":19}],12:[function(_dereq_,module,exports){
+},{"./util":19,"amdefine":20}],13:[function(_dereq_,module,exports){
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* Copyright 2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE or:
* http://opensource.org/licenses/BSD-3-Clause
@@ -9853,11 +10295,11 @@
};
};
});
-},{"./base64":13,"amdefine":19}],13:[function(_dereq_,module,exports){
+},{"./base64":14,"amdefine":20}],14:[function(_dereq_,module,exports){
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* Copyright 2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE or:
* http://opensource.org/licenses/BSD-3-Clause
@@ -9897,11 +10339,11 @@
throw new TypeError("Not a valid base 64 digit: " + aChar);
};
});
-},{"amdefine":19}],14:[function(_dereq_,module,exports){
+},{"amdefine":20}],15:[function(_dereq_,module,exports){
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* Copyright 2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE or:
* http://opensource.org/licenses/BSD-3-Clause
@@ -9980,11 +10422,11 @@
: null;
};
});
-},{"amdefine":19}],15:[function(_dereq_,module,exports){
+},{"amdefine":20}],16:[function(_dereq_,module,exports){
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* Copyright 2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE or:
* http://opensource.org/licenses/BSD-3-Clause
@@ -10459,11 +10901,11 @@
exports.SourceMapConsumer = SourceMapConsumer;
});
-},{"./array-set":11,"./base64-vlq":12,"./binary-search":14,"./util":18,"amdefine":19}],16:[function(_dereq_,module,exports){
+},{"./array-set":12,"./base64-vlq":13,"./binary-search":15,"./util":19,"amdefine":20}],17:[function(_dereq_,module,exports){
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* Copyright 2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE or:
* http://opensource.org/licenses/BSD-3-Clause
@@ -10841,11 +11283,11 @@
exports.SourceMapGenerator = SourceMapGenerator;
});
-},{"./array-set":11,"./base64-vlq":12,"./util":18,"amdefine":19}],17:[function(_dereq_,module,exports){
+},{"./array-set":12,"./base64-vlq":13,"./util":19,"amdefine":20}],18:[function(_dereq_,module,exports){
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* Copyright 2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE or:
* http://opensource.org/licenses/BSD-3-Clause
@@ -11214,11 +11656,11 @@
exports.SourceNode = SourceNode;
});
-},{"./source-map-generator":16,"./util":18,"amdefine":19}],18:[function(_dereq_,module,exports){
+},{"./source-map-generator":17,"./util":19,"amdefine":20}],19:[function(_dereq_,module,exports){
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* Copyright 2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE or:
* http://opensource.org/licenses/BSD-3-Clause
@@ -11421,11 +11863,11 @@
};
exports.compareByGeneratedPositions = compareByGeneratedPositions;
});
-},{"amdefine":19}],19:[function(_dereq_,module,exports){
+},{"amdefine":20}],20:[function(_dereq_,module,exports){
(function (process,__filename){
/** vim: et:ts=4:sw=4:sts=4
* @license amdefine 0.1.0 Copyright (c) 2011, The Dojo Foundation All Rights Reserved.
* Available via the MIT or new BSD license.
* see: http://github.com/jrburke/amdefine for details
@@ -11724,11 +12166,11 @@
}
module.exports = amdefine;
}).call(this,_dereq_('_process'),"/node_modules/jstransform/node_modules/source-map/node_modules/amdefine/amdefine.js")
-},{"_process":7,"path":6}],20:[function(_dereq_,module,exports){
+},{"_process":8,"path":7}],21:[function(_dereq_,module,exports){
/**
* Copyright 2013 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -11812,11 +12254,11 @@
exports.extract = extract;
exports.parse = parse;
exports.parseAsObject = parseAsObject;
-},{}],21:[function(_dereq_,module,exports){
+},{}],22:[function(_dereq_,module,exports){
/**
* Copyright 2013 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -11856,11 +12298,16 @@
var parentIsFunction =
parentNode.type === Syntax.FunctionDeclaration
|| parentNode.type === Syntax.FunctionExpression
|| parentNode.type === Syntax.ArrowFunctionExpression;
- return node.type === Syntax.BlockStatement && parentIsFunction;
+ var parentIsCurlylessArrowFunc =
+ parentNode.type === Syntax.ArrowFunctionExpression
+ && node === parentNode.body;
+
+ return parentIsFunction
+ && (node.type === Syntax.BlockStatement || parentIsCurlylessArrowFunc);
}
function _nodeIsBlockScopeBoundary(node, parentNode) {
if (node.type === Syntax.Program) {
return false;
@@ -11874,33 +12321,42 @@
* @param {object} node
* @param {array} path
* @param {object} state
*/
function traverse(node, path, state) {
+ /*jshint -W004*/
// Create a scope stack entry if this is the first node we've encountered in
// its local scope
+ var startIndex = null;
var parentNode = path[0];
if (!Array.isArray(node) && state.localScope.parentNode !== parentNode) {
if (_nodeIsClosureScopeBoundary(node, parentNode)) {
- var scopeIsStrict =
- state.scopeIsStrict
- || node.body.length > 0
- && node.body[0].type === Syntax.ExpressionStatement
- && node.body[0].expression.type === Syntax.Literal
- && node.body[0].expression.value === 'use strict';
+ var scopeIsStrict = state.scopeIsStrict;
+ if (!scopeIsStrict
+ && (node.type === Syntax.BlockStatement
+ || node.type === Syntax.Program)) {
+ scopeIsStrict =
+ node.body.length > 0
+ && node.body[0].type === Syntax.ExpressionStatement
+ && node.body[0].expression.type === Syntax.Literal
+ && node.body[0].expression.value === 'use strict';
+ }
if (node.type === Syntax.Program) {
+ startIndex = state.g.buffer.length;
state = utils.updateState(state, {
scopeIsStrict: scopeIsStrict
});
} else {
+ startIndex = state.g.buffer.length + 1;
state = utils.updateState(state, {
localScope: {
parentNode: parentNode,
parentScope: state.localScope,
identifiers: {},
- tempVarIndex: 0
+ tempVarIndex: 0,
+ tempVars: []
},
scopeIsStrict: scopeIsStrict
});
// All functions have an implicit 'arguments' object in scope
@@ -11908,20 +12364,30 @@
// Include function arg identifiers in the scope boundaries of the
// function
if (parentNode.params.length > 0) {
var param;
+ var metadata = initScopeMetadata(parentNode, path.slice(1), path[0]);
for (var i = 0; i < parentNode.params.length; i++) {
param = parentNode.params[i];
if (param.type === Syntax.Identifier) {
- declareIdentInScope(
- param.name, initScopeMetadata(parentNode), state
- );
+ declareIdentInScope(param.name, metadata, state);
}
}
}
+ // Include rest arg identifiers in the scope boundaries of their
+ // functions
+ if (parentNode.rest) {
+ var metadata = initScopeMetadata(
+ parentNode,
+ path.slice(1),
+ path[0]
+ );
+ declareIdentInScope(parentNode.rest.name, metadata, state);
+ }
+
// Named FunctionExpressions scope their name within the body block of
// themselves only
if (parentNode.type === Syntax.FunctionExpression && parentNode.id) {
var metaData =
initScopeMetadata(parentNode, path.parentNodeslice, parentNode);
@@ -11933,22 +12399,28 @@
// account for function/variable declaration hoisting
collectClosureIdentsAndTraverse(node, path, state);
}
if (_nodeIsBlockScopeBoundary(node, parentNode)) {
+ startIndex = state.g.buffer.length;
state = utils.updateState(state, {
localScope: {
parentNode: parentNode,
parentScope: state.localScope,
- identifiers: {}
+ identifiers: {},
+ tempVarIndex: 0,
+ tempVars: []
}
});
if (parentNode.type === Syntax.CatchClause) {
- declareIdentInScope(
- parentNode.param.name, initScopeMetadata(parentNode), state
+ var metadata = initScopeMetadata(
+ parentNode,
+ path.slice(1),
+ parentNode
);
+ declareIdentInScope(parentNode.param.name, metadata, state);
}
collectBlockIdentsAndTraverse(node, path, state);
}
}
@@ -11958,10 +12430,15 @@
traverse(node, path, state);
node.range && utils.catchup(node.range[1], state);
}
utils.analyzeAndTraverse(walker, traverser, node, path, state);
+
+ // Inject temp variables into the scope.
+ if (startIndex !== null) {
+ utils.injectTempVarDeclarations(state, startIndex);
+ }
}
function collectClosureIdentsAndTraverse(node, path, state) {
utils.analyzeAndTraverse(
visitLocalClosureIdentifiers,
@@ -11983,10 +12460,11 @@
}
function visitLocalClosureIdentifiers(node, path, state) {
var metaData;
switch (node.type) {
+ case Syntax.ArrowFunctionExpression:
case Syntax.FunctionExpression:
// Function expressions don't get their names (if there is one) added to
// the closure scope they're defined in
return false;
case Syntax.ClassDeclaration:
@@ -12023,10 +12501,26 @@
}
}
var _astCache = {};
+function getAstForSource(source, options) {
+ if (_astCache[source] && !options.disableAstCache) {
+ return _astCache[source];
+ }
+ var ast = esprima.parse(source, {
+ comment: true,
+ loc: true,
+ range: true,
+ sourceType: options.sourceType
+ });
+ if (!options.disableAstCache) {
+ _astCache[source] = ast;
+ }
+ return ast;
+}
+
/**
* Applies all available transformations to the source
* @param {array} visitors
* @param {string} source
* @param {?object} options
@@ -12034,17 +12528,11 @@
*/
function transform(visitors, source, options) {
options = options || {};
var ast;
try {
- var cachedAst = _astCache[source];
- ast = cachedAst ||
- (_astCache[source] = esprima.parse(source, {
- comment: true,
- loc: true,
- range: true
- }));
+ ast = getAstForSource(source, options);
} catch (e) {
e.message = 'Parse Error: ' + e.message;
throw e;
}
var state = utils.createState(source, ast, options);
@@ -12067,11 +12555,11 @@
}
exports.transform = transform;
exports.Syntax = Syntax;
-},{"./utils":22,"esprima-fb":9,"source-map":10}],22:[function(_dereq_,module,exports){
+},{"./utils":23,"esprima-fb":9,"source-map":11}],23:[function(_dereq_,module,exports){
/**
* Copyright 2013 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -12112,11 +12600,12 @@
*/
localScope: {
parentNode: rootNode,
parentScope: null,
identifiers: {},
- tempVarIndex: 0
+ tempVarIndex: 0,
+ tempVars: []
},
/**
* The name (and, if applicable, expression) of the super class
* @type {Object}
*/
@@ -12329,33 +12818,91 @@
*/
function getNodeSourceText(node, state) {
return state.g.source.substring(node.range[0], node.range[1]);
}
-function replaceNonWhite(value) {
+function _replaceNonWhite(value) {
return value.replace(nonWhiteRegexp, ' ');
}
/**
* Removes all non-whitespace characters
*/
-function stripNonWhite(value) {
+function _stripNonWhite(value) {
return value.replace(nonWhiteRegexp, '');
}
/**
+ * Finds the position of the next instance of the specified syntactic char in
+ * the pending source.
+ *
+ * NOTE: This will skip instances of the specified char if they sit inside a
+ * comment body.
+ *
+ * NOTE: This function also assumes that the buffer's current position is not
+ * already within a comment or a string. This is rarely the case since all
+ * of the buffer-advancement utility methods tend to be used on syntactic
+ * nodes' range values -- but it's a small gotcha that's worth mentioning.
+ */
+function getNextSyntacticCharOffset(char, state) {
+ var pendingSource = state.g.source.substring(state.g.position);
+ var pendingSourceLines = pendingSource.split('\n');
+
+ var charOffset = 0;
+ var line;
+ var withinBlockComment = false;
+ var withinString = false;
+ lineLoop: while ((line = pendingSourceLines.shift()) !== undefined) {
+ var lineEndPos = charOffset + line.length;
+ charLoop: for (; charOffset < lineEndPos; charOffset++) {
+ var currChar = pendingSource[charOffset];
+ if (currChar === '"' || currChar === '\'') {
+ withinString = !withinString;
+ continue charLoop;
+ } else if (withinString) {
+ continue charLoop;
+ } else if (charOffset + 1 < lineEndPos) {
+ var nextTwoChars = currChar + line[charOffset + 1];
+ if (nextTwoChars === '//') {
+ charOffset = lineEndPos + 1;
+ continue lineLoop;
+ } else if (nextTwoChars === '/*') {
+ withinBlockComment = true;
+ charOffset += 1;
+ continue charLoop;
+ } else if (nextTwoChars === '*/') {
+ withinBlockComment = false;
+ charOffset += 1;
+ continue charLoop;
+ }
+ }
+
+ if (!withinBlockComment && currChar === char) {
+ return charOffset + state.g.position;
+ }
+ }
+
+ // Account for '\n'
+ charOffset++;
+ withinString = false;
+ }
+
+ throw new Error('`' + char + '` not found!');
+}
+
+/**
* Catches up as `catchup` but replaces non-whitespace chars with spaces.
*/
function catchupWhiteOut(end, state) {
- catchup(end, state, replaceNonWhite);
+ catchup(end, state, _replaceNonWhite);
}
/**
* Catches up as `catchup` but removes all non-whitespace characters.
*/
function catchupWhiteSpace(end, state) {
- catchup(end, state, stripNonWhite);
+ catchup(end, state, _stripNonWhite);
}
/**
* Removes all non-newline characters
*/
@@ -12434,10 +12981,11 @@
* @param {string} str
* @param {object} state
* @return {string}
*/
function updateIndent(str, state) {
+ /*jshint -W004*/
var indentBy = state.indentBy;
if (indentBy < 0) {
for (var i = 0; i < -indentBy; i++) {
str = str.replace(leadingIndentRegexp, '$1');
}
@@ -12525,10 +13073,21 @@
state: Object.create(state)
};
}
function getLexicalBindingMetadata(identName, state) {
+ var currScope = state.localScope;
+ while (currScope) {
+ if (currScope.identifiers[identName] !== undefined) {
+ return currScope.identifiers[identName];
+ }
+
+ currScope = currScope.parentScope;
+ }
+}
+
+function getLocalBindingMetadata(identName, state) {
return state.localScope.identifiers[identName];
}
/**
* Apply the given analyzer function to the current node. If the analyzer
@@ -12640,10 +13199,11 @@
);
return foundMatchingChild;
}
var scopeTypes = {};
+scopeTypes[Syntax.ArrowFunctionExpression] = true;
scopeTypes[Syntax.FunctionExpression] = true;
scopeTypes[Syntax.FunctionDeclaration] = true;
scopeTypes[Syntax.Program] = true;
function getBoundaryNode(path) {
@@ -12660,41 +13220,56 @@
function getTempVar(tempVarIndex) {
return '$__' + tempVarIndex;
}
-function getTempVarWithValue(tempVarIndex, tempVarValue) {
- return getTempVar(tempVarIndex) + '=' + tempVarValue;
+function injectTempVar(state) {
+ var tempVar = '$__' + (state.localScope.tempVarIndex++);
+ state.localScope.tempVars.push(tempVar);
+ return tempVar;
}
+function injectTempVarDeclarations(state, index) {
+ if (state.localScope.tempVars.length) {
+ state.g.buffer =
+ state.g.buffer.slice(0, index) +
+ 'var ' + state.localScope.tempVars.join(', ') + ';' +
+ state.g.buffer.slice(index);
+ state.localScope.tempVars = [];
+ }
+}
+
+exports.analyzeAndTraverse = analyzeAndTraverse;
exports.append = append;
exports.catchup = catchup;
+exports.catchupNewlines = catchupNewlines;
exports.catchupWhiteOut = catchupWhiteOut;
exports.catchupWhiteSpace = catchupWhiteSpace;
-exports.catchupNewlines = catchupNewlines;
exports.containsChildMatching = containsChildMatching;
exports.containsChildOfType = containsChildOfType;
exports.createState = createState;
exports.declareIdentInLocalScope = declareIdentInLocalScope;
exports.getBoundaryNode = getBoundaryNode;
exports.getDocblock = getDocblock;
exports.getLexicalBindingMetadata = getLexicalBindingMetadata;
-exports.initScopeMetadata = initScopeMetadata;
-exports.identWithinLexicalScope = identWithinLexicalScope;
+exports.getLocalBindingMetadata = getLocalBindingMetadata;
+exports.getNextSyntacticCharOffset = getNextSyntacticCharOffset;
+exports.getNodeSourceText = getNodeSourceText;
+exports.getOrderedChildren = getOrderedChildren;
+exports.getTempVar = getTempVar;
exports.identInLocalScope = identInLocalScope;
+exports.identWithinLexicalScope = identWithinLexicalScope;
exports.indentBefore = indentBefore;
+exports.initScopeMetadata = initScopeMetadata;
+exports.injectTempVar = injectTempVar;
+exports.injectTempVarDeclarations = injectTempVarDeclarations;
exports.move = move;
exports.scopeTypes = scopeTypes;
exports.updateIndent = updateIndent;
exports.updateState = updateState;
-exports.analyzeAndTraverse = analyzeAndTraverse;
-exports.getOrderedChildren = getOrderedChildren;
-exports.getNodeSourceText = getNodeSourceText;
-exports.getTempVar = getTempVar;
-exports.getTempVarWithValue = getTempVarWithValue;
-},{"./docblock":20,"esprima-fb":9}],23:[function(_dereq_,module,exports){
+},{"./docblock":21,"esprima-fb":9}],24:[function(_dereq_,module,exports){
/**
* Copyright 2013 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -12850,12 +13425,121 @@
exports.visitorList = [
visitArrowFunction
];
-},{"../src/utils":22,"./es6-destructuring-visitors":25,"./es6-rest-param-visitors":28,"esprima-fb":9}],24:[function(_dereq_,module,exports){
+},{"../src/utils":23,"./es6-destructuring-visitors":27,"./es6-rest-param-visitors":30,"esprima-fb":9}],25:[function(_dereq_,module,exports){
/**
+ * Copyright 2004-present Facebook. All Rights Reserved.
+ */
+/*global exports:true*/
+
+/**
+ * Implements ES6 call spread.
+ *
+ * instance.method(a, b, c, ...d)
+ *
+ * instance.method.apply(instance, [a, b, c].concat(d))
+ *
+ */
+
+var Syntax = _dereq_('esprima-fb').Syntax;
+var utils = _dereq_('../src/utils');
+
+function process(traverse, node, path, state) {
+ utils.move(node.range[0], state);
+ traverse(node, path, state);
+ utils.catchup(node.range[1], state);
+}
+
+function visitCallSpread(traverse, node, path, state) {
+ utils.catchup(node.range[0], state);
+
+ if (node.type === Syntax.NewExpression) {
+ // Input = new Set(1, 2, ...list)
+ // Output = new (Function.prototype.bind.apply(Set, [null, 1, 2].concat(list)))
+ utils.append('new (Function.prototype.bind.apply(', state);
+ process(traverse, node.callee, path, state);
+ } else if (node.callee.type === Syntax.MemberExpression) {
+ // Input = get().fn(1, 2, ...more)
+ // Output = (_ = get()).fn.apply(_, [1, 2].apply(more))
+ var tempVar = utils.injectTempVar(state);
+ utils.append('(' + tempVar + ' = ', state);
+ process(traverse, node.callee.object, path, state);
+ utils.append(')', state);
+ if (node.callee.property.type === Syntax.Identifier) {
+ utils.append('.', state);
+ process(traverse, node.callee.property, path, state);
+ } else {
+ utils.append('[', state);
+ process(traverse, node.callee.property, path, state);
+ utils.append(']', state);
+ }
+ utils.append('.apply(' + tempVar, state);
+ } else {
+ // Input = max(1, 2, ...list)
+ // Output = max.apply(null, [1, 2].concat(list))
+ var needsToBeWrappedInParenthesis =
+ node.callee.type === Syntax.FunctionDeclaration ||
+ node.callee.type === Syntax.FunctionExpression;
+ if (needsToBeWrappedInParenthesis) {
+ utils.append('(', state);
+ }
+ process(traverse, node.callee, path, state);
+ if (needsToBeWrappedInParenthesis) {
+ utils.append(')', state);
+ }
+ utils.append('.apply(null', state);
+ }
+ utils.append(', ', state);
+
+ var args = node.arguments.slice();
+ var spread = args.pop();
+ if (args.length || node.type === Syntax.NewExpression) {
+ utils.append('[', state);
+ if (node.type === Syntax.NewExpression) {
+ utils.append('null' + (args.length ? ', ' : ''), state);
+ }
+ while (args.length) {
+ var arg = args.shift();
+ utils.move(arg.range[0], state);
+ traverse(arg, path, state);
+ if (args.length) {
+ utils.catchup(args[0].range[0], state);
+ } else {
+ utils.catchup(arg.range[1], state);
+ }
+ }
+ utils.append('].concat(', state);
+ process(traverse, spread.argument, path, state);
+ utils.append(')', state);
+ } else {
+ process(traverse, spread.argument, path, state);
+ }
+ utils.append(node.type === Syntax.NewExpression ? '))' : ')', state);
+
+ utils.move(node.range[1], state);
+ return false;
+}
+
+visitCallSpread.test = function(node, path, state) {
+ return (
+ (
+ node.type === Syntax.CallExpression ||
+ node.type === Syntax.NewExpression
+ ) &&
+ node.arguments.length > 0 &&
+ node.arguments[node.arguments.length - 1].type === Syntax.SpreadElement
+ );
+};
+
+exports.visitorList = [
+ visitCallSpread
+];
+
+},{"../src/utils":23,"esprima-fb":9}],26:[function(_dereq_,module,exports){
+/**
* Copyright 2013 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
@@ -13034,10 +13718,11 @@
});
if (methodNode.key.name === 'constructor') {
utils.append('function ' + state.className, state);
} else {
+ var methodAccessorComputed = false;
var methodAccessor;
var prototypeOrStatic = methodNode["static"] ? '' : '.prototype';
var objectAccessor = state.className + prototypeOrStatic;
if (methodNode.key.type === Syntax.Identifier) {
@@ -13047,37 +13732,53 @@
methodAccessor = _getMungedName(methodAccessor, state);
}
if (isGetter || isSetter) {
methodAccessor = JSON.stringify(methodAccessor);
} else if (reservedWordsHelper.isReservedWord(methodAccessor)) {
- methodAccessor = '[' + JSON.stringify(methodAccessor) + ']';
- } else {
- methodAccessor = '.' + methodAccessor;
+ methodAccessorComputed = true;
+ methodAccessor = JSON.stringify(methodAccessor);
}
} else if (methodNode.key.type === Syntax.Literal) {
// 'foo bar'() {} | get 'foo bar'() {} | set 'foo bar'() {}
methodAccessor = JSON.stringify(methodNode.key.value);
- if (!(isGetter || isSetter)) {
- methodAccessor = '[' + methodAccessor + ']';
- }
+ methodAccessorComputed = true;
}
if (isSetter || isGetter) {
utils.append(
'Object.defineProperty(' +
objectAccessor + ',' +
methodAccessor + ',' +
- '{enumerable:true,configurable:true,' +
+ '{configurable:true,' +
methodNode.kind + ':function',
state
);
} else {
- utils.append(
- objectAccessor +
- methodAccessor + '=function' + (node.generator ? '*' : ''),
- state
- );
+ if (state.g.opts.es3) {
+ if (methodAccessorComputed) {
+ methodAccessor = '[' + methodAccessor + ']';
+ } else {
+ methodAccessor = '.' + methodAccessor;
+ }
+ utils.append(
+ objectAccessor +
+ methodAccessor + '=function' + (node.generator ? '*' : ''),
+ state
+ );
+ } else {
+ if (!methodAccessorComputed) {
+ methodAccessor = JSON.stringify(methodAccessor);
+ }
+ utils.append(
+ 'Object.defineProperty(' +
+ objectAccessor + ',' +
+ methodAccessor + ',' +
+ '{writable:true,configurable:true,' +
+ 'value:function' + (node.generator ? '*' : ''),
+ state
+ );
+ }
}
}
utils.move(methodNode.key.range[1], state);
utils.append('(', state);
@@ -13089,13 +13790,17 @@
path.unshift(node);
traverse(params[i], path, state);
path.shift();
}
}
- utils.append(')', state);
- utils.catchupWhiteSpace(node.body.range[0], state);
- utils.append('{', state);
+
+ var closingParenPosition = utils.getNextSyntacticCharOffset(')', state);
+ utils.catchupWhiteSpace(closingParenPosition, state);
+
+ var openingBracketPosition = utils.getNextSyntacticCharOffset('{', state);
+ utils.catchup(openingBracketPosition + 1, state);
+
if (!state.scopeIsStrict) {
utils.append('"use strict";', state);
state = utils.updateState(state, {
scopeIsStrict: true
});
@@ -13106,11 +13811,11 @@
traverse(node.body, path, state);
path.shift();
utils.catchup(node.body.range[1], state);
if (methodNode.key.name !== 'constructor') {
- if (isGetter || isSetter) {
+ if (isGetter || isSetter || !state.g.opts.es3) {
utils.append('})', state);
}
utils.append(';', state);
}
return false;
@@ -13419,11 +14124,11 @@
visitPrivateIdentifier,
visitSuperCallExpression,
visitSuperMemberExpression
];
-},{"../src/utils":22,"./reserved-words-helper":32,"base62":8,"esprima-fb":9}],25:[function(_dereq_,module,exports){
+},{"../src/utils":23,"./reserved-words-helper":34,"base62":10,"esprima-fb":9}],27:[function(_dereq_,module,exports){
/**
* Copyright 2014 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -13541,11 +14246,11 @@
// Simple pattern item.
components.push(value.name + '=' + accessor);
} else {
// Complex sub-structure.
components.push(
- utils.getTempVarWithValue(++state.localScope.tempVarIndex, accessor) +
+ utils.getTempVar(++state.localScope.tempVarIndex) + '=' + accessor +
',' + getDestructuredComponents(value, state)
);
}
}
@@ -13701,11 +14406,11 @@
];
exports.renderDestructuredComponents = renderDestructuredComponents;
-},{"../src/utils":22,"./es6-rest-param-visitors":28,"./es7-rest-property-helpers":30,"./reserved-words-helper":32,"esprima-fb":9}],26:[function(_dereq_,module,exports){
+},{"../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){
/**
* Copyright 2013 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -13772,11 +14477,11 @@
exports.visitorList = [
visitObjectConciseMethod
];
-},{"../src/utils":22,"./reserved-words-helper":32,"esprima-fb":9}],27:[function(_dereq_,module,exports){
+},{"../src/utils":23,"./reserved-words-helper":34,"esprima-fb":9}],29:[function(_dereq_,module,exports){
/**
* Copyright 2013 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -13827,11 +14532,11 @@
exports.visitorList = [
visitObjectLiteralShortNotation
];
-},{"../src/utils":22,"esprima-fb":9}],28:[function(_dereq_,module,exports){
+},{"../src/utils":23,"esprima-fb":9}],30:[function(_dereq_,module,exports){
/**
* Copyright 2013 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -13910,12 +14615,12 @@
function renderRestParamSetup(functionNode, state) {
var idx = state.localScope.tempVarIndex++;
var len = state.localScope.tempVarIndex++;
return 'for (var ' + functionNode.rest.name + '=[],' +
- utils.getTempVarWithValue(idx, functionNode.params.length) + ',' +
- utils.getTempVarWithValue(len, 'arguments.length') + ';' +
+ utils.getTempVar(idx) + '=' + functionNode.params.length + ',' +
+ utils.getTempVar(len) + '=arguments.length;' +
utils.getTempVar(idx) + '<' + utils.getTempVar(len) + ';' +
utils.getTempVar(idx) + '++) ' +
functionNode.rest.name + '.push(arguments[' + utils.getTempVar(idx) + ']);';
}
@@ -13935,11 +14640,11 @@
exports.visitorList = [
visitFunctionParamsWithRestParam,
visitFunctionBodyWithRestParam
];
-},{"../src/utils":22,"esprima-fb":9}],29:[function(_dereq_,module,exports){
+},{"../src/utils":23,"esprima-fb":9}],31:[function(_dereq_,module,exports){
/**
* Copyright 2013 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -14093,11 +14798,11 @@
exports.visitorList = [
visitTemplateLiteral,
visitTaggedTemplateExpression
];
-},{"../src/utils":22,"esprima-fb":9}],30:[function(_dereq_,module,exports){
+},{"../src/utils":23,"esprima-fb":9}],32:[function(_dereq_,module,exports){
/**
* Copyright 2013 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -14117,11 +14822,10 @@
/**
* Desugars ES7 rest properties into ES5 object iteration.
*/
var Syntax = _dereq_('esprima-fb').Syntax;
-var utils = _dereq_('../src/utils');
// TODO: This is a pretty massive helper, it should only be defined once, in the
// transform's runtime environment. We don't currently have a runtime though.
var restFunction =
'(function(source, exclusion) {' +
@@ -14176,11 +14880,11 @@
);
}
exports.renderRestExpression = renderRestExpression;
-},{"../src/utils":22,"esprima-fb":9}],31:[function(_dereq_,module,exports){
+},{"esprima-fb":9}],33:[function(_dereq_,module,exports){
/**
* Copyright 2004-present Facebook. All Rights Reserved.
*/
/*global exports:true*/
@@ -14286,11 +14990,11 @@
exports.visitorList = [
visitObjectLiteralSpread
];
-},{"../src/utils":22,"esprima-fb":9}],32:[function(_dereq_,module,exports){
+},{"../src/utils":23,"esprima-fb":9}],34:[function(_dereq_,module,exports){
/**
* Copyright 2014 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -14333,15 +15037,110 @@
var reservedWordsMap = Object.create(null);
RESERVED_WORDS.forEach(function(k) {
reservedWordsMap[k] = true;
});
+/**
+ * This list should not grow as new reserved words are introdued. This list is
+ * of words that need to be quoted because ES3-ish browsers do not allow their
+ * use as identifier names.
+ */
+var ES3_FUTURE_RESERVED_WORDS = [
+ 'enum', 'implements', 'package', 'protected', 'static', 'interface',
+ 'private', 'public'
+];
+
+var ES3_RESERVED_WORDS = [].concat(
+ KEYWORDS,
+ ES3_FUTURE_RESERVED_WORDS,
+ LITERALS
+);
+
+var es3ReservedWordsMap = Object.create(null);
+ES3_RESERVED_WORDS.forEach(function(k) {
+ es3ReservedWordsMap[k] = true;
+});
+
exports.isReservedWord = function(word) {
return !!reservedWordsMap[word];
};
-},{}],33:[function(_dereq_,module,exports){
+exports.isES3ReservedWord = function(word) {
+ return !!es3ReservedWordsMap[word];
+};
+
+},{}],35:[function(_dereq_,module,exports){
+/**
+ * Copyright 2014 Facebook, Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+/*global exports:true*/
+
+var Syntax = _dereq_('esprima-fb').Syntax;
+var utils = _dereq_('../src/utils');
+var reserverdWordsHelper = _dereq_('./reserved-words-helper');
+
+/**
+ * Code adapted from https://github.com/spicyj/es3ify
+ * The MIT License (MIT)
+ * Copyright (c) 2014 Ben Alpert
+ */
+
+function visitProperty(traverse, node, path, state) {
+ utils.catchup(node.key.range[0], state);
+ utils.append('"', state);
+ utils.catchup(node.key.range[1], state);
+ utils.append('"', state);
+ utils.catchup(node.value.range[0], state);
+ traverse(node.value, path, state);
+ return false;
+}
+
+visitProperty.test = function(node) {
+ return node.type === Syntax.Property &&
+ node.key.type === Syntax.Identifier &&
+ !node.method &&
+ !node.shorthand &&
+ !node.computed &&
+ reserverdWordsHelper.isES3ReservedWord(node.key.name);
+};
+
+function visitMemberExpression(traverse, node, path, state) {
+ traverse(node.object, path, state);
+ utils.catchup(node.property.range[0] - 1, state);
+ utils.append('[', state);
+ utils.catchupWhiteSpace(node.property.range[0], state);
+ utils.append('"', state);
+ utils.catchup(node.property.range[1], state);
+ utils.append('"]', state);
+ return false;
+}
+
+visitMemberExpression.test = function(node) {
+ return node.type === Syntax.MemberExpression &&
+ node.property.type === Syntax.Identifier &&
+ reserverdWordsHelper.isES3ReservedWord(node.property.name);
+};
+
+exports.visitorList = [
+ visitProperty,
+ visitMemberExpression
+];
+
+},{"../src/utils":23,"./reserved-words-helper":34,"esprima-fb":9}],36:[function(_dereq_,module,exports){
var esprima = _dereq_('esprima-fb');
var utils = _dereq_('../src/utils');
var Syntax = esprima.Syntax;
@@ -14366,10 +15165,23 @@
}
visitTypeAlias.test = function(node, path, state) {
return node.type === Syntax.TypeAlias;
};
+function visitTypeCast(traverse, node, path, state) {
+ path.unshift(node);
+ traverse(node.expression, path, state);
+ path.shift();
+
+ utils.catchup(node.typeAnnotation.range[0], state);
+ utils.catchupWhiteOut(node.typeAnnotation.range[1], state);
+ return false;
+}
+visitTypeCast.test = function(node, path, state) {
+ return node.type === Syntax.TypeCastExpression;
+};
+
function visitInterfaceDeclaration(traverse, node, path, state) {
utils.catchupWhiteOut(node.range[1], state);
return false;
}
visitInterfaceDeclaration.test = function(node, path, state) {
@@ -14380,17 +15192,18 @@
utils.catchupWhiteOut(node.range[1], state);
return false;
}
visitDeclare.test = function(node, path, state) {
switch (node.type) {
- case Syntax.DeclareVariable:
- case Syntax.DeclareFunction:
- case Syntax.DeclareClass:
- case Syntax.DeclareModule: return true
+ case Syntax.DeclareVariable:
+ case Syntax.DeclareFunction:
+ case Syntax.DeclareClass:
+ case Syntax.DeclareModule:
+ return true;
}
return false;
-}
+};
function visitFunctionParametricAnnotation(traverse, node, path, state) {
utils.catchup(node.range[0], state);
utils.catchupWhiteOut(node.range[1], state);
return false;
@@ -14473,45 +15286,168 @@
visitMethod.test = function(node, path, state) {
return (node.type === "Property" && (node.method || node.kind === "set" || node.kind === "get"))
|| (node.type === "MethodDefinition");
};
+function visitImportType(traverse, node, path, state) {
+ utils.catchupWhiteOut(node.range[1], state);
+ return false;
+}
+visitImportType.test = function(node, path, state) {
+ return node.type === 'ImportDeclaration'
+ && node.isType;
+};
+
exports.visitorList = [
visitClassProperty,
visitDeclare,
+ visitImportType,
visitInterfaceDeclaration,
visitFunctionParametricAnnotation,
visitFunctionReturnAnnotation,
visitMethod,
visitOptionalFunctionParameterAnnotation,
visitTypeAlias,
+ visitTypeCast,
visitTypeAnnotatedIdentifier,
visitTypeAnnotatedObjectOrArrayPattern
];
-},{"../src/utils":22,"esprima-fb":9}],34:[function(_dereq_,module,exports){
+},{"../src/utils":23,"esprima-fb":9}],37:[function(_dereq_,module,exports){
/**
- * Copyright 2013-2014, Facebook, Inc.
+ * Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
/*global exports:true*/
-"use strict";
+'use strict';
+var Syntax = _dereq_('jstransform').Syntax;
+var utils = _dereq_('jstransform/src/utils');
+function renderJSXLiteral(object, isLast, state, start, end) {
+ var lines = object.value.split(/\r\n|\n|\r/);
+
+ if (start) {
+ utils.append(start, state);
+ }
+
+ var lastNonEmptyLine = 0;
+
+ lines.forEach(function(line, index) {
+ if (line.match(/[^ \t]/)) {
+ lastNonEmptyLine = index;
+ }
+ });
+
+ lines.forEach(function(line, index) {
+ var isFirstLine = index === 0;
+ var isLastLine = index === lines.length - 1;
+ var isLastNonEmptyLine = index === lastNonEmptyLine;
+
+ // replace rendered whitespace tabs with spaces
+ var trimmedLine = line.replace(/\t/g, ' ');
+
+ // trim whitespace touching a newline
+ if (!isFirstLine) {
+ trimmedLine = trimmedLine.replace(/^[ ]+/, '');
+ }
+ if (!isLastLine) {
+ trimmedLine = trimmedLine.replace(/[ ]+$/, '');
+ }
+
+ if (!isFirstLine) {
+ utils.append(line.match(/^[ \t]*/)[0], state);
+ }
+
+ if (trimmedLine || isLastNonEmptyLine) {
+ utils.append(
+ JSON.stringify(trimmedLine) +
+ (!isLastNonEmptyLine ? ' + \' \' +' : ''),
+ state);
+
+ if (isLastNonEmptyLine) {
+ if (end) {
+ utils.append(end, state);
+ }
+ if (!isLast) {
+ utils.append(', ', state);
+ }
+ }
+
+ // only restore tail whitespace if line had literals
+ if (trimmedLine && !isLastLine) {
+ utils.append(line.match(/[ \t]*$/)[0], state);
+ }
+ }
+
+ if (!isLastLine) {
+ utils.append('\n', state);
+ }
+ });
+
+ utils.move(object.range[1], state);
+}
+
+function renderJSXExpressionContainer(traverse, object, isLast, path, state) {
+ // Plus 1 to skip `{`.
+ utils.move(object.range[0] + 1, state);
+ utils.catchup(object.expression.range[0], state);
+ traverse(object.expression, path, state);
+
+ if (!isLast && object.expression.type !== Syntax.JSXEmptyExpression) {
+ // If we need to append a comma, make sure to do so after the expression.
+ utils.catchup(object.expression.range[1], state, trimLeft);
+ utils.append(', ', state);
+ }
+
+ // Minus 1 to skip `}`.
+ utils.catchup(object.range[1] - 1, state, trimLeft);
+ utils.move(object.range[1], state);
+ return false;
+}
+
+function quoteAttrName(attr) {
+ // Quote invalid JS identifiers.
+ if (!/^[a-z_$][a-z\d_$]*$/i.test(attr)) {
+ return '"' + attr + '"';
+ }
+ return attr;
+}
+
+function trimLeft(value) {
+ return value.replace(/^[ ]+/, '');
+}
+
+exports.renderJSXExpressionContainer = renderJSXExpressionContainer;
+exports.renderJSXLiteral = renderJSXLiteral;
+exports.quoteAttrName = quoteAttrName;
+exports.trimLeft = trimLeft;
+
+},{"jstransform":22,"jstransform/src/utils":23}],38:[function(_dereq_,module,exports){
+/**
+ * Copyright 2013-2015, Facebook, Inc.
+ * All rights reserved.
+ *
+ * This source code is licensed under the BSD-style license found in the
+ * LICENSE file in the root directory of this source tree. An additional grant
+ * of patent rights can be found in the PATENTS file in the same directory.
+ */
+/*global exports:true*/
+'use strict';
+
var Syntax = _dereq_('jstransform').Syntax;
var utils = _dereq_('jstransform/src/utils');
-var FALLBACK_TAGS = _dereq_('./xjs').knownTags;
-var renderXJSExpressionContainer =
- _dereq_('./xjs').renderXJSExpressionContainer;
-var renderXJSLiteral = _dereq_('./xjs').renderXJSLiteral;
-var quoteAttrName = _dereq_('./xjs').quoteAttrName;
+var renderJSXExpressionContainer =
+ _dereq_('./jsx').renderJSXExpressionContainer;
+var renderJSXLiteral = _dereq_('./jsx').renderJSXLiteral;
+var quoteAttrName = _dereq_('./jsx').quoteAttrName;
-var trimLeft = _dereq_('./xjs').trimLeft;
+var trimLeft = _dereq_('./jsx').trimLeft;
/**
* Customized desugar processor for React JSX. Currently:
*
* <X> </X> => React.createElement(X, null)
@@ -14540,44 +15476,34 @@
var nameObject = openingElement.name;
var attributesObject = openingElement.attributes;
utils.catchup(openingElement.range[0], state, trimLeft);
- if (nameObject.type === Syntax.XJSNamespacedName && nameObject.namespace) {
+ if (nameObject.type === Syntax.JSXNamespacedName && nameObject.namespace) {
throw new Error('Namespace tags are not supported. ReactJSX is not XML.');
}
// We assume that the React runtime is already in scope
utils.append('React.createElement(', state);
- // Identifiers with lower case or hypthens are fallback tags (strings).
- // XJSMemberExpressions are not.
- if (nameObject.type === Syntax.XJSIdentifier && isTagName(nameObject.name)) {
- // This is a temporary error message to assist upgrades
- if (!FALLBACK_TAGS.hasOwnProperty(nameObject.name)) {
- throw new Error(
- 'Lower case component names (' + nameObject.name + ') are no longer ' +
- 'supported in JSX: See http://fb.me/react-jsx-lower-case'
- );
- }
-
+ if (nameObject.type === Syntax.JSXIdentifier && isTagName(nameObject.name)) {
utils.append('"' + nameObject.name + '"', state);
utils.move(nameObject.range[1], state);
} else {
// Use utils.catchup in this case so we can easily handle
- // XJSMemberExpressions which look like Foo.Bar.Baz. This also handles
- // XJSIdentifiers that aren't fallback tags.
+ // JSXMemberExpressions which look like Foo.Bar.Baz. This also handles
+ // JSXIdentifiers that aren't fallback tags.
utils.move(nameObject.range[0], state);
utils.catchup(nameObject.range[1], state);
}
utils.append(', ', state);
var hasAttributes = attributesObject.length;
var hasAtLeastOneSpreadProperty = attributesObject.some(function(attr) {
- return attr.type === Syntax.XJSSpreadAttribute;
+ return attr.type === Syntax.JSXSpreadAttribute;
});
// if we don't have any attributes, pass in null
if (hasAtLeastOneSpreadProperty) {
utils.append('React.__spread({', state);
@@ -14592,11 +15518,11 @@
// write attributes
attributesObject.forEach(function(attr, index) {
var isLast = index === attributesObject.length - 1;
- if (attr.type === Syntax.XJSSpreadAttribute) {
+ if (attr.type === Syntax.JSXSpreadAttribute) {
// Close the previous object or initial object
if (!previousWasSpread) {
utils.append('}, ', state);
}
@@ -14625,11 +15551,11 @@
return;
}
// If the next attribute is a spread, we're effective last in this object
if (!isLast) {
- isLast = attributesObject[index + 1].type === Syntax.XJSSpreadAttribute;
+ isLast = attributesObject[index + 1].type === Syntax.JSXSpreadAttribute;
}
if (attr.name.namespace) {
throw new Error(
'Namespace attributes are not supported. ReactJSX is not XML.');
@@ -14654,13 +15580,13 @@
} else {
utils.move(attr.name.range[1], state);
// Use catchupNewlines to skip over the '=' in the attribute
utils.catchupNewlines(attr.value.range[0], state);
if (attr.value.type === Syntax.Literal) {
- renderXJSLiteral(attr.value, isLast, state);
+ renderJSXLiteral(attr.value, isLast, state);
} else {
- renderXJSExpressionContainer(traverse, attr.value, isLast, path, state);
+ renderJSXExpressionContainer(traverse, attr.value, isLast, path, state);
}
}
utils.catchup(attr.range[1], state, trimLeft);
@@ -14689,12 +15615,12 @@
});
if (childrenToRender.length > 0) {
var lastRenderableIndex;
childrenToRender.forEach(function(child, index) {
- if (child.type !== Syntax.XJSExpressionContainer ||
- child.expression.type !== Syntax.XJSEmptyExpression) {
+ if (child.type !== Syntax.JSXExpressionContainer ||
+ child.expression.type !== Syntax.JSXEmptyExpression) {
lastRenderableIndex = index;
}
});
if (lastRenderableIndex !== undefined) {
@@ -14705,13 +15631,13 @@
utils.catchup(child.range[0], state, trimLeft);
var isLast = index >= lastRenderableIndex;
if (child.type === Syntax.Literal) {
- renderXJSLiteral(child, isLast, state);
- } else if (child.type === Syntax.XJSExpressionContainer) {
- renderXJSExpressionContainer(traverse, child, isLast, path, state);
+ renderJSXLiteral(child, isLast, state);
+ } else if (child.type === Syntax.JSXExpressionContainer) {
+ renderJSXExpressionContainer(traverse, child, isLast, path, state);
} else {
traverse(child, path, state);
if (!isLast) {
utils.append(', ', state);
}
@@ -14734,28 +15660,28 @@
utils.append(')', state);
return false;
}
visitReactTag.test = function(object, path, state) {
- return object.type === Syntax.XJSElement;
+ return object.type === Syntax.JSXElement;
};
exports.visitorList = [
visitReactTag
];
-},{"./xjs":36,"jstransform":21,"jstransform/src/utils":22}],35:[function(_dereq_,module,exports){
+},{"./jsx":37,"jstransform":22,"jstransform/src/utils":23}],39:[function(_dereq_,module,exports){
/**
- * Copyright 2013-2014, Facebook, Inc.
+ * Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
/*global exports:true*/
-"use strict";
+'use strict';
var Syntax = _dereq_('jstransform').Syntax;
var utils = _dereq_('jstransform/src/utils');
function addDisplayName(displayName, object, state) {
@@ -14764,23 +15690,23 @@
object.callee.type === Syntax.MemberExpression &&
object.callee.object.type === Syntax.Identifier &&
object.callee.object.name === 'React' &&
object.callee.property.type === Syntax.Identifier &&
object.callee.property.name === 'createClass' &&
- object['arguments'].length === 1 &&
- object['arguments'][0].type === Syntax.ObjectExpression) {
+ object.arguments.length === 1 &&
+ object.arguments[0].type === Syntax.ObjectExpression) {
// Verify that the displayName property isn't already set
- var properties = object['arguments'][0].properties;
+ var properties = object.arguments[0].properties;
var safe = properties.every(function(property) {
var value = property.key.type === Syntax.Identifier ?
property.key.name :
property.key.value;
return value !== 'displayName';
});
if (safe) {
- utils.catchup(object['arguments'][0].range[0] + 1, state);
+ utils.catchup(object.arguments[0].range[0] + 1, state);
utils.append('displayName: "' + displayName + '",', state);
}
}
}
@@ -14836,271 +15762,33 @@
exports.visitorList = [
visitReactDisplayName
];
-},{"jstransform":21,"jstransform/src/utils":22}],36:[function(_dereq_,module,exports){
-/**
- * Copyright 2013-2014, Facebook, Inc.
- * All rights reserved.
- *
- * This source code is licensed under the BSD-style license found in the
- * LICENSE file in the root directory of this source tree. An additional grant
- * of patent rights can be found in the PATENTS file in the same directory.
- */
+},{"jstransform":22,"jstransform/src/utils":23}],40:[function(_dereq_,module,exports){
/*global exports:true*/
-"use strict";
-var Syntax = _dereq_('jstransform').Syntax;
-var utils = _dereq_('jstransform/src/utils');
-var knownTags = {
- a: true,
- abbr: true,
- address: true,
- applet: true,
- area: true,
- article: true,
- aside: true,
- audio: true,
- b: true,
- base: true,
- bdi: true,
- bdo: true,
- big: true,
- blockquote: true,
- body: true,
- br: true,
- button: true,
- canvas: true,
- caption: true,
- circle: true,
- cite: true,
- code: true,
- col: true,
- colgroup: true,
- command: true,
- data: true,
- datalist: true,
- dd: true,
- defs: true,
- del: true,
- details: true,
- dfn: true,
- dialog: true,
- div: true,
- dl: true,
- dt: true,
- ellipse: true,
- em: true,
- embed: true,
- fieldset: true,
- figcaption: true,
- figure: true,
- footer: true,
- form: true,
- g: true,
- h1: true,
- h2: true,
- h3: true,
- h4: true,
- h5: true,
- h6: true,
- head: true,
- header: true,
- hgroup: true,
- hr: true,
- html: true,
- i: true,
- iframe: true,
- img: true,
- input: true,
- ins: true,
- kbd: true,
- keygen: true,
- label: true,
- legend: true,
- li: true,
- line: true,
- linearGradient: true,
- link: true,
- main: true,
- map: true,
- mark: true,
- marquee: true,
- mask: false,
- menu: true,
- menuitem: true,
- meta: true,
- meter: true,
- nav: true,
- noscript: true,
- object: true,
- ol: true,
- optgroup: true,
- option: true,
- output: true,
- p: true,
- param: true,
- path: true,
- pattern: false,
- picture: true,
- polygon: true,
- polyline: true,
- pre: true,
- progress: true,
- q: true,
- radialGradient: true,
- rect: true,
- rp: true,
- rt: true,
- ruby: true,
- s: true,
- samp: true,
- script: true,
- section: true,
- select: true,
- small: true,
- source: true,
- span: true,
- stop: true,
- strong: true,
- style: true,
- sub: true,
- summary: true,
- sup: true,
- svg: true,
- table: true,
- tbody: true,
- td: true,
- text: true,
- textarea: true,
- tfoot: true,
- th: true,
- thead: true,
- time: true,
- title: true,
- tr: true,
- track: true,
- tspan: true,
- u: true,
- ul: true,
- 'var': true,
- video: true,
- wbr: true
-};
+'use strict';
-function renderXJSLiteral(object, isLast, state, start, end) {
- var lines = object.value.split(/\r\n|\n|\r/);
-
- if (start) {
- utils.append(start, state);
- }
-
- var lastNonEmptyLine = 0;
-
- lines.forEach(function (line, index) {
- if (line.match(/[^ \t]/)) {
- lastNonEmptyLine = index;
- }
- });
-
- lines.forEach(function (line, index) {
- var isFirstLine = index === 0;
- var isLastLine = index === lines.length - 1;
- var isLastNonEmptyLine = index === lastNonEmptyLine;
-
- // replace rendered whitespace tabs with spaces
- var trimmedLine = line.replace(/\t/g, ' ');
-
- // trim whitespace touching a newline
- if (!isFirstLine) {
- trimmedLine = trimmedLine.replace(/^[ ]+/, '');
- }
- if (!isLastLine) {
- trimmedLine = trimmedLine.replace(/[ ]+$/, '');
- }
-
- if (!isFirstLine) {
- utils.append(line.match(/^[ \t]*/)[0], state);
- }
-
- if (trimmedLine || isLastNonEmptyLine) {
- utils.append(
- JSON.stringify(trimmedLine) +
- (!isLastNonEmptyLine ? " + ' ' +" : ''),
- state);
-
- if (isLastNonEmptyLine) {
- if (end) {
- utils.append(end, state);
- }
- if (!isLast) {
- utils.append(', ', state);
- }
- }
-
- // only restore tail whitespace if line had literals
- if (trimmedLine && !isLastLine) {
- utils.append(line.match(/[ \t]*$/)[0], state);
- }
- }
-
- if (!isLastLine) {
- utils.append('\n', state);
- }
- });
-
- utils.move(object.range[1], state);
-}
-
-function renderXJSExpressionContainer(traverse, object, isLast, path, state) {
- // Plus 1 to skip `{`.
- utils.move(object.range[0] + 1, state);
- traverse(object.expression, path, state);
-
- if (!isLast && object.expression.type !== Syntax.XJSEmptyExpression) {
- // If we need to append a comma, make sure to do so after the expression.
- utils.catchup(object.expression.range[1], state, trimLeft);
- utils.append(', ', state);
- }
-
- // Minus 1 to skip `}`.
- utils.catchup(object.range[1] - 1, state, trimLeft);
- utils.move(object.range[1], state);
- return false;
-}
-
-function quoteAttrName(attr) {
- // Quote invalid JS identifiers.
- if (!/^[a-z_$][a-z\d_$]*$/i.test(attr)) {
- return '"' + attr + '"';
- }
- return attr;
-}
-
-function trimLeft(value) {
- return value.replace(/^[ ]+/, '');
-}
-
-exports.knownTags = knownTags;
-exports.renderXJSExpressionContainer = renderXJSExpressionContainer;
-exports.renderXJSLiteral = renderXJSLiteral;
-exports.quoteAttrName = quoteAttrName;
-exports.trimLeft = trimLeft;
-
-},{"jstransform":21,"jstransform/src/utils":22}],37:[function(_dereq_,module,exports){
-/*global exports:true*/
-var es6ArrowFunctions = _dereq_('jstransform/visitors/es6-arrow-function-visitors');
+var es6ArrowFunctions =
+ _dereq_('jstransform/visitors/es6-arrow-function-visitors');
var es6Classes = _dereq_('jstransform/visitors/es6-class-visitors');
-var es6Destructuring = _dereq_('jstransform/visitors/es6-destructuring-visitors');
-var es6ObjectConciseMethod = _dereq_('jstransform/visitors/es6-object-concise-method-visitors');
-var es6ObjectShortNotation = _dereq_('jstransform/visitors/es6-object-short-notation-visitors');
+var es6Destructuring =
+ _dereq_('jstransform/visitors/es6-destructuring-visitors');
+var es6ObjectConciseMethod =
+ _dereq_('jstransform/visitors/es6-object-concise-method-visitors');
+var es6ObjectShortNotation =
+ _dereq_('jstransform/visitors/es6-object-short-notation-visitors');
var es6RestParameters = _dereq_('jstransform/visitors/es6-rest-param-visitors');
var es6Templates = _dereq_('jstransform/visitors/es6-template-visitors');
-var es7SpreadProperty = _dereq_('jstransform/visitors/es7-spread-property-visitors');
+var es6CallSpread =
+ _dereq_('jstransform/visitors/es6-call-spread-visitors');
+var es7SpreadProperty =
+ _dereq_('jstransform/visitors/es7-spread-property-visitors');
var react = _dereq_('./transforms/react');
var reactDisplayName = _dereq_('./transforms/reactDisplayName');
+var reservedWords = _dereq_('jstransform/visitors/reserved-words-visitors');
/**
* Map from transformName => orderedListOfVisitors.
*/
var transformVisitors = {
@@ -15109,12 +15797,14 @@
'es6-destructuring': es6Destructuring.visitorList,
'es6-object-concise-method': es6ObjectConciseMethod.visitorList,
'es6-object-short-notation': es6ObjectShortNotation.visitorList,
'es6-rest-params': es6RestParameters.visitorList,
'es6-templates': es6Templates.visitorList,
+ 'es6-call-spread': es6CallSpread.visitorList,
'es7-spread-property': es7SpreadProperty.visitorList,
- 'react': react.visitorList.concat(reactDisplayName.visitorList)
+ 'react': react.visitorList.concat(reactDisplayName.visitorList),
+ 'reserved-words': reservedWords.visitorList
};
var transformSets = {
'harmony': [
'es6-arrow-functions',
@@ -15122,28 +15812,34 @@
'es6-object-short-notation',
'es6-classes',
'es6-rest-params',
'es6-templates',
'es6-destructuring',
+ 'es6-call-spread',
'es7-spread-property'
],
+ 'es3': [
+ 'reserved-words'
+ ],
'react': [
'react'
]
};
/**
* Specifies the order in which each transform should run.
*/
var transformRunOrder = [
+ 'reserved-words',
'es6-arrow-functions',
'es6-object-concise-method',
'es6-object-short-notation',
'es6-classes',
'es6-rest-params',
'es6-templates',
'es6-destructuring',
+ 'es6-call-spread',
'es7-spread-property',
'react'
];
/**
@@ -15193,7 +15889,36 @@
exports.getVisitorsBySet = getVisitorsBySet;
exports.getAllVisitors = getAllVisitors;
exports.transformVisitors = transformVisitors;
-},{"./transforms/react":34,"./transforms/reactDisplayName":35,"jstransform/visitors/es6-arrow-function-visitors":23,"jstransform/visitors/es6-class-visitors":24,"jstransform/visitors/es6-destructuring-visitors":25,"jstransform/visitors/es6-object-concise-method-visitors":26,"jstransform/visitors/es6-object-short-notation-visitors":27,"jstransform/visitors/es6-rest-param-visitors":28,"jstransform/visitors/es6-template-visitors":29,"jstransform/visitors/es7-spread-property-visitors":31}]},{},[1])(1)
+},{"./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){
+/**
+ * Copyright 2013-2015, Facebook, Inc.
+ * All rights reserved.
+ *
+ * This source code is licensed under the BSD-style license found in the
+ * LICENSE file in the root directory of this source tree. An additional grant
+ * of patent rights can be found in the PATENTS file in the same directory.
+ */
+
+'use strict';
+/*eslint-disable no-undef*/
+var Buffer = _dereq_('buffer').Buffer;
+
+function inlineSourceMap(sourceMap, sourceCode, sourceFilename) {
+ // This can be used with a sourcemap that has already has toJSON called on it.
+ // Check first.
+ var json = sourceMap;
+ if (typeof sourceMap.toJSON === 'function') {
+ json = sourceMap.toJSON();
+ }
+ json.sources = [sourceFilename];
+ json.sourcesContent = [sourceCode];
+ var base64 = Buffer(JSON.stringify(json)).toString('base64');
+ return '//# sourceMappingURL=data:application/json;base64,' + base64;
+}
+
+module.exports = inlineSourceMap;
+
+},{"buffer":3}]},{},[1])(1)
});
\ No newline at end of file