PageRenderTime 91ms CodeModel.GetById 25ms RepoModel.GetById 0ms app.codeStats 1ms

/dist/jasmine/blanket_jasmine.js

https://github.com/geekdave/blanket
JavaScript | 5442 lines | 4485 code | 731 blank | 226 comment | 811 complexity | e48ea7fe662ee563a53e84a29ac6d7c2 MD5 | raw file
Possible License(s): MIT
  1. /*! blanket - v1.1.5 */
  2. (function(define){
  3. /*
  4. Copyright (C) 2012 Ariya Hidayat <ariya.hidayat@gmail.com>
  5. Copyright (C) 2012 Mathias Bynens <mathias@qiwi.be>
  6. Copyright (C) 2012 Joost-Wim Boekesteijn <joost-wim@boekesteijn.nl>
  7. Copyright (C) 2012 Kris Kowal <kris.kowal@cixar.com>
  8. Copyright (C) 2012 Yusuke Suzuki <utatane.tea@gmail.com>
  9. Copyright (C) 2012 Arpad Borsos <arpad.borsos@googlemail.com>
  10. Copyright (C) 2011 Ariya Hidayat <ariya.hidayat@gmail.com>
  11. Redistribution and use in source and binary forms, with or without
  12. modification, are permitted provided that the following conditions are met:
  13. * Redistributions of source code must retain the above copyright
  14. notice, this list of conditions and the following disclaimer.
  15. * Redistributions in binary form must reproduce the above copyright
  16. notice, this list of conditions and the following disclaimer in the
  17. documentation and/or other materials provided with the distribution.
  18. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  19. AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  20. IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  21. ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
  22. DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  23. (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  24. LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  25. ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  26. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  27. THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  28. */
  29. /*jslint bitwise:true plusplus:true */
  30. /*global esprima:true, define:true, exports:true, window: true,
  31. throwError: true, createLiteral: true, generateStatement: true,
  32. parseAssignmentExpression: true, parseBlock: true, parseExpression: true,
  33. parseFunctionDeclaration: true, parseFunctionExpression: true,
  34. parseFunctionSourceElements: true, parseVariableIdentifier: true,
  35. parseLeftHandSideExpression: true,
  36. parseStatement: true, parseSourceElement: true */
  37. (function (root, factory) {
  38. 'use strict';
  39. // Universal Module Definition (UMD) to support AMD, CommonJS/Node.js,
  40. // Rhino, and plain browser loading.
  41. if (typeof define === 'function' && define.amd) {
  42. define(['exports'], factory);
  43. } else if (typeof exports !== 'undefined') {
  44. factory(exports);
  45. } else {
  46. factory((root.esprima = {}));
  47. }
  48. }(this, function (exports) {
  49. 'use strict';
  50. var Token,
  51. TokenName,
  52. Syntax,
  53. PropertyKind,
  54. Messages,
  55. Regex,
  56. source,
  57. strict,
  58. index,
  59. lineNumber,
  60. lineStart,
  61. length,
  62. buffer,
  63. state,
  64. extra;
  65. Token = {
  66. BooleanLiteral: 1,
  67. EOF: 2,
  68. Identifier: 3,
  69. Keyword: 4,
  70. NullLiteral: 5,
  71. NumericLiteral: 6,
  72. Punctuator: 7,
  73. StringLiteral: 8
  74. };
  75. TokenName = {};
  76. TokenName[Token.BooleanLiteral] = 'Boolean';
  77. TokenName[Token.EOF] = '<end>';
  78. TokenName[Token.Identifier] = 'Identifier';
  79. TokenName[Token.Keyword] = 'Keyword';
  80. TokenName[Token.NullLiteral] = 'Null';
  81. TokenName[Token.NumericLiteral] = 'Numeric';
  82. TokenName[Token.Punctuator] = 'Punctuator';
  83. TokenName[Token.StringLiteral] = 'String';
  84. Syntax = {
  85. AssignmentExpression: 'AssignmentExpression',
  86. ArrayExpression: 'ArrayExpression',
  87. BlockStatement: 'BlockStatement',
  88. BinaryExpression: 'BinaryExpression',
  89. BreakStatement: 'BreakStatement',
  90. CallExpression: 'CallExpression',
  91. CatchClause: 'CatchClause',
  92. ConditionalExpression: 'ConditionalExpression',
  93. ContinueStatement: 'ContinueStatement',
  94. DoWhileStatement: 'DoWhileStatement',
  95. DebuggerStatement: 'DebuggerStatement',
  96. EmptyStatement: 'EmptyStatement',
  97. ExpressionStatement: 'ExpressionStatement',
  98. ForStatement: 'ForStatement',
  99. ForInStatement: 'ForInStatement',
  100. FunctionDeclaration: 'FunctionDeclaration',
  101. FunctionExpression: 'FunctionExpression',
  102. Identifier: 'Identifier',
  103. IfStatement: 'IfStatement',
  104. Literal: 'Literal',
  105. LabeledStatement: 'LabeledStatement',
  106. LogicalExpression: 'LogicalExpression',
  107. MemberExpression: 'MemberExpression',
  108. NewExpression: 'NewExpression',
  109. ObjectExpression: 'ObjectExpression',
  110. Program: 'Program',
  111. Property: 'Property',
  112. ReturnStatement: 'ReturnStatement',
  113. SequenceExpression: 'SequenceExpression',
  114. SwitchStatement: 'SwitchStatement',
  115. SwitchCase: 'SwitchCase',
  116. ThisExpression: 'ThisExpression',
  117. ThrowStatement: 'ThrowStatement',
  118. TryStatement: 'TryStatement',
  119. UnaryExpression: 'UnaryExpression',
  120. UpdateExpression: 'UpdateExpression',
  121. VariableDeclaration: 'VariableDeclaration',
  122. VariableDeclarator: 'VariableDeclarator',
  123. WhileStatement: 'WhileStatement',
  124. WithStatement: 'WithStatement'
  125. };
  126. PropertyKind = {
  127. Data: 1,
  128. Get: 2,
  129. Set: 4
  130. };
  131. // Error messages should be identical to V8.
  132. Messages = {
  133. UnexpectedToken: 'Unexpected token %0',
  134. UnexpectedNumber: 'Unexpected number',
  135. UnexpectedString: 'Unexpected string',
  136. UnexpectedIdentifier: 'Unexpected identifier',
  137. UnexpectedReserved: 'Unexpected reserved word',
  138. UnexpectedEOS: 'Unexpected end of input',
  139. NewlineAfterThrow: 'Illegal newline after throw',
  140. InvalidRegExp: 'Invalid regular expression',
  141. UnterminatedRegExp: 'Invalid regular expression: missing /',
  142. InvalidLHSInAssignment: 'Invalid left-hand side in assignment',
  143. InvalidLHSInForIn: 'Invalid left-hand side in for-in',
  144. MultipleDefaultsInSwitch: 'More than one default clause in switch statement',
  145. NoCatchOrFinally: 'Missing catch or finally after try',
  146. UnknownLabel: 'Undefined label \'%0\'',
  147. Redeclaration: '%0 \'%1\' has already been declared',
  148. IllegalContinue: 'Illegal continue statement',
  149. IllegalBreak: 'Illegal break statement',
  150. IllegalReturn: 'Illegal return statement',
  151. StrictModeWith: 'Strict mode code may not include a with statement',
  152. StrictCatchVariable: 'Catch variable may not be eval or arguments in strict mode',
  153. StrictVarName: 'Variable name may not be eval or arguments in strict mode',
  154. StrictParamName: 'Parameter name eval or arguments is not allowed in strict mode',
  155. StrictParamDupe: 'Strict mode function may not have duplicate parameter names',
  156. StrictFunctionName: 'Function name may not be eval or arguments in strict mode',
  157. StrictOctalLiteral: 'Octal literals are not allowed in strict mode.',
  158. StrictDelete: 'Delete of an unqualified identifier in strict mode.',
  159. StrictDuplicateProperty: 'Duplicate data property in object literal not allowed in strict mode',
  160. AccessorDataProperty: 'Object literal may not have data and accessor property with the same name',
  161. AccessorGetSet: 'Object literal may not have multiple get/set accessors with the same name',
  162. StrictLHSAssignment: 'Assignment to eval or arguments is not allowed in strict mode',
  163. StrictLHSPostfix: 'Postfix increment/decrement may not have eval or arguments operand in strict mode',
  164. StrictLHSPrefix: 'Prefix increment/decrement may not have eval or arguments operand in strict mode',
  165. StrictReservedWord: 'Use of future reserved word in strict mode'
  166. };
  167. // See also tools/generate-unicode-regex.py.
  168. Regex = {
  169. NonAsciiIdentifierStart: new RegExp('[\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u0527\u0531-\u0556\u0559\u0561-\u0587\u05d0-\u05ea\u05f0-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u08a0\u08a2-\u08ac\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0977\u0979-\u097f\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c33\u0c35-\u0c39\u0c3d\u0c58\u0c59\u0c60\u0c61\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d05-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d60\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e87\u0e88\u0e8a\u0e8d\u0e94-\u0e97\u0e99-\u0e9f\u0ea1-\u0ea3\u0ea5\u0ea7\u0eaa\u0eab\u0ead-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f4\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f0\u1700-\u170c\u170e-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1877\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191c\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19c1-\u19c7\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4b\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1ce9-\u1cec\u1cee-\u1cf1\u1cf5\u1cf6\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2119-\u211d\u2124\u2126\u2128\u212a-\u212d\u212f-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u2e2f\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309d-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312d\u3131-\u318e\u31a0-\u31ba\u31f0-\u31ff\u3400-\u4db5\u4e00-\u9fcc\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua697\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua78e\ua790-\ua793\ua7a0-\ua7aa\ua7f8-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa80-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uabc0-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc]'),
  170. NonAsciiIdentifierPart: new RegExp('[\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0300-\u0374\u0376\u0377\u037a-\u037d\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u0483-\u0487\u048a-\u0527\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u05d0-\u05ea\u05f0-\u05f2\u0610-\u061a\u0620-\u0669\u066e-\u06d3\u06d5-\u06dc\u06df-\u06e8\u06ea-\u06fc\u06ff\u0710-\u074a\u074d-\u07b1\u07c0-\u07f5\u07fa\u0800-\u082d\u0840-\u085b\u08a0\u08a2-\u08ac\u08e4-\u08fe\u0900-\u0963\u0966-\u096f\u0971-\u0977\u0979-\u097f\u0981-\u0983\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bc-\u09c4\u09c7\u09c8\u09cb-\u09ce\u09d7\u09dc\u09dd\u09df-\u09e3\u09e6-\u09f1\u0a01-\u0a03\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a59-\u0a5c\u0a5e\u0a66-\u0a75\u0a81-\u0a83\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abc-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ad0\u0ae0-\u0ae3\u0ae6-\u0aef\u0b01-\u0b03\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3c-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b56\u0b57\u0b5c\u0b5d\u0b5f-\u0b63\u0b66-\u0b6f\u0b71\u0b82\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd0\u0bd7\u0be6-\u0bef\u0c01-\u0c03\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c33\u0c35-\u0c39\u0c3d-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c58\u0c59\u0c60-\u0c63\u0c66-\u0c6f\u0c82\u0c83\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbc-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0cde\u0ce0-\u0ce3\u0ce6-\u0cef\u0cf1\u0cf2\u0d02\u0d03\u0d05-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d-\u0d44\u0d46-\u0d48\u0d4a-\u0d4e\u0d57\u0d60-\u0d63\u0d66-\u0d6f\u0d7a-\u0d7f\u0d82\u0d83\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0df2\u0df3\u0e01-\u0e3a\u0e40-\u0e4e\u0e50-\u0e59\u0e81\u0e82\u0e84\u0e87\u0e88\u0e8a\u0e8d\u0e94-\u0e97\u0e99-\u0e9f\u0ea1-\u0ea3\u0ea5\u0ea7\u0eaa\u0eab\u0ead-\u0eb9\u0ebb-\u0ebd\u0ec0-\u0ec4\u0ec6\u0ec8-\u0ecd\u0ed0-\u0ed9\u0edc-\u0edf\u0f00\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f3e-\u0f47\u0f49-\u0f6c\u0f71-\u0f84\u0f86-\u0f97\u0f99-\u0fbc\u0fc6\u1000-\u1049\u1050-\u109d\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u135d-\u135f\u1380-\u138f\u13a0-\u13f4\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f0\u1700-\u170c\u170e-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176c\u176e-\u1770\u1772\u1773\u1780-\u17d3\u17d7\u17dc\u17dd\u17e0-\u17e9\u180b-\u180d\u1810-\u1819\u1820-\u1877\u1880-\u18aa\u18b0-\u18f5\u1900-\u191c\u1920-\u192b\u1930-\u193b\u1946-\u196d\u1970-\u1974\u1980-\u19ab\u19b0-\u19c9\u19d0-\u19d9\u1a00-\u1a1b\u1a20-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1aa7\u1b00-\u1b4b\u1b50-\u1b59\u1b6b-\u1b73\u1b80-\u1bf3\u1c00-\u1c37\u1c40-\u1c49\u1c4d-\u1c7d\u1cd0-\u1cd2\u1cd4-\u1cf6\u1d00-\u1de6\u1dfc-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u200c\u200d\u203f\u2040\u2054\u2071\u207f\u2090-\u209c\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2102\u2107\u210a-\u2113\u2115\u2119-\u211d\u2124\u2126\u2128\u212a-\u212d\u212f-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d7f-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u2de0-\u2dff\u2e2f\u3005-\u3007\u3021-\u302f\u3031-\u3035\u3038-\u303c\u3041-\u3096\u3099\u309a\u309d-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312d\u3131-\u318e\u31a0-\u31ba\u31f0-\u31ff\u3400-\u4db5\u4e00-\u9fcc\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua62b\ua640-\ua66f\ua674-\ua67d\ua67f-\ua697\ua69f-\ua6f1\ua717-\ua71f\ua722-\ua788\ua78b-\ua78e\ua790-\ua793\ua7a0-\ua7aa\ua7f8-\ua827\ua840-\ua873\ua880-\ua8c4\ua8d0-\ua8d9\ua8e0-\ua8f7\ua8fb\ua900-\ua92d\ua930-\ua953\ua960-\ua97c\ua980-\ua9c0\ua9cf-\ua9d9\uaa00-\uaa36\uaa40-\uaa4d\uaa50-\uaa59\uaa60-\uaa76\uaa7a\uaa7b\uaa80-\uaac2\uaadb-\uaadd\uaae0-\uaaef\uaaf2-\uaaf6\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uabc0-\uabea\uabec\uabed\uabf0-\uabf9\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe00-\ufe0f\ufe20-\ufe26\ufe33\ufe34\ufe4d-\ufe4f\ufe70-\ufe74\ufe76-\ufefc\uff10-\uff19\uff21-\uff3a\uff3f\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc]')
  171. };
  172. // Ensure the condition is true, otherwise throw an error.
  173. // This is only to have a better contract semantic, i.e. another safety net
  174. // to catch a logic error. The condition shall be fulfilled in normal case.
  175. // Do NOT use this to enforce a certain condition on any user input.
  176. function assert(condition, message) {
  177. if (!condition) {
  178. throw new Error('ASSERT: ' + message);
  179. }
  180. }
  181. function sliceSource(from, to) {
  182. return source.slice(from, to);
  183. }
  184. if (typeof 'esprima'[0] === 'undefined') {
  185. sliceSource = function sliceArraySource(from, to) {
  186. return source.slice(from, to).join('');
  187. };
  188. }
  189. function isDecimalDigit(ch) {
  190. return '0123456789'.indexOf(ch) >= 0;
  191. }
  192. function isHexDigit(ch) {
  193. return '0123456789abcdefABCDEF'.indexOf(ch) >= 0;
  194. }
  195. function isOctalDigit(ch) {
  196. return '01234567'.indexOf(ch) >= 0;
  197. }
  198. // 7.2 White Space
  199. function isWhiteSpace(ch) {
  200. return (ch === ' ') || (ch === '\u0009') || (ch === '\u000B') ||
  201. (ch === '\u000C') || (ch === '\u00A0') ||
  202. (ch.charCodeAt(0) >= 0x1680 &&
  203. '\u1680\u180E\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\uFEFF'.indexOf(ch) >= 0);
  204. }
  205. // 7.3 Line Terminators
  206. function isLineTerminator(ch) {
  207. return (ch === '\n' || ch === '\r' || ch === '\u2028' || ch === '\u2029');
  208. }
  209. // 7.6 Identifier Names and Identifiers
  210. function isIdentifierStart(ch) {
  211. return (ch === '$') || (ch === '_') || (ch === '\\') ||
  212. (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') ||
  213. ((ch.charCodeAt(0) >= 0x80) && Regex.NonAsciiIdentifierStart.test(ch));
  214. }
  215. function isIdentifierPart(ch) {
  216. return (ch === '$') || (ch === '_') || (ch === '\\') ||
  217. (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') ||
  218. ((ch >= '0') && (ch <= '9')) ||
  219. ((ch.charCodeAt(0) >= 0x80) && Regex.NonAsciiIdentifierPart.test(ch));
  220. }
  221. // 7.6.1.2 Future Reserved Words
  222. function isFutureReservedWord(id) {
  223. switch (id) {
  224. // Future reserved words.
  225. case 'class':
  226. case 'enum':
  227. case 'export':
  228. case 'extends':
  229. case 'import':
  230. case 'super':
  231. return true;
  232. }
  233. return false;
  234. }
  235. function isStrictModeReservedWord(id) {
  236. switch (id) {
  237. // Strict Mode reserved words.
  238. case 'implements':
  239. case 'interface':
  240. case 'package':
  241. case 'private':
  242. case 'protected':
  243. case 'public':
  244. case 'static':
  245. case 'yield':
  246. case 'let':
  247. return true;
  248. }
  249. return false;
  250. }
  251. function isRestrictedWord(id) {
  252. return id === 'eval' || id === 'arguments';
  253. }
  254. // 7.6.1.1 Keywords
  255. function isKeyword(id) {
  256. var keyword = false;
  257. switch (id.length) {
  258. case 2:
  259. keyword = (id === 'if') || (id === 'in') || (id === 'do');
  260. break;
  261. case 3:
  262. keyword = (id === 'var') || (id === 'for') || (id === 'new') || (id === 'try');
  263. break;
  264. case 4:
  265. keyword = (id === 'this') || (id === 'else') || (id === 'case') || (id === 'void') || (id === 'with');
  266. break;
  267. case 5:
  268. keyword = (id === 'while') || (id === 'break') || (id === 'catch') || (id === 'throw');
  269. break;
  270. case 6:
  271. keyword = (id === 'return') || (id === 'typeof') || (id === 'delete') || (id === 'switch');
  272. break;
  273. case 7:
  274. keyword = (id === 'default') || (id === 'finally');
  275. break;
  276. case 8:
  277. keyword = (id === 'function') || (id === 'continue') || (id === 'debugger');
  278. break;
  279. case 10:
  280. keyword = (id === 'instanceof');
  281. break;
  282. }
  283. if (keyword) {
  284. return true;
  285. }
  286. switch (id) {
  287. // Future reserved words.
  288. // 'const' is specialized as Keyword in V8.
  289. case 'const':
  290. return true;
  291. // For compatiblity to SpiderMonkey and ES.next
  292. case 'yield':
  293. case 'let':
  294. return true;
  295. }
  296. if (strict && isStrictModeReservedWord(id)) {
  297. return true;
  298. }
  299. return isFutureReservedWord(id);
  300. }
  301. // 7.4 Comments
  302. function skipComment() {
  303. var ch, blockComment, lineComment;
  304. blockComment = false;
  305. lineComment = false;
  306. while (index < length) {
  307. ch = source[index];
  308. if (lineComment) {
  309. ch = source[index++];
  310. if (isLineTerminator(ch)) {
  311. lineComment = false;
  312. if (ch === '\r' && source[index] === '\n') {
  313. ++index;
  314. }
  315. ++lineNumber;
  316. lineStart = index;
  317. }
  318. } else if (blockComment) {
  319. if (isLineTerminator(ch)) {
  320. if (ch === '\r' && source[index + 1] === '\n') {
  321. ++index;
  322. }
  323. ++lineNumber;
  324. ++index;
  325. lineStart = index;
  326. if (index >= length) {
  327. throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
  328. }
  329. } else {
  330. ch = source[index++];
  331. if (index >= length) {
  332. throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
  333. }
  334. if (ch === '*') {
  335. ch = source[index];
  336. if (ch === '/') {
  337. ++index;
  338. blockComment = false;
  339. }
  340. }
  341. }
  342. } else if (ch === '/') {
  343. ch = source[index + 1];
  344. if (ch === '/') {
  345. index += 2;
  346. lineComment = true;
  347. } else if (ch === '*') {
  348. index += 2;
  349. blockComment = true;
  350. if (index >= length) {
  351. throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
  352. }
  353. } else {
  354. break;
  355. }
  356. } else if (isWhiteSpace(ch)) {
  357. ++index;
  358. } else if (isLineTerminator(ch)) {
  359. ++index;
  360. if (ch === '\r' && source[index] === '\n') {
  361. ++index;
  362. }
  363. ++lineNumber;
  364. lineStart = index;
  365. } else {
  366. break;
  367. }
  368. }
  369. }
  370. function scanHexEscape(prefix) {
  371. var i, len, ch, code = 0;
  372. len = (prefix === 'u') ? 4 : 2;
  373. for (i = 0; i < len; ++i) {
  374. if (index < length && isHexDigit(source[index])) {
  375. ch = source[index++];
  376. code = code * 16 + '0123456789abcdef'.indexOf(ch.toLowerCase());
  377. } else {
  378. return '';
  379. }
  380. }
  381. return String.fromCharCode(code);
  382. }
  383. function scanIdentifier() {
  384. var ch, start, id, restore;
  385. ch = source[index];
  386. if (!isIdentifierStart(ch)) {
  387. return;
  388. }
  389. start = index;
  390. if (ch === '\\') {
  391. ++index;
  392. if (source[index] !== 'u') {
  393. return;
  394. }
  395. ++index;
  396. restore = index;
  397. ch = scanHexEscape('u');
  398. if (ch) {
  399. if (ch === '\\' || !isIdentifierStart(ch)) {
  400. return;
  401. }
  402. id = ch;
  403. } else {
  404. index = restore;
  405. id = 'u';
  406. }
  407. } else {
  408. id = source[index++];
  409. }
  410. while (index < length) {
  411. ch = source[index];
  412. if (!isIdentifierPart(ch)) {
  413. break;
  414. }
  415. if (ch === '\\') {
  416. ++index;
  417. if (source[index] !== 'u') {
  418. return;
  419. }
  420. ++index;
  421. restore = index;
  422. ch = scanHexEscape('u');
  423. if (ch) {
  424. if (ch === '\\' || !isIdentifierPart(ch)) {
  425. return;
  426. }
  427. id += ch;
  428. } else {
  429. index = restore;
  430. id += 'u';
  431. }
  432. } else {
  433. id += source[index++];
  434. }
  435. }
  436. // There is no keyword or literal with only one character.
  437. // Thus, it must be an identifier.
  438. if (id.length === 1) {
  439. return {
  440. type: Token.Identifier,
  441. value: id,
  442. lineNumber: lineNumber,
  443. lineStart: lineStart,
  444. range: [start, index]
  445. };
  446. }
  447. if (isKeyword(id)) {
  448. return {
  449. type: Token.Keyword,
  450. value: id,
  451. lineNumber: lineNumber,
  452. lineStart: lineStart,
  453. range: [start, index]
  454. };
  455. }
  456. // 7.8.1 Null Literals
  457. if (id === 'null') {
  458. return {
  459. type: Token.NullLiteral,
  460. value: id,
  461. lineNumber: lineNumber,
  462. lineStart: lineStart,
  463. range: [start, index]
  464. };
  465. }
  466. // 7.8.2 Boolean Literals
  467. if (id === 'true' || id === 'false') {
  468. return {
  469. type: Token.BooleanLiteral,
  470. value: id,
  471. lineNumber: lineNumber,
  472. lineStart: lineStart,
  473. range: [start, index]
  474. };
  475. }
  476. return {
  477. type: Token.Identifier,
  478. value: id,
  479. lineNumber: lineNumber,
  480. lineStart: lineStart,
  481. range: [start, index]
  482. };
  483. }
  484. // 7.7 Punctuators
  485. function scanPunctuator() {
  486. var start = index,
  487. ch1 = source[index],
  488. ch2,
  489. ch3,
  490. ch4;
  491. // Check for most common single-character punctuators.
  492. if (ch1 === ';' || ch1 === '{' || ch1 === '}') {
  493. ++index;
  494. return {
  495. type: Token.Punctuator,
  496. value: ch1,
  497. lineNumber: lineNumber,
  498. lineStart: lineStart,
  499. range: [start, index]
  500. };
  501. }
  502. if (ch1 === ',' || ch1 === '(' || ch1 === ')') {
  503. ++index;
  504. return {
  505. type: Token.Punctuator,
  506. value: ch1,
  507. lineNumber: lineNumber,
  508. lineStart: lineStart,
  509. range: [start, index]
  510. };
  511. }
  512. // Dot (.) can also start a floating-point number, hence the need
  513. // to check the next character.
  514. ch2 = source[index + 1];
  515. if (ch1 === '.' && !isDecimalDigit(ch2)) {
  516. return {
  517. type: Token.Punctuator,
  518. value: source[index++],
  519. lineNumber: lineNumber,
  520. lineStart: lineStart,
  521. range: [start, index]
  522. };
  523. }
  524. // Peek more characters.
  525. ch3 = source[index + 2];
  526. ch4 = source[index + 3];
  527. // 4-character punctuator: >>>=
  528. if (ch1 === '>' && ch2 === '>' && ch3 === '>') {
  529. if (ch4 === '=') {
  530. index += 4;
  531. return {
  532. type: Token.Punctuator,
  533. value: '>>>=',
  534. lineNumber: lineNumber,
  535. lineStart: lineStart,
  536. range: [start, index]
  537. };
  538. }
  539. }
  540. // 3-character punctuators: === !== >>> <<= >>=
  541. if (ch1 === '=' && ch2 === '=' && ch3 === '=') {
  542. index += 3;
  543. return {
  544. type: Token.Punctuator,
  545. value: '===',
  546. lineNumber: lineNumber,
  547. lineStart: lineStart,
  548. range: [start, index]
  549. };
  550. }
  551. if (ch1 === '!' && ch2 === '=' && ch3 === '=') {
  552. index += 3;
  553. return {
  554. type: Token.Punctuator,
  555. value: '!==',
  556. lineNumber: lineNumber,
  557. lineStart: lineStart,
  558. range: [start, index]
  559. };
  560. }
  561. if (ch1 === '>' && ch2 === '>' && ch3 === '>') {
  562. index += 3;
  563. return {
  564. type: Token.Punctuator,
  565. value: '>>>',
  566. lineNumber: lineNumber,
  567. lineStart: lineStart,
  568. range: [start, index]
  569. };
  570. }
  571. if (ch1 === '<' && ch2 === '<' && ch3 === '=') {
  572. index += 3;
  573. return {
  574. type: Token.Punctuator,
  575. value: '<<=',
  576. lineNumber: lineNumber,
  577. lineStart: lineStart,
  578. range: [start, index]
  579. };
  580. }
  581. if (ch1 === '>' && ch2 === '>' && ch3 === '=') {
  582. index += 3;
  583. return {
  584. type: Token.Punctuator,
  585. value: '>>=',
  586. lineNumber: lineNumber,
  587. lineStart: lineStart,
  588. range: [start, index]
  589. };
  590. }
  591. // 2-character punctuators: <= >= == != ++ -- << >> && ||
  592. // += -= *= %= &= |= ^= /=
  593. if (ch2 === '=') {
  594. if ('<>=!+-*%&|^/'.indexOf(ch1) >= 0) {
  595. index += 2;
  596. return {
  597. type: Token.Punctuator,
  598. value: ch1 + ch2,
  599. lineNumber: lineNumber,
  600. lineStart: lineStart,
  601. range: [start, index]
  602. };
  603. }
  604. }
  605. if (ch1 === ch2 && ('+-<>&|'.indexOf(ch1) >= 0)) {
  606. if ('+-<>&|'.indexOf(ch2) >= 0) {
  607. index += 2;
  608. return {
  609. type: Token.Punctuator,
  610. value: ch1 + ch2,
  611. lineNumber: lineNumber,
  612. lineStart: lineStart,
  613. range: [start, index]
  614. };
  615. }
  616. }
  617. // The remaining 1-character punctuators.
  618. if ('[]<>+-*%&|^!~?:=/'.indexOf(ch1) >= 0) {
  619. return {
  620. type: Token.Punctuator,
  621. value: source[index++],
  622. lineNumber: lineNumber,
  623. lineStart: lineStart,
  624. range: [start, index]
  625. };
  626. }
  627. }
  628. // 7.8.3 Numeric Literals
  629. function scanNumericLiteral() {
  630. var number, start, ch;
  631. ch = source[index];
  632. assert(isDecimalDigit(ch) || (ch === '.'),
  633. 'Numeric literal must start with a decimal digit or a decimal point');
  634. start = index;
  635. number = '';
  636. if (ch !== '.') {
  637. number = source[index++];
  638. ch = source[index];
  639. // Hex number starts with '0x'.
  640. // Octal number starts with '0'.
  641. if (number === '0') {
  642. if (ch === 'x' || ch === 'X') {
  643. number += source[index++];
  644. while (index < length) {
  645. ch = source[index];
  646. if (!isHexDigit(ch)) {
  647. break;
  648. }
  649. number += source[index++];
  650. }
  651. if (number.length <= 2) {
  652. // only 0x
  653. throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
  654. }
  655. if (index < length) {
  656. ch = source[index];
  657. if (isIdentifierStart(ch)) {
  658. throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
  659. }
  660. }
  661. return {
  662. type: Token.NumericLiteral,
  663. value: parseInt(number, 16),
  664. lineNumber: lineNumber,
  665. lineStart: lineStart,
  666. range: [start, index]
  667. };
  668. } else if (isOctalDigit(ch)) {
  669. number += source[index++];
  670. while (index < length) {
  671. ch = source[index];
  672. if (!isOctalDigit(ch)) {
  673. break;
  674. }
  675. number += source[index++];
  676. }
  677. if (index < length) {
  678. ch = source[index];
  679. if (isIdentifierStart(ch) || isDecimalDigit(ch)) {
  680. throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
  681. }
  682. }
  683. return {
  684. type: Token.NumericLiteral,
  685. value: parseInt(number, 8),
  686. octal: true,
  687. lineNumber: lineNumber,
  688. lineStart: lineStart,
  689. range: [start, index]
  690. };
  691. }
  692. // decimal number starts with '0' such as '09' is illegal.
  693. if (isDecimalDigit(ch)) {
  694. throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
  695. }
  696. }
  697. while (index < length) {
  698. ch = source[index];
  699. if (!isDecimalDigit(ch)) {
  700. break;
  701. }
  702. number += source[index++];
  703. }
  704. }
  705. if (ch === '.') {
  706. number += source[index++];
  707. while (index < length) {
  708. ch = source[index];
  709. if (!isDecimalDigit(ch)) {
  710. break;
  711. }
  712. number += source[index++];
  713. }
  714. }
  715. if (ch === 'e' || ch === 'E') {
  716. number += source[index++];
  717. ch = source[index];
  718. if (ch === '+' || ch === '-') {
  719. number += source[index++];
  720. }
  721. ch = source[index];
  722. if (isDecimalDigit(ch)) {
  723. number += source[index++];
  724. while (index < length) {
  725. ch = source[index];
  726. if (!isDecimalDigit(ch)) {
  727. break;
  728. }
  729. number += source[index++];
  730. }
  731. } else {
  732. ch = 'character ' + ch;
  733. if (index >= length) {
  734. ch = '<end>';
  735. }
  736. throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
  737. }
  738. }
  739. if (index < length) {
  740. ch = source[index];
  741. if (isIdentifierStart(ch)) {
  742. throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
  743. }
  744. }
  745. return {
  746. type: Token.NumericLiteral,
  747. value: parseFloat(number),
  748. lineNumber: lineNumber,
  749. lineStart: lineStart,
  750. range: [start, index]
  751. };
  752. }
  753. // 7.8.4 String Literals
  754. function scanStringLiteral() {
  755. var str = '', quote, start, ch, code, unescaped, restore, octal = false;
  756. quote = source[index];
  757. assert((quote === '\'' || quote === '"'),
  758. 'String literal must starts with a quote');
  759. start = index;
  760. ++index;
  761. while (index < length) {
  762. ch = source[index++];
  763. if (ch === quote) {
  764. quote = '';
  765. break;
  766. } else if (ch === '\\') {
  767. ch = source[index++];
  768. if (!isLineTerminator(ch)) {
  769. switch (ch) {
  770. case 'n':
  771. str += '\n';
  772. break;
  773. case 'r':
  774. str += '\r';
  775. break;
  776. case 't':
  777. str += '\t';
  778. break;
  779. case 'u':
  780. case 'x':
  781. restore = index;
  782. unescaped = scanHexEscape(ch);
  783. if (unescaped) {
  784. str += unescaped;
  785. } else {
  786. index = restore;
  787. str += ch;
  788. }
  789. break;
  790. case 'b':
  791. str += '\b';
  792. break;
  793. case 'f':
  794. str += '\f';
  795. break;
  796. case 'v':
  797. str += '\v';
  798. break;
  799. default:
  800. if (isOctalDigit(ch)) {
  801. code = '01234567'.indexOf(ch);
  802. // \0 is not octal escape sequence
  803. if (code !== 0) {
  804. octal = true;
  805. }
  806. if (index < length && isOctalDigit(source[index])) {
  807. octal = true;
  808. code = code * 8 + '01234567'.indexOf(source[index++]);
  809. // 3 digits are only allowed when string starts
  810. // with 0, 1, 2, 3
  811. if ('0123'.indexOf(ch) >= 0 &&
  812. index < length &&
  813. isOctalDigit(source[index])) {
  814. code = code * 8 + '01234567'.indexOf(source[index++]);
  815. }
  816. }
  817. str += String.fromCharCode(code);
  818. } else {
  819. str += ch;
  820. }
  821. break;
  822. }
  823. } else {
  824. ++lineNumber;
  825. if (ch === '\r' && source[index] === '\n') {
  826. ++index;
  827. }
  828. }
  829. } else if (isLineTerminator(ch)) {
  830. break;
  831. } else {
  832. str += ch;
  833. }
  834. }
  835. if (quote !== '') {
  836. throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
  837. }
  838. return {
  839. type: Token.StringLiteral,
  840. value: str,
  841. octal: octal,
  842. lineNumber: lineNumber,
  843. lineStart: lineStart,
  844. range: [start, index]
  845. };
  846. }
  847. function scanRegExp() {
  848. var str, ch, start, pattern, flags, value, classMarker = false, restore, terminated = false;
  849. buffer = null;
  850. skipComment();
  851. start = index;
  852. ch = source[index];
  853. assert(ch === '/', 'Regular expression literal must start with a slash');
  854. str = source[index++];
  855. while (index < length) {
  856. ch = source[index++];
  857. str += ch;
  858. if (classMarker) {
  859. if (ch === ']') {
  860. classMarker = false;
  861. }
  862. } else {
  863. if (ch === '\\') {
  864. ch = source[index++];
  865. // ECMA-262 7.8.5
  866. if (isLineTerminator(ch)) {
  867. throwError({}, Messages.UnterminatedRegExp);
  868. }
  869. str += ch;
  870. } else if (ch === '/') {
  871. terminated = true;
  872. break;
  873. } else if (ch === '[') {
  874. classMarker = true;
  875. } else if (isLineTerminator(ch)) {
  876. throwError({}, Messages.UnterminatedRegExp);
  877. }
  878. }
  879. }
  880. if (!terminated) {
  881. throwError({}, Messages.UnterminatedRegExp);
  882. }
  883. // Exclude leading and trailing slash.
  884. pattern = str.substr(1, str.length - 2);
  885. flags = '';
  886. while (index < length) {
  887. ch = source[index];
  888. if (!isIdentifierPart(ch)) {
  889. break;
  890. }
  891. ++index;
  892. if (ch === '\\' && index < length) {
  893. ch = source[index];
  894. if (ch === 'u') {
  895. ++index;
  896. restore = index;
  897. ch = scanHexEscape('u');
  898. if (ch) {
  899. flags += ch;
  900. str += '\\u';
  901. for (; restore < index; ++restore) {
  902. str += source[restore];
  903. }
  904. } else {
  905. index = restore;
  906. flags += 'u';
  907. str += '\\u';
  908. }
  909. } else {
  910. str += '\\';
  911. }
  912. } else {
  913. flags += ch;
  914. str += ch;
  915. }
  916. }
  917. try {
  918. value = new RegExp(pattern, flags);
  919. } catch (e) {
  920. throwError({}, Messages.InvalidRegExp);
  921. }
  922. return {
  923. literal: str,
  924. value: value,
  925. range: [start, index]
  926. };
  927. }
  928. function isIdentifierName(token) {
  929. return token.type === Token.Identifier ||
  930. token.type === Token.Keyword ||
  931. token.type === Token.BooleanLiteral ||
  932. token.type === Token.NullLiteral;
  933. }
  934. function advance() {
  935. var ch, token;
  936. skipComment();
  937. if (index >= length) {
  938. return {
  939. type: Token.EOF,
  940. lineNumber: lineNumber,
  941. lineStart: lineStart,
  942. range: [index, index]
  943. };
  944. }
  945. token = scanPunctuator();
  946. if (typeof token !== 'undefined') {
  947. return token;
  948. }
  949. ch = source[index];
  950. if (ch === '\'' || ch === '"') {
  951. return scanStringLiteral();
  952. }
  953. if (ch === '.' || isDecimalDigit(ch)) {
  954. return scanNumericLiteral();
  955. }
  956. token = scanIdentifier();
  957. if (typeof token !== 'undefined') {
  958. return token;
  959. }
  960. throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
  961. }
  962. function lex() {
  963. var token;
  964. if (buffer) {
  965. index = buffer.range[1];
  966. lineNumber = buffer.lineNumber;
  967. lineStart = buffer.lineStart;
  968. token = buffer;
  969. buffer = null;
  970. return token;
  971. }
  972. buffer = null;
  973. return advance();
  974. }
  975. function lookahead() {
  976. var pos, line, start;
  977. if (buffer !== null) {
  978. return buffer;
  979. }
  980. pos = index;
  981. line = lineNumber;
  982. start = lineStart;
  983. buffer = advance();
  984. index = pos;
  985. lineNumber = line;
  986. lineStart = start;
  987. return buffer;
  988. }
  989. // Return true if there is a line terminator before the next token.
  990. function peekLineTerminator() {
  991. var pos, line, start, found;
  992. pos = index;
  993. line = lineNumber;
  994. start = lineStart;
  995. skipComment();
  996. found = lineNumber !== line;
  997. index = pos;
  998. lineNumber = line;
  999. lineStart = start;
  1000. return found;
  1001. }
  1002. // Throw an exception
  1003. function throwError(token, messageFormat) {
  1004. var error,
  1005. args = Array.prototype.slice.call(arguments, 2),
  1006. msg = messageFormat.replace(
  1007. /%(\d)/g,
  1008. function (whole, index) {
  1009. return args[index] || '';
  1010. }
  1011. );
  1012. if (typeof token.lineNumber === 'number') {
  1013. error = new Error('Line ' + token.lineNumber + ': ' + msg);
  1014. error.index = token.range[0];
  1015. error.lineNumber = token.lineNumber;
  1016. error.column = token.range[0] - lineStart + 1;
  1017. } else {
  1018. error = new Error('Line ' + lineNumber + ': ' + msg);
  1019. error.index = index;
  1020. error.lineNumber = lineNumber;
  1021. error.column = index - lineStart + 1;
  1022. }
  1023. throw error;
  1024. }
  1025. function throwErrorTolerant() {
  1026. try {
  1027. throwError.apply(null, arguments);
  1028. } catch (e) {
  1029. if (extra.errors) {
  1030. extra.errors.push(e);
  1031. } else {
  1032. throw e;
  1033. }
  1034. }
  1035. }
  1036. // Throw an exception because of the token.
  1037. function throwUnexpected(token) {
  1038. if (token.type === Token.EOF) {
  1039. throwError(token, Messages.UnexpectedEOS);
  1040. }
  1041. if (token.type === Token.NumericLiteral) {
  1042. throwError(token, Messages.UnexpectedNumber);
  1043. }
  1044. if (token.type === Token.StringLiteral) {
  1045. throwError(token, Messages.UnexpectedString);
  1046. }
  1047. if (token.type === Token.Identifier) {
  1048. throwError(token, Messages.UnexpectedIdentifier);
  1049. }
  1050. if (token.type === Token.Keyword) {
  1051. if (isFutureReservedWord(token.value)) {
  1052. throwError(token, Messages.UnexpectedReserved);
  1053. } else if (strict && isStrictModeReservedWord(token.value)) {
  1054. throwErrorTolerant(token, Messages.StrictReservedWord);
  1055. return;
  1056. }
  1057. throwError(token, Messages.UnexpectedToken, token.value);
  1058. }
  1059. // BooleanLiteral, NullLiteral, or Punctuator.
  1060. throwError(token, Messages.UnexpectedToken, token.value);
  1061. }
  1062. // Expect the next token to match the specified punctuator.
  1063. // If not, an exception will be thrown.
  1064. function expect(value) {
  1065. var token = lex();
  1066. if (token.type !== Token.Punctuator || token.value !== value) {
  1067. throwUnexpected(token);
  1068. }
  1069. }
  1070. // Expect the next token to match the specified keyword.
  1071. // If not, an exception will be thrown.
  1072. function expectKeyword(keyword) {
  1073. var token = lex();
  1074. if (token.type !== Token.Keyword || token.value !== keyword) {
  1075. throwUnexpected(token);
  1076. }
  1077. }
  1078. // Return true if the next token matches the specified punctuator.
  1079. function match(value) {
  1080. var token = lookahead();
  1081. return token.type === Token.Punctuator && token.value === value;
  1082. }
  1083. // Return true if the next token matches the specified keyword
  1084. function matchKeyword(keyword) {
  1085. var token = lookahead();
  1086. return token.type === Token.Keyword && token.value === keyword;
  1087. }
  1088. // Return true if the next token is an assignment operator
  1089. function matchAssign() {
  1090. var token = lookahead(),
  1091. op = token.value;
  1092. if (token.type !== Token.Punctuator) {
  1093. return false;
  1094. }
  1095. return op === '=' ||
  1096. op === '*=' ||
  1097. op === '/=' ||
  1098. op === '%=' ||
  1099. op === '+=' ||
  1100. op === '-=' ||
  1101. op === '<<=' ||
  1102. op === '>>=' ||
  1103. op === '>>>=' ||
  1104. op === '&=' ||
  1105. op === '^=' ||
  1106. op === '|=';
  1107. }
  1108. function consumeSemicolon() {
  1109. var token, line;
  1110. // Catch the very common case first.
  1111. if (source[index] === ';') {
  1112. lex();
  1113. return;
  1114. }
  1115. line = lineNumber;
  1116. skipComment();
  1117. if (lineNumber !== line) {
  1118. return;
  1119. }
  1120. if (match(';')) {
  1121. lex();
  1122. return;
  1123. }
  1124. token = lookahead();
  1125. if (token.type !== Token.EOF && !match('}')) {
  1126. throwUnexpected(token);
  1127. }
  1128. }
  1129. // Return true if provided expression is LeftHandSideExpression
  1130. function isLeftHandSide(expr) {
  1131. return expr.type === Syntax.Identifier || expr.type === Syntax.MemberExpression;
  1132. }
  1133. // 11.1.4 Array Initialiser
  1134. function parseArrayInitialiser() {
  1135. var elements = [];
  1136. expect('[');
  1137. while (!match(']')) {
  1138. if (match(',')) {
  1139. lex();
  1140. elements.push(null);
  1141. } else {
  1142. elements.push(parseAssignmentExpression());
  1143. if (!match(']')) {
  1144. expect(',');
  1145. }
  1146. }
  1147. }
  1148. expect(']');
  1149. return {
  1150. type: Syntax.ArrayExpression,
  1151. elements: elements
  1152. };
  1153. }
  1154. // 11.1.5 Object Initialiser
  1155. function parsePropertyFunction(param, first) {
  1156. var previousStrict, body;
  1157. previousStrict = strict;
  1158. body = parseFunctionSourceElements();
  1159. if (first && strict && isRestrictedWord(param[0].name)) {
  1160. throwErrorTolerant(first, Messages.StrictParamName);
  1161. }
  1162. strict = previousStrict;
  1163. return {
  1164. type: Syntax.FunctionExpression,
  1165. id: null,
  1166. params: param,
  1167. defaults: [],
  1168. body: body,
  1169. rest: null,
  1170. generator: false,
  1171. expression: false
  1172. };
  1173. }
  1174. function parseObjectPropertyKey() {
  1175. var token = lex();
  1176. // Note: This function is called only from parseObjectProperty(), where
  1177. // EOF and Punctuator tokens are already filtered out.
  1178. if (token.type === Token.StringLiteral || token.type === Token.NumericLiteral) {
  1179. if (strict && token.octal) {
  1180. throwErrorTolerant(token, Messages.StrictOctalLiteral);
  1181. }
  1182. return createLiteral(token);
  1183. }
  1184. return {
  1185. type: Syntax.Identifier,
  1186. name: token.value
  1187. };
  1188. }
  1189. function parseObjectProperty() {
  1190. var token, key, id, param;
  1191. token = lookahead();
  1192. if (token.type === Token.Identifier) {
  1193. id = parseObjectPropertyKey();
  1194. // Property Assignment: Getter and Setter.
  1195. if (token.value === 'get' && !match(':')) {
  1196. key = parseObjectPropertyKey();
  1197. expect('(');
  1198. expect(')');
  1199. return {
  1200. type: Syntax.Property,
  1201. key: key,
  1202. value: parsePropertyFunction([]),
  1203. kind: 'get'
  1204. };
  1205. } else if (token.value === 'set' && !match(':')) {
  1206. key = parseObjectPropertyKey();
  1207. expect('(');
  1208. token = lookahead();
  1209. if (token.type !== Token.Identifier) {
  1210. throwUnexpected(lex());
  1211. }
  1212. param = [ parseVariableIdentifier() ];
  1213. expect(')');
  1214. return {
  1215. type: Syntax.Property,
  1216. key: key,
  1217. value: parsePropertyFunction(param, token),
  1218. kind: 'set'
  1219. };
  1220. } else {
  1221. expect(':');
  1222. return {
  1223. type: Syntax.Property,
  1224. key: id,
  1225. value: parseAssignmentExpression(),
  1226. kind: 'init'
  1227. };
  1228. }
  1229. } else if (token.type === Token.EOF || token.type === Token.Punctuator) {
  1230. throwUnexpected(token);
  1231. } else {
  1232. key = parseObjectPropertyKey();
  1233. expect(':');
  1234. return {
  1235. type: Syntax.Property,
  1236. key: key,
  1237. value: parseAssignmentExpression(),
  1238. kind: 'init'
  1239. };
  1240. }
  1241. }
  1242. function parseObjectInitialiser() {
  1243. var properties = [], property, name, kind, map = {}, toString = String;
  1244. expect('{');
  1245. while (!match('}')) {
  1246. property = parseObjectProperty();
  1247. if (property.key.type === Syntax.Identifier) {
  1248. name = property.key.name;
  1249. } else {
  1250. name = toString(property.key.value);
  1251. }
  1252. kind = (property.kind === 'init') ? PropertyKind.Data : (property.kind === 'get') ? PropertyKind.Get : PropertyKind.Set;
  1253. if (Object.prototype.hasOwnProperty.call(map, name)) {
  1254. if (map[name] === PropertyKind.Data) {
  1255. if (strict && kind === PropertyKind.Data) {
  1256. throwErrorTolerant({}, Messages.StrictDuplicateProperty);
  1257. } else if (kind !== PropertyKind.Data) {
  1258. throwErrorTolerant({}, Messages.AccessorDataProperty);
  1259. }
  1260. } else {
  1261. if (kind === PropertyKind.Data) {
  1262. throwErrorTolerant({}, Messages.AccessorDataProperty);
  1263. } else if (map[name] & kind) {
  1264. throwErrorTolerant({}, Messages.AccessorGetSet);
  1265. }
  1266. }
  1267. map[name] |= kind;
  1268. } else {
  1269. map[name] = kind;
  1270. }
  1271. properties.push(property);
  1272. if (!match('}')) {
  1273. expect(',');
  1274. }
  1275. }
  1276. expect('}');
  1277. return {
  1278. type: Syntax.ObjectExpression,
  1279. properties: properties
  1280. };
  1281. }
  1282. // 11.1.6 The Grouping Operator
  1283. function parseGroupExpression() {
  1284. var expr;
  1285. expect('(');
  1286. expr = parseExpression();
  1287. expect(')');
  1288. return expr;
  1289. }
  1290. // 11.1 Primary Expressions
  1291. function parsePrimaryExpression() {
  1292. var token = lookahead(),
  1293. type = token.type;
  1294. if (type === Token.Identifier) {
  1295. return {
  1296. type: Syntax.Identifier,
  1297. name: lex().value
  1298. };
  1299. }
  1300. if (type === Token.StringLiteral || type === Token.NumericLiteral) {
  1301. if (strict && token.octal) {
  1302. throwErrorTolerant(token, Messages.StrictOctalLiteral);
  1303. }
  1304. return createLiteral(lex());
  1305. }
  1306. if (type === Token.Keyword) {
  1307. if (matchKeyword('this')) {
  1308. lex();
  1309. return {
  1310. type: Syntax.ThisExpression
  1311. };
  1312. }
  1313. if (matchKeyword('function')) {
  1314. return parseFunctionExpression();
  1315. }
  1316. }
  1317. if (type === Token.BooleanLiteral) {
  1318. lex();
  1319. token.value = (token.value === 'true');
  1320. return createLiteral(token);
  1321. }
  1322. if (type === Token.NullLiteral) {
  1323. lex();
  1324. token.value = null;
  1325. return createLiteral(token);
  1326. }
  1327. if (match('[')) {
  1328. return parseArrayInitialiser();
  1329. }
  1330. if (match('{')) {
  1331. return parseObjectInitialiser();
  1332. }
  1333. if (match('(')) {
  1334. return parseGroupExpression();
  1335. }
  1336. if (match('/') || match('/=')) {
  1337. return createLiteral(scanRegExp());
  1338. }
  1339. return throwUnexpected(lex());
  1340. }
  1341. // 11.2 Left-Hand-Side Expressions
  1342. function parseArguments() {
  1343. var args = [];
  1344. expect('(');
  1345. if (!match(')')) {
  1346. while (index < length) {
  1347. args.push(parseAssignmentExpression());
  1348. if (match(')')) {
  1349. break;
  1350. }
  1351. expect(',');
  1352. }
  1353. }
  1354. expect(')');
  1355. return args;
  1356. }
  1357. function parseNonComputedProperty() {
  1358. var token = lex();
  1359. if (!isIdentifierName(token)) {
  1360. throwUnexpected(token);
  1361. }
  1362. return {
  1363. type: Syntax.Identifier,
  1364. name: token.value
  1365. };
  1366. }
  1367. function parseNonComputedMember() {
  1368. expect('.');
  1369. return parseNonComputedProperty();
  1370. }
  1371. function parseComputedMember() {
  1372. var expr;
  1373. expect('[');
  1374. expr = parseExpression();
  1375. expect(']');
  1376. return expr;
  1377. }
  1378. function parseNewExpression() {
  1379. var expr;
  1380. expectKeyword('new');
  1381. expr = {
  1382. type: Syntax.NewExpression,
  1383. callee: parseLeftHandSideExpression(),
  1384. 'arguments': []
  1385. };
  1386. if (match('(')) {
  1387. expr['arguments'] = parseArguments();
  1388. }
  1389. return expr;
  1390. }
  1391. function parseLeftHandSideExpressionAllowCall() {
  1392. var expr;
  1393. expr = matchKeyword('new') ? parseNewExpression() : parsePrimaryExpression();
  1394. while (match('.') || match('[') || match('(')) {
  1395. if (match('(')) {
  1396. expr = {
  1397. type: Syntax.CallExpression,
  1398. callee: expr,
  1399. 'arguments': parseArguments()
  1400. };
  1401. } else if (match('[')) {
  1402. expr = {
  1403. type: Syntax.MemberExpression,
  1404. computed: true,
  1405. object: expr,
  1406. property: parseComputedMember()
  1407. };
  1408. } else {
  1409. expr = {
  1410. type: Syntax.MemberExpression,
  1411. computed: false,
  1412. object: expr,
  1413. property: parseNonComputedMember()
  1414. };
  1415. }
  1416. }
  1417. return expr;
  1418. }
  1419. function parseLeftHandSideExpression() {
  1420. var expr;
  1421. expr = matchKeyword('new') ? parseNewExpression() : parsePrimaryExpression();
  1422. while (match('.') || match('[')) {
  1423. if (match('[')) {
  1424. expr = {
  1425. type: Syntax.MemberExpression,
  1426. computed: true,
  1427. object: expr,
  1428. property: parseComputedMember()
  1429. };
  1430. } else {
  1431. expr = {
  1432. type: Syntax.MemberExpression,
  1433. computed: false,
  1434. object: expr,
  1435. property: parseNonComputedMember()
  1436. };
  1437. }
  1438. }
  1439. return expr;
  1440. }
  1441. // 11.3 Postfix Expressions
  1442. function parsePostfixExpression() {
  1443. var expr = parseLeftHandSideExpressionAllowCall(), token;
  1444. token = lookahead();
  1445. if (token.type !== Token.Punctuator) {
  1446. return expr;
  1447. }
  1448. if ((match('++') || match('--')) && !peekLineTerminator()) {
  1449. // 11.3.1, 11.3.2
  1450. if (strict && expr.type === Syntax.Identifier && isRestrictedWord(expr.name)) {
  1451. throwErrorTolerant({}, Messages.StrictLHSPostfix);
  1452. }
  1453. if (!isLeftHandSide(expr)) {
  1454. throwError({}, Messages.InvalidLHSInAssignment);
  1455. }
  1456. expr = {
  1457. type: Syntax.UpdateExpression,
  1458. operator: lex().value,
  1459. argument: expr,
  1460. prefix: false
  1461. };
  1462. }
  1463. return expr;
  1464. }
  1465. // 11.4 Unary Operators
  1466. function parseUnaryExpression() {
  1467. var token, expr;
  1468. token = lookahead();
  1469. if (token.type !== Token.Punctuator && token.type !== Token.Keyword) {
  1470. return parsePostfixExpression();
  1471. }
  1472. if (match('++') || match('--')) {
  1473. token = lex();
  1474. expr = parseUnaryExpression();
  1475. // 11.4.4, 11.4.5
  1476. if (strict && expr.type === Syntax.Identifier && isRestrictedWord(expr.name)) {
  1477. throwErrorTolerant({}, Messages.StrictLHSPrefix);
  1478. }
  1479. if (!isLeftHandSide(expr)) {
  1480. throwError({}, Messages.InvalidLHSInAssignment);
  1481. }
  1482. expr = {
  1483. type: Syntax.UpdateExpression,
  1484. operator: token.value,
  1485. argument: expr,
  1486. prefix: true
  1487. };
  1488. return expr;
  1489. }
  1490. if (match('+') || match('-') || match('~') || match('!')) {
  1491. expr = {
  1492. type: Syntax.UnaryExpression,
  1493. operator: lex().value,
  1494. argument: parseUnaryExpression()
  1495. };
  1496. return expr;
  1497. }
  1498. if (matchKeyword('delete') || matchKeyword('void') || matchKeyword('typeof')) {
  1499. expr = {
  1500. type: Syntax.UnaryExpression,
  1501. operator: lex().value,
  1502. argument: parseUnaryExpression()
  1503. };
  1504. if (strict && expr.operator === 'delete' && expr.argument.type === Syntax.Identifier) {
  1505. throwErrorTolerant({}, Messages.StrictDelete);
  1506. }
  1507. return expr;
  1508. }
  1509. return parsePostfixExpression();
  1510. }
  1511. // 11.5 Multiplicative Operators
  1512. function parseMultiplicativeExpression() {
  1513. var expr = parseUnaryExpression();
  1514. while (match('*') || match('/') || match('%')) {
  1515. expr = {
  1516. type: Syntax.BinaryExpression,
  1517. operator: lex().value,
  1518. left: expr,
  1519. right: parseUnaryExpression()
  1520. };
  1521. }
  1522. return expr;
  1523. }
  1524. // 11.6 Additive Operators
  1525. function parseAdditiveExpression() {
  1526. var expr = parseMultiplicativeExpression();
  1527. while (match('+') || match('-')) {
  1528. expr = {
  1529. type: Syntax.BinaryExpression,
  1530. operator: lex().value,
  1531. left: expr,
  1532. right: parseMultiplicativeExpression()
  1533. };
  1534. }
  1535. return expr;
  1536. }
  1537. // 11.7 Bitwise Shift Operators
  1538. function parseShiftExpression() {
  1539. var expr = parseAdditiveExpression();
  1540. while (match('<<') || match('>>') || match('>>>')) {
  1541. expr = {
  1542. type: Syntax.BinaryExpression,
  1543. operator: lex().value,
  1544. left: expr,
  1545. right: parseAdditiveExpression()
  1546. };
  1547. }
  1548. return expr;
  1549. }
  1550. // 11.8 Relational Operators
  1551. function parseRelationalExpression() {
  1552. var expr, previousAllowIn;
  1553. previousAllowIn = state.allowIn;
  1554. state.allowIn = true;
  1555. expr = parseShiftExpression();
  1556. while (match('<') || match('>') || match('<=') || match('>=') || (previousAllowIn && matchKeyword('in')) || matchKeyword('instanceof')) {
  1557. expr = {
  1558. type: Syntax.BinaryExpression,
  1559. operator: lex().value,
  1560. left: expr,
  1561. right: parseShiftExpression()
  1562. };
  1563. }
  1564. state.allowIn = previousAllowIn;
  1565. return expr;
  1566. }
  1567. // 11.9 Equality Operators
  1568. function parseEqualityExpression() {
  1569. var expr = parseRelationalExpression();
  1570. while (match('==') || match('!=') || match('===') || match('!==')) {
  1571. expr = {
  1572. type: Syntax.BinaryExpression,
  1573. operator: lex().value,
  1574. left: expr,
  1575. right: parseRelationalExpression()
  1576. };
  1577. }
  1578. return expr;
  1579. }
  1580. // 11.10 Binary Bitwise Operators
  1581. function parseBitwiseANDExpression() {
  1582. var expr = parseEqualityExpression();
  1583. while (match('&')) {
  1584. lex();
  1585. expr = {
  1586. type: Syntax.BinaryExpression,
  1587. operator: '&',
  1588. left: expr,
  1589. right: parseEqualityExpression()
  1590. };
  1591. }
  1592. return expr;
  1593. }
  1594. function parseBitwiseXORExpression() {
  1595. var expr = parseBitwiseANDExpression();
  1596. while (match('^')) {
  1597. lex();
  1598. expr = {
  1599. type: Syntax.BinaryExpression,
  1600. operator: '^',
  1601. left: expr,
  1602. right: parseBitwiseANDExpression()
  1603. };
  1604. }
  1605. return expr;
  1606. }
  1607. function parseBitwiseORExpression() {
  1608. var expr = parseBitwiseXORExpression();
  1609. while (match('|')) {
  1610. lex();
  1611. expr = {
  1612. type: Syntax.BinaryExpression,
  1613. operator: '|',
  1614. left: expr,
  1615. right: parseBitwiseXORExpression()
  1616. };
  1617. }
  1618. return expr;
  1619. }
  1620. // 11.11 Binary Logical Operators
  1621. function parseLogicalANDExpression() {
  1622. var expr = parseBitwiseORExpression();
  1623. while (match('&&')) {
  1624. lex();
  1625. expr = {
  1626. type: Syntax.LogicalExpression,
  1627. operator: '&&',
  1628. left: expr,
  1629. right: parseBitwiseORExpression()
  1630. };
  1631. }
  1632. return expr;
  1633. }
  1634. function parseLogicalORExpression() {
  1635. var expr = parseLogicalANDExpression();
  1636. while (match('||')) {
  1637. lex();
  1638. expr = {
  1639. type: Syntax.LogicalExpression,
  1640. operator: '||',
  1641. left: expr,
  1642. right: parseLogicalANDExpression()
  1643. };
  1644. }
  1645. return expr;
  1646. }
  1647. // 11.12 Conditional Operator
  1648. function parseConditionalExpression() {
  1649. var expr, previousAllowIn, consequent;
  1650. expr = parseLogicalORExpression();
  1651. if (match('?')) {
  1652. lex();
  1653. previousAllowIn = state.allowIn;
  1654. state.allowIn = true;
  1655. consequent = parseAssignmentExpression();
  1656. state.allowIn = previousAllowIn;
  1657. expect(':');
  1658. expr = {
  1659. type: Syntax.ConditionalExpression,
  1660. test: expr,
  1661. consequent: consequent,
  1662. alternate: parseAssignmentExpression()
  1663. };
  1664. }
  1665. return expr;
  1666. }
  1667. // 11.13 Assignment Operators
  1668. function parseAssignmentExpression() {
  1669. var token, expr;
  1670. token = lookahead();
  1671. expr = parseConditionalExpression();
  1672. if (matchAssign()) {
  1673. // LeftHandSideExpression
  1674. if (!isLeftHandSide(expr)) {
  1675. throwError({}, Messages.InvalidLHSInAssignment);
  1676. }
  1677. // 11.13.1
  1678. if (strict && expr.type === Syntax.Identifier && isRestrictedWord(expr.name)) {
  1679. throwErrorTolerant(token, Messages.StrictLHSAssignment);
  1680. }
  1681. expr = {
  1682. type: Syntax.AssignmentExpression,
  1683. operator: lex().value,
  1684. left: expr,
  1685. right: parseAssignmentExpression()
  1686. };
  1687. }
  1688. return expr;
  1689. }
  1690. // 11.14 Comma Operator
  1691. function parseExpression() {
  1692. var expr = parseAssignmentExpression();
  1693. if (match(',')) {
  1694. expr = {
  1695. type: Syntax.SequenceExpression,
  1696. expressions: [ expr ]
  1697. };
  1698. while (index < length) {
  1699. if (!match(',')) {
  1700. break;
  1701. }
  1702. lex();
  1703. expr.expressions.push(parseAssignmentExpression());
  1704. }
  1705. }
  1706. return expr;
  1707. }
  1708. // 12.1 Block
  1709. function parseStatementList() {
  1710. var list = [],
  1711. statement;
  1712. while (index < length) {
  1713. if (match('}')) {
  1714. break;
  1715. }
  1716. statement = parseSourceElement();
  1717. if (typeof statement === 'undefined') {
  1718. break;
  1719. }
  1720. list.push(statement);
  1721. }
  1722. return list;
  1723. }
  1724. function parseBlock() {
  1725. var block;
  1726. expect('{');
  1727. block = parseStatementList();
  1728. expect('}');
  1729. return {
  1730. type: Syntax.BlockStatement,
  1731. body: block
  1732. };
  1733. }
  1734. // 12.2 Variable Statement
  1735. function parseVariableIdentifier() {
  1736. var token = lex();
  1737. if (token.type !== Token.Identifier) {
  1738. throwUnexpected(token);
  1739. }
  1740. return {
  1741. type: Syntax.Identifier,
  1742. name: token.value
  1743. };
  1744. }
  1745. function parseVariableDeclaration(kind) {
  1746. var id = parseVariableIdentifier(),
  1747. init = null;
  1748. // 12.2.1
  1749. if (strict && isRestrictedWord(id.name)) {
  1750. throwErrorTolerant({}, Messages.StrictVarName);
  1751. }
  1752. if (kind === 'const') {
  1753. expect('=');
  1754. init = parseAssignmentExpression();
  1755. } else if (match('=')) {
  1756. lex();
  1757. init = parseAssignmentExpression();
  1758. }
  1759. return {
  1760. type: Syntax.VariableDeclarator,
  1761. id: id,
  1762. init: init
  1763. };
  1764. }
  1765. function parseVariableDeclarationList(kind) {
  1766. var list = [];
  1767. while (index < length) {
  1768. list.push(parseVariableDeclaration(kind));
  1769. if (!match(',')) {
  1770. break;
  1771. }
  1772. lex();
  1773. }
  1774. return list;
  1775. }
  1776. function parseVariableStatement() {
  1777. var declarations;
  1778. expectKeyword('var');
  1779. declarations = parseVariableDeclarationList();
  1780. consumeSemicolon();
  1781. return {
  1782. type: Syntax.VariableDeclaration,
  1783. declarations: declarations,
  1784. kind: 'var'
  1785. };
  1786. }
  1787. // kind may be `const` or `let`
  1788. // Both are experimental and not in the specification yet.
  1789. // see http://wiki.ecmascript.org/doku.php?id=harmony:const
  1790. // and http://wiki.ecmascript.org/doku.php?id=harmony:let
  1791. function parseConstLetDeclaration(kind) {
  1792. var declarations;
  1793. expectKeyword(kind);
  1794. declarations = parseVariableDeclarationList(kind);
  1795. consumeSemicolon();
  1796. return {
  1797. type: Syntax.VariableDeclaration,
  1798. declarations: declarations,
  1799. kind: kind
  1800. };
  1801. }
  1802. // 12.3 Empty Statement
  1803. function parseEmptyStatement() {
  1804. expect(';');
  1805. return {
  1806. type: Syntax.EmptyStatement
  1807. };
  1808. }
  1809. // 12.4 Expression Statement
  1810. function parseExpressionStatement() {
  1811. var expr = parseExpression();
  1812. consumeSemicolon();
  1813. return {
  1814. type: Syntax.ExpressionStatement,
  1815. expression: expr
  1816. };
  1817. }
  1818. // 12.5 If statement
  1819. function parseIfStatement() {
  1820. var test, consequent, alternate;
  1821. expectKeyword('if');
  1822. expect('(');
  1823. test = parseExpression();
  1824. expect(')');
  1825. consequent = parseStatement();
  1826. if (matchKeyword('else')) {
  1827. lex();
  1828. alternate = parseStatement();
  1829. } else {
  1830. alternate = null;
  1831. }
  1832. return {
  1833. type: Syntax.IfStatement,
  1834. test: test,
  1835. consequent: consequent,
  1836. alternate: alternate
  1837. };
  1838. }
  1839. // 12.6 Iteration Statements
  1840. function parseDoWhileStatement() {
  1841. var body, test, oldInIteration;
  1842. expectKeyword('do');
  1843. oldInIteration = state.inIteration;
  1844. state.inIteration = true;
  1845. body = parseStatement();
  1846. state.inIteration = oldInIteration;
  1847. expectKeyword('while');
  1848. expect('(');
  1849. test = parseExpression();
  1850. expect(')');
  1851. if (match(';')) {
  1852. lex();
  1853. }
  1854. return {
  1855. type: Syntax.DoWhileStatement,
  1856. body: body,
  1857. test: test
  1858. };
  1859. }
  1860. function parseWhileStatement() {
  1861. var test, body, oldInIteration;
  1862. expectKeyword('while');
  1863. expect('(');
  1864. test = parseExpression();
  1865. expect(')');
  1866. oldInIteration = state.inIteration;
  1867. state.inIteration = true;
  1868. body = parseStatement();
  1869. state.inIteration = oldInIteration;
  1870. return {
  1871. type: Syntax.WhileStatement,
  1872. test: test,
  1873. body: body
  1874. };
  1875. }
  1876. function parseForVariableDeclaration() {
  1877. var token = lex();
  1878. return {
  1879. type: Syntax.VariableDeclaration,
  1880. declarations: parseVariableDeclarationList(),
  1881. kind: token.value
  1882. };
  1883. }
  1884. function parseForStatement() {
  1885. var init, test, update, left, right, body, oldInIteration;
  1886. init = test = update = null;
  1887. expectKeyword('for');
  1888. expect('(');
  1889. if (match(';')) {
  1890. lex();
  1891. } else {
  1892. if (matchKeyword('var') || matchKeyword('let')) {
  1893. state.allowIn = false;
  1894. init = parseForVariableDeclaration();
  1895. state.allowIn = true;
  1896. if (init.declarations.length === 1 && matchKeyword('in')) {
  1897. lex();
  1898. left = init;
  1899. right = parseExpression();
  1900. init = null;
  1901. }
  1902. } else {
  1903. state.allowIn = false;
  1904. init = parseExpression();
  1905. state.allowIn = true;
  1906. if (matchKeyword('in')) {
  1907. // LeftHandSideExpression
  1908. if (!isLeftHandSide(init)) {
  1909. throwError({}, Messages.InvalidLHSInForIn);
  1910. }
  1911. lex();
  1912. left = init;
  1913. right = parseExpression();
  1914. init = null;
  1915. }
  1916. }
  1917. if (typeof left === 'undefined') {
  1918. expect(';');
  1919. }
  1920. }
  1921. if (typeof left === 'undefined') {
  1922. if (!match(';')) {
  1923. test = parseExpression();
  1924. }
  1925. expect(';');
  1926. if (!match(')')) {
  1927. update = parseExpression();
  1928. }
  1929. }
  1930. expect(')');
  1931. oldInIteration = state.inIteration;
  1932. state.inIteration = true;
  1933. body = parseStatement();
  1934. state.inIteration = oldInIteration;
  1935. if (typeof left === 'undefined') {
  1936. return {
  1937. type: Syntax.ForStatement,
  1938. init: init,
  1939. test: test,
  1940. update: update,
  1941. body: body
  1942. };
  1943. }
  1944. return {
  1945. type: Syntax.ForInStatement,
  1946. left: left,
  1947. right: right,
  1948. body: body,
  1949. each: false
  1950. };
  1951. }
  1952. // 12.7 The continue statement
  1953. function parseContinueStatement() {
  1954. var token, label = null;
  1955. expectKeyword('continue');
  1956. // Optimize the most common form: 'continue;'.
  1957. if (source[index] === ';') {
  1958. lex();
  1959. if (!state.inIteration) {
  1960. throwError({}, Messages.IllegalContinue);
  1961. }
  1962. return {
  1963. type: Syntax.ContinueStatement,
  1964. label: null
  1965. };
  1966. }
  1967. if (peekLineTerminator()) {
  1968. if (!state.inIteration) {
  1969. throwError({}, Messages.IllegalContinue);
  1970. }
  1971. return {
  1972. type: Syntax.ContinueStatement,
  1973. label: null
  1974. };
  1975. }
  1976. token = lookahead();
  1977. if (token.type === Token.Identifier) {
  1978. label = parseVariableIdentifier();
  1979. if (!Object.prototype.hasOwnProperty.call(state.labelSet, label.name)) {
  1980. throwError({}, Messages.UnknownLabel, label.name);
  1981. }
  1982. }
  1983. consumeSemicolon();
  1984. if (label === null && !state.inIteration) {
  1985. throwError({}, Messages.IllegalContinue);
  1986. }
  1987. return {
  1988. type: Syntax.ContinueStatement,
  1989. label: label
  1990. };
  1991. }
  1992. // 12.8 The break statement
  1993. function parseBreakStatement() {
  1994. var token, label = null;
  1995. expectKeyword('break');
  1996. // Optimize the most common form: 'break;'.
  1997. if (source[index] === ';') {
  1998. lex();
  1999. if (!(state.inIteration || state.inSwitch)) {
  2000. throwError({}, Messages.IllegalBreak);
  2001. }
  2002. return {
  2003. type: Syntax.BreakStatement,
  2004. label: null
  2005. };
  2006. }
  2007. if (peekLineTerminator()) {
  2008. if (!(state.inIteration || state.inSwitch)) {
  2009. throwError({}, Messages.IllegalBreak);
  2010. }
  2011. return {
  2012. type: Syntax.BreakStatement,
  2013. label: null
  2014. };
  2015. }
  2016. token = lookahead();
  2017. if (token.type === Token.Identifier) {
  2018. label = parseVariableIdentifier();
  2019. if (!Object.prototype.hasOwnProperty.call(state.labelSet, label.name)) {
  2020. throwError({}, Messages.UnknownLabel, label.name);
  2021. }
  2022. }
  2023. consumeSemicolon();
  2024. if (label === null && !(state.inIteration || state.inSwitch)) {
  2025. throwError({}, Messages.IllegalBreak);
  2026. }
  2027. return {
  2028. type: Syntax.BreakStatement,
  2029. label: label
  2030. };
  2031. }
  2032. // 12.9 The return statement
  2033. function parseReturnStatement() {
  2034. var token, argument = null;
  2035. expectKeyword('return');
  2036. if (!state.inFunctionBody) {
  2037. throwErrorTolerant({}, Messages.IllegalReturn);
  2038. }
  2039. // 'return' followed by a space and an identifier is very common.
  2040. if (source[index] === ' ') {
  2041. if (isIdentifierStart(source[index + 1])) {
  2042. argument = parseExpression();
  2043. consumeSemicolon();
  2044. return {
  2045. type: Syntax.ReturnStatement,
  2046. argument: argument
  2047. };
  2048. }
  2049. }
  2050. if (peekLineTerminator()) {
  2051. return {
  2052. type: Syntax.ReturnStatement,
  2053. argument: null
  2054. };
  2055. }
  2056. if (!match(';')) {
  2057. token = lookahead();
  2058. if (!match('}') && token.type !== Token.EOF) {
  2059. argument = parseExpression();
  2060. }
  2061. }
  2062. consumeSemicolon();
  2063. return {
  2064. type: Syntax.ReturnStatement,
  2065. argument: argument
  2066. };
  2067. }
  2068. // 12.10 The with statement
  2069. function parseWithStatement() {
  2070. var object, body;
  2071. if (strict) {
  2072. throwErrorTolerant({}, Messages.StrictModeWith);
  2073. }
  2074. expectKeyword('with');
  2075. expect('(');
  2076. object = parseExpression();
  2077. expect(')');
  2078. body = parseStatement();
  2079. return {
  2080. type: Syntax.WithStatement,
  2081. object: object,
  2082. body: body
  2083. };
  2084. }
  2085. // 12.10 The swith statement
  2086. function parseSwitchCase() {
  2087. var test,
  2088. consequent = [],
  2089. statement;
  2090. if (matchKeyword('default')) {
  2091. lex();
  2092. test = null;
  2093. } else {
  2094. expectKeyword('case');
  2095. test = parseExpression();
  2096. }
  2097. expect(':');
  2098. while (index < length) {
  2099. if (match('}') || matchKeyword('default') || matchKeyword('case')) {
  2100. break;
  2101. }
  2102. statement = parseStatement();
  2103. if (typeof statement === 'undefined') {
  2104. break;
  2105. }
  2106. consequent.push(statement);
  2107. }
  2108. return {
  2109. type: Syntax.SwitchCase,
  2110. test: test,
  2111. consequent: consequent
  2112. };
  2113. }
  2114. function parseSwitchStatement() {
  2115. var discriminant, cases, clause, oldInSwitch, defaultFound;
  2116. expectKeyword('switch');
  2117. expect('(');
  2118. discriminant = parseExpression();
  2119. expect(')');
  2120. expect('{');
  2121. if (match('}')) {
  2122. lex();
  2123. return {
  2124. type: Syntax.SwitchStatement,
  2125. discriminant: discriminant
  2126. };
  2127. }
  2128. cases = [];
  2129. oldInSwitch = state.inSwitch;
  2130. state.inSwitch = true;
  2131. defaultFound = false;
  2132. while (index < length) {
  2133. if (match('}')) {
  2134. break;
  2135. }
  2136. clause = parseSwitchCase();
  2137. if (clause.test === null) {
  2138. if (defaultFound) {
  2139. throwError({}, Messages.MultipleDefaultsInSwitch);
  2140. }
  2141. defaultFound = true;
  2142. }
  2143. cases.push(clause);
  2144. }
  2145. state.inSwitch = oldInSwitch;
  2146. expect('}');
  2147. return {
  2148. type: Syntax.SwitchStatement,
  2149. discriminant: discriminant,
  2150. cases: cases
  2151. };
  2152. }
  2153. // 12.13 The throw statement
  2154. function parseThrowStatement() {
  2155. var argument;
  2156. expectKeyword('throw');
  2157. if (peekLineTerminator()) {
  2158. throwError({}, Messages.NewlineAfterThrow);
  2159. }
  2160. argument = parseExpression();
  2161. consumeSemicolon();
  2162. return {
  2163. type: Syntax.ThrowStatement,
  2164. argument: argument
  2165. };
  2166. }
  2167. // 12.14 The try statement
  2168. function parseCatchClause() {
  2169. var param;
  2170. expectKeyword('catch');
  2171. expect('(');
  2172. if (!match(')')) {
  2173. param = parseExpression();
  2174. // 12.14.1
  2175. if (strict && param.type === Syntax.Identifier && isRestrictedWord(param.name)) {
  2176. throwErrorTolerant({}, Messages.StrictCatchVariable);
  2177. }
  2178. }
  2179. expect(')');
  2180. return {
  2181. type: Syntax.CatchClause,
  2182. param: param,
  2183. body: parseBlock()
  2184. };
  2185. }
  2186. function parseTryStatement() {
  2187. var block, handlers = [], finalizer = null;
  2188. expectKeyword('try');
  2189. block = parseBlock();
  2190. if (matchKeyword('catch')) {
  2191. handlers.push(parseCatchClause());
  2192. }
  2193. if (matchKeyword('finally')) {
  2194. lex();
  2195. finalizer = parseBlock();
  2196. }
  2197. if (handlers.length === 0 && !finalizer) {
  2198. throwError({}, Messages.NoCatchOrFinally);
  2199. }
  2200. return {
  2201. type: Syntax.TryStatement,
  2202. block: block,
  2203. guardedHandlers: [],
  2204. handlers: handlers,
  2205. finalizer: finalizer
  2206. };
  2207. }
  2208. // 12.15 The debugger statement
  2209. function parseDebuggerStatement() {
  2210. expectKeyword('debugger');
  2211. consumeSemicolon();
  2212. return {
  2213. type: Syntax.DebuggerStatement
  2214. };
  2215. }
  2216. // 12 Statements
  2217. function parseStatement() {
  2218. var token = lookahead(),
  2219. expr,
  2220. labeledBody;
  2221. if (token.type === Token.EOF) {
  2222. throwUnexpected(token);
  2223. }
  2224. if (token.type === Token.Punctuator) {
  2225. switch (token.value) {
  2226. case ';':
  2227. return parseEmptyStatement();
  2228. case '{':
  2229. return parseBlock();
  2230. case '(':
  2231. return parseExpressionStatement();
  2232. default:
  2233. break;
  2234. }
  2235. }
  2236. if (token.type === Token.Keyword) {
  2237. switch (token.value) {
  2238. case 'break':
  2239. return parseBreakStatement();
  2240. case 'continue':
  2241. return parseContinueStatement();
  2242. case 'debugger':
  2243. return parseDebuggerStatement();
  2244. case 'do':
  2245. return parseDoWhileStatement();
  2246. case 'for':
  2247. return parseForStatement();
  2248. case 'function':
  2249. return parseFunctionDeclaration();
  2250. case 'if':
  2251. return parseIfStatement();
  2252. case 'return':
  2253. return parseReturnStatement();
  2254. case 'switch':
  2255. return parseSwitchStatement();
  2256. case 'throw':
  2257. return parseThrowStatement();
  2258. case 'try':
  2259. return parseTryStatement();
  2260. case 'var':
  2261. return parseVariableStatement();
  2262. case 'while':
  2263. return parseWhileStatement();
  2264. case 'with':
  2265. return parseWithStatement();
  2266. default:
  2267. break;
  2268. }
  2269. }
  2270. expr = parseExpression();
  2271. // 12.12 Labelled Statements
  2272. if ((expr.type === Syntax.Identifier) && match(':')) {
  2273. lex();
  2274. if (Object.prototype.hasOwnProperty.call(state.labelSet, expr.name)) {
  2275. throwError({}, Messages.Redeclaration, 'Label', expr.name);
  2276. }
  2277. state.labelSet[expr.name] = true;
  2278. labeledBody = parseStatement();
  2279. delete state.labelSet[expr.name];
  2280. return {
  2281. type: Syntax.LabeledStatement,
  2282. label: expr,
  2283. body: labeledBody
  2284. };
  2285. }
  2286. consumeSemicolon();
  2287. return {
  2288. type: Syntax.ExpressionStatement,
  2289. expression: expr
  2290. };
  2291. }
  2292. // 13 Function Definition
  2293. function parseFunctionSourceElements() {
  2294. var sourceElement, sourceElements = [], token, directive, firstRestricted,
  2295. oldLabelSet, oldInIteration, oldInSwitch, oldInFunctionBody;
  2296. expect('{');
  2297. while (index < length) {
  2298. token = lookahead();
  2299. if (token.type !== Token.StringLiteral) {
  2300. break;
  2301. }
  2302. sourceElement = parseSourceElement();
  2303. sourceElements.push(sourceElement);
  2304. if (sourceElement.expression.type !== Syntax.Literal) {
  2305. // this is not directive
  2306. break;
  2307. }
  2308. directive = sliceSource(token.range[0] + 1, token.range[1] - 1);
  2309. if (directive === 'use strict') {
  2310. strict = true;
  2311. if (firstRestricted) {
  2312. throwErrorTolerant(firstRestricted, Messages.StrictOctalLiteral);
  2313. }
  2314. } else {
  2315. if (!firstRestricted && token.octal) {
  2316. firstRestricted = token;
  2317. }
  2318. }
  2319. }
  2320. oldLabelSet = state.labelSet;
  2321. oldInIteration = state.inIteration;
  2322. oldInSwitch = state.inSwitch;
  2323. oldInFunctionBody = state.inFunctionBody;
  2324. state.labelSet = {};
  2325. state.inIteration = false;
  2326. state.inSwitch = false;
  2327. state.inFunctionBody = true;
  2328. while (index < length) {
  2329. if (match('}')) {
  2330. break;
  2331. }
  2332. sourceElement = parseSourceElement();
  2333. if (typeof sourceElement === 'undefined') {
  2334. break;
  2335. }
  2336. sourceElements.push(sourceElement);
  2337. }
  2338. expect('}');
  2339. state.labelSet = oldLabelSet;
  2340. state.inIteration = oldInIteration;
  2341. state.inSwitch = oldInSwitch;
  2342. state.inFunctionBody = oldInFunctionBody;
  2343. return {
  2344. type: Syntax.BlockStatement,
  2345. body: sourceElements
  2346. };
  2347. }
  2348. function parseFunctionDeclaration() {
  2349. var id, param, params = [], body, token, stricted, firstRestricted, message, previousStrict, paramSet;
  2350. expectKeyword('function');
  2351. token = lookahead();
  2352. id = parseVariableIdentifier();
  2353. if (strict) {
  2354. if (isRestrictedWord(token.value)) {
  2355. throwErrorTolerant(token, Messages.StrictFunctionName);
  2356. }
  2357. } else {
  2358. if (isRestrictedWord(token.value)) {
  2359. firstRestricted = token;
  2360. message = Messages.StrictFunctionName;
  2361. } else if (isStrictModeReservedWord(token.value)) {
  2362. firstRestricted = token;
  2363. message = Messages.StrictReservedWord;
  2364. }
  2365. }
  2366. expect('(');
  2367. if (!match(')')) {
  2368. paramSet = {};
  2369. while (index < length) {
  2370. token = lookahead();
  2371. param = parseVariableIdentifier();
  2372. if (strict) {
  2373. if (isRestrictedWord(token.value)) {
  2374. stricted = token;
  2375. message = Messages.StrictParamName;
  2376. }
  2377. if (Object.prototype.hasOwnProperty.call(paramSet, token.value)) {
  2378. stricted = token;
  2379. message = Messages.StrictParamDupe;
  2380. }
  2381. } else if (!firstRestricted) {
  2382. if (isRestrictedWord(token.value)) {
  2383. firstRestricted = token;
  2384. message = Messages.StrictParamName;
  2385. } else if (isStrictModeReservedWord(token.value)) {
  2386. firstRestricted = token;
  2387. message = Messages.StrictReservedWord;
  2388. } else if (Object.prototype.hasOwnProperty.call(paramSet, token.value)) {
  2389. firstRestricted = token;
  2390. message = Messages.StrictParamDupe;
  2391. }
  2392. }
  2393. params.push(param);
  2394. paramSet[param.name] = true;
  2395. if (match(')')) {
  2396. break;
  2397. }
  2398. expect(',');
  2399. }
  2400. }
  2401. expect(')');
  2402. previousStrict = strict;
  2403. body = parseFunctionSourceElements();
  2404. if (strict && firstRestricted) {
  2405. throwError(firstRestricted, message);
  2406. }
  2407. if (strict && stricted) {
  2408. throwErrorTolerant(stricted, message);
  2409. }
  2410. strict = previousStrict;
  2411. return {
  2412. type: Syntax.FunctionDeclaration,
  2413. id: id,
  2414. params: params,
  2415. defaults: [],
  2416. body: body,
  2417. rest: null,
  2418. generator: false,
  2419. expression: false
  2420. };
  2421. }
  2422. function parseFunctionExpression() {
  2423. var token, id = null, stricted, firstRestricted, message, param, params = [], body, previousStrict, paramSet;
  2424. expectKeyword('function');
  2425. if (!match('(')) {
  2426. token = lookahead();
  2427. id = parseVariableIdentifier();
  2428. if (strict) {
  2429. if (isRestrictedWord(token.value)) {
  2430. throwErrorTolerant(token, Messages.StrictFunctionName);
  2431. }
  2432. } else {
  2433. if (isRestrictedWord(token.value)) {
  2434. firstRestricted = token;
  2435. message = Messages.StrictFunctionName;
  2436. } else if (isStrictModeReservedWord(token.value)) {
  2437. firstRestricted = token;
  2438. message = Messages.StrictReservedWord;
  2439. }
  2440. }
  2441. }
  2442. expect('(');
  2443. if (!match(')')) {
  2444. paramSet = {};
  2445. while (index < length) {
  2446. token = lookahead();
  2447. param = parseVariableIdentifier();
  2448. if (strict) {
  2449. if (isRestrictedWord(token.value)) {
  2450. stricted = token;
  2451. message = Messages.StrictParamName;
  2452. }
  2453. if (Object.prototype.hasOwnProperty.call(paramSet, token.value)) {
  2454. stricted = token;
  2455. message = Messages.StrictParamDupe;
  2456. }
  2457. } else if (!firstRestricted) {
  2458. if (isRestrictedWord(token.value)) {
  2459. firstRestricted = token;
  2460. message = Messages.StrictParamName;
  2461. } else if (isStrictModeReservedWord(token.value)) {
  2462. firstRestricted = token;
  2463. message = Messages.StrictReservedWord;
  2464. } else if (Object.prototype.hasOwnProperty.call(paramSet, token.value)) {
  2465. firstRestricted = token;
  2466. message = Messages.StrictParamDupe;
  2467. }
  2468. }
  2469. params.push(param);
  2470. paramSet[param.name] = true;
  2471. if (match(')')) {
  2472. break;
  2473. }
  2474. expect(',');
  2475. }
  2476. }
  2477. expect(')');
  2478. previousStrict = strict;
  2479. body = parseFunctionSourceElements();
  2480. if (strict && firstRestricted) {
  2481. throwError(firstRestricted, message);
  2482. }
  2483. if (strict && stricted) {
  2484. throwErrorTolerant(stricted, message);
  2485. }
  2486. strict = previousStrict;
  2487. return {
  2488. type: Syntax.FunctionExpression,
  2489. id: id,
  2490. params: params,
  2491. defaults: [],
  2492. body: body,
  2493. rest: null,
  2494. generator: false,
  2495. expression: false
  2496. };
  2497. }
  2498. // 14 Program
  2499. function parseSourceElement() {
  2500. var token = lookahead();
  2501. if (token.type === Token.Keyword) {
  2502. switch (token.value) {
  2503. case 'const':
  2504. case 'let':
  2505. return parseConstLetDeclaration(token.value);
  2506. case 'function':
  2507. return parseFunctionDeclaration();
  2508. default:
  2509. return parseStatement();
  2510. }
  2511. }
  2512. if (token.type !== Token.EOF) {
  2513. return parseStatement();
  2514. }
  2515. }
  2516. function parseSourceElements() {
  2517. var sourceElement, sourceElements = [], token, directive, firstRestricted;
  2518. while (index < length) {
  2519. token = lookahead();
  2520. if (token.type !== Token.StringLiteral) {
  2521. break;
  2522. }
  2523. sourceElement = parseSourceElement();
  2524. sourceElements.push(sourceElement);
  2525. if (sourceElement.expression.type !== Syntax.Literal) {
  2526. // this is not directive
  2527. break;
  2528. }
  2529. directive = sliceSource(token.range[0] + 1, token.range[1] - 1);
  2530. if (directive === 'use strict') {
  2531. strict = true;
  2532. if (firstRestricted) {
  2533. throwErrorTolerant(firstRestricted, Messages.StrictOctalLiteral);
  2534. }
  2535. } else {
  2536. if (!firstRestricted && token.octal) {
  2537. firstRestricted = token;
  2538. }
  2539. }
  2540. }
  2541. while (index < length) {
  2542. sourceElement = parseSourceElement();
  2543. if (typeof sourceElement === 'undefined') {
  2544. break;
  2545. }
  2546. sourceElements.push(sourceElement);
  2547. }
  2548. return sourceElements;
  2549. }
  2550. function parseProgram() {
  2551. var program;
  2552. strict = false;
  2553. program = {
  2554. type: Syntax.Program,
  2555. body: parseSourceElements()
  2556. };
  2557. return program;
  2558. }
  2559. // The following functions are needed only when the option to preserve
  2560. // the comments is active.
  2561. function addComment(type, value, start, end, loc) {
  2562. assert(typeof start === 'number', 'Comment must have valid position');
  2563. // Because the way the actual token is scanned, often the comments
  2564. // (if any) are skipped twice during the lexical analysis.
  2565. // Thus, we need to skip adding a comment if the comment array already
  2566. // handled it.
  2567. if (extra.comments.length > 0) {
  2568. if (extra.comments[extra.comments.length - 1].range[1] > start) {
  2569. return;
  2570. }
  2571. }
  2572. extra.comments.push({
  2573. type: type,
  2574. value: value,
  2575. range: [start, end],
  2576. loc: loc
  2577. });
  2578. }
  2579. function scanComment() {
  2580. var comment, ch, loc, start, blockComment, lineComment;
  2581. comment = '';
  2582. blockComment = false;
  2583. lineComment = false;
  2584. while (index < length) {
  2585. ch = source[index];
  2586. if (lineComment) {
  2587. ch = source[index++];
  2588. if (isLineTerminator(ch)) {
  2589. loc.end = {
  2590. line: lineNumber,
  2591. column: index - lineStart - 1
  2592. };
  2593. lineComment = false;
  2594. addComment('Line', comment, start, index - 1, loc);
  2595. if (ch === '\r' && source[index] === '\n') {
  2596. ++index;
  2597. }
  2598. ++lineNumber;
  2599. lineStart = index;
  2600. comment = '';
  2601. } else if (index >= length) {
  2602. lineComment = false;
  2603. comment += ch;
  2604. loc.end = {
  2605. line: lineNumber,
  2606. column: length - lineStart
  2607. };
  2608. addComment('Line', comment, start, length, loc);
  2609. } else {
  2610. comment += ch;
  2611. }
  2612. } else if (blockComment) {
  2613. if (isLineTerminator(ch)) {
  2614. if (ch === '\r' && source[index + 1] === '\n') {
  2615. ++index;
  2616. comment += '\r\n';
  2617. } else {
  2618. comment += ch;
  2619. }
  2620. ++lineNumber;
  2621. ++index;
  2622. lineStart = index;
  2623. if (index >= length) {
  2624. throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
  2625. }
  2626. } else {
  2627. ch = source[index++];
  2628. if (index >= length) {
  2629. throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
  2630. }
  2631. comment += ch;
  2632. if (ch === '*') {
  2633. ch = source[index];
  2634. if (ch === '/') {
  2635. comment = comment.substr(0, comment.length - 1);
  2636. blockComment = false;
  2637. ++index;
  2638. loc.end = {
  2639. line: lineNumber,
  2640. column: index - lineStart
  2641. };
  2642. addComment('Block', comment, start, index, loc);
  2643. comment = '';
  2644. }
  2645. }
  2646. }
  2647. } else if (ch === '/') {
  2648. ch = source[index + 1];
  2649. if (ch === '/') {
  2650. loc = {
  2651. start: {
  2652. line: lineNumber,
  2653. column: index - lineStart
  2654. }
  2655. };
  2656. start = index;
  2657. index += 2;
  2658. lineComment = true;
  2659. if (index >= length) {
  2660. loc.end = {
  2661. line: lineNumber,
  2662. column: index - lineStart
  2663. };
  2664. lineComment = false;
  2665. addComment('Line', comment, start, index, loc);
  2666. }
  2667. } else if (ch === '*') {
  2668. start = index;
  2669. index += 2;
  2670. blockComment = true;
  2671. loc = {
  2672. start: {
  2673. line: lineNumber,
  2674. column: index - lineStart - 2
  2675. }
  2676. };
  2677. if (index >= length) {
  2678. throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
  2679. }
  2680. } else {
  2681. break;
  2682. }
  2683. } else if (isWhiteSpace(ch)) {
  2684. ++index;
  2685. } else if (isLineTerminator(ch)) {
  2686. ++index;
  2687. if (ch === '\r' && source[index] === '\n') {
  2688. ++index;
  2689. }
  2690. ++lineNumber;
  2691. lineStart = index;
  2692. } else {
  2693. break;
  2694. }
  2695. }
  2696. }
  2697. function filterCommentLocation() {
  2698. var i, entry, comment, comments = [];
  2699. for (i = 0; i < extra.comments.length; ++i) {
  2700. entry = extra.comments[i];
  2701. comment = {
  2702. type: entry.type,
  2703. value: entry.value
  2704. };
  2705. if (extra.range) {
  2706. comment.range = entry.range;
  2707. }
  2708. if (extra.loc) {
  2709. comment.loc = entry.loc;
  2710. }
  2711. comments.push(comment);
  2712. }
  2713. extra.comments = comments;
  2714. }
  2715. function collectToken() {
  2716. var start, loc, token, range, value;
  2717. skipComment();
  2718. start = index;
  2719. loc = {
  2720. start: {
  2721. line: lineNumber,
  2722. column: index - lineStart
  2723. }
  2724. };
  2725. token = extra.advance();
  2726. loc.end = {
  2727. line: lineNumber,
  2728. column: index - lineStart
  2729. };
  2730. if (token.type !== Token.EOF) {
  2731. range = [token.range[0], token.range[1]];
  2732. value = sliceSource(token.range[0], token.range[1]);
  2733. extra.tokens.push({
  2734. type: TokenName[token.type],
  2735. value: value,
  2736. range: range,
  2737. loc: loc
  2738. });
  2739. }
  2740. return token;
  2741. }
  2742. function collectRegex() {
  2743. var pos, loc, regex, token;
  2744. skipComment();
  2745. pos = index;
  2746. loc = {
  2747. start: {
  2748. line: lineNumber,
  2749. column: index - lineStart
  2750. }
  2751. };
  2752. regex = extra.scanRegExp();
  2753. loc.end = {
  2754. line: lineNumber,
  2755. column: index - lineStart
  2756. };
  2757. // Pop the previous token, which is likely '/' or '/='
  2758. if (extra.tokens.length > 0) {
  2759. token = extra.tokens[extra.tokens.length - 1];
  2760. if (token.range[0] === pos && token.type === 'Punctuator') {
  2761. if (token.value === '/' || token.value === '/=') {
  2762. extra.tokens.pop();
  2763. }
  2764. }
  2765. }
  2766. extra.tokens.push({
  2767. type: 'RegularExpression',
  2768. value: regex.literal,
  2769. range: [pos, index],
  2770. loc: loc
  2771. });
  2772. return regex;
  2773. }
  2774. function filterTokenLocation() {
  2775. var i, entry, token, tokens = [];
  2776. for (i = 0; i < extra.tokens.length; ++i) {
  2777. entry = extra.tokens[i];
  2778. token = {
  2779. type: entry.type,
  2780. value: entry.value
  2781. };
  2782. if (extra.range) {
  2783. token.range = entry.range;
  2784. }
  2785. if (extra.loc) {
  2786. token.loc = entry.loc;
  2787. }
  2788. tokens.push(token);
  2789. }
  2790. extra.tokens = tokens;
  2791. }
  2792. function createLiteral(token) {
  2793. return {
  2794. type: Syntax.Literal,
  2795. value: token.value
  2796. };
  2797. }
  2798. function createRawLiteral(token) {
  2799. return {
  2800. type: Syntax.Literal,
  2801. value: token.value,
  2802. raw: sliceSource(token.range[0], token.range[1])
  2803. };
  2804. }
  2805. function createLocationMarker() {
  2806. var marker = {};
  2807. marker.range = [index, index];
  2808. marker.loc = {
  2809. start: {
  2810. line: lineNumber,
  2811. column: index - lineStart
  2812. },
  2813. end: {
  2814. line: lineNumber,
  2815. column: index - lineStart
  2816. }
  2817. };
  2818. marker.end = function () {
  2819. this.range[1] = index;
  2820. this.loc.end.line = lineNumber;
  2821. this.loc.end.column = index - lineStart;
  2822. };
  2823. marker.applyGroup = function (node) {
  2824. if (extra.range) {
  2825. node.groupRange = [this.range[0], this.range[1]];
  2826. }
  2827. if (extra.loc) {
  2828. node.groupLoc = {
  2829. start: {
  2830. line: this.loc.start.line,
  2831. column: this.loc.start.column
  2832. },
  2833. end: {
  2834. line: this.loc.end.line,
  2835. column: this.loc.end.column
  2836. }
  2837. };
  2838. }
  2839. };
  2840. marker.apply = function (node) {
  2841. if (extra.range) {
  2842. node.range = [this.range[0], this.range[1]];
  2843. }
  2844. if (extra.loc) {
  2845. node.loc = {
  2846. start: {
  2847. line: this.loc.start.line,
  2848. column: this.loc.start.column
  2849. },
  2850. end: {
  2851. line: this.loc.end.line,
  2852. column: this.loc.end.column
  2853. }
  2854. };
  2855. }
  2856. };
  2857. return marker;
  2858. }
  2859. function trackGroupExpression() {
  2860. var marker, expr;
  2861. skipComment();
  2862. marker = createLocationMarker();
  2863. expect('(');
  2864. expr = parseExpression();
  2865. expect(')');
  2866. marker.end();
  2867. marker.applyGroup(expr);
  2868. return expr;
  2869. }
  2870. function trackLeftHandSideExpression() {
  2871. var marker, expr;
  2872. skipComment();
  2873. marker = createLocationMarker();
  2874. expr = matchKeyword('new') ? parseNewExpression() : parsePrimaryExpression();
  2875. while (match('.') || match('[')) {
  2876. if (match('[')) {
  2877. expr = {
  2878. type: Syntax.MemberExpression,
  2879. computed: true,
  2880. object: expr,
  2881. property: parseComputedMember()
  2882. };
  2883. marker.end();
  2884. marker.apply(expr);
  2885. } else {
  2886. expr = {
  2887. type: Syntax.MemberExpression,
  2888. computed: false,
  2889. object: expr,
  2890. property: parseNonComputedMember()
  2891. };
  2892. marker.end();
  2893. marker.apply(expr);
  2894. }
  2895. }
  2896. return expr;
  2897. }
  2898. function trackLeftHandSideExpressionAllowCall() {
  2899. var marker, expr;
  2900. skipComment();
  2901. marker = createLocationMarker();
  2902. expr = matchKeyword('new') ? parseNewExpression() : parsePrimaryExpression();
  2903. while (match('.') || match('[') || match('(')) {
  2904. if (match('(')) {
  2905. expr = {
  2906. type: Syntax.CallExpression,
  2907. callee: expr,
  2908. 'arguments': parseArguments()
  2909. };
  2910. marker.end();
  2911. marker.apply(expr);
  2912. } else if (match('[')) {
  2913. expr = {
  2914. type: Syntax.MemberExpression,
  2915. computed: true,
  2916. object: expr,
  2917. property: parseComputedMember()
  2918. };
  2919. marker.end();
  2920. marker.apply(expr);
  2921. } else {
  2922. expr = {
  2923. type: Syntax.MemberExpression,
  2924. computed: false,
  2925. object: expr,
  2926. property: parseNonComputedMember()
  2927. };
  2928. marker.end();
  2929. marker.apply(expr);
  2930. }
  2931. }
  2932. return expr;
  2933. }
  2934. function filterGroup(node) {
  2935. var n, i, entry;
  2936. n = (Object.prototype.toString.apply(node) === '[object Array]') ? [] : {};
  2937. for (i in node) {
  2938. if (node.hasOwnProperty(i) && i !== 'groupRange' && i !== 'groupLoc') {
  2939. entry = node[i];
  2940. if (entry === null || typeof entry !== 'object' || entry instanceof RegExp) {
  2941. n[i] = entry;
  2942. } else {
  2943. n[i] = filterGroup(entry);
  2944. }
  2945. }
  2946. }
  2947. return n;
  2948. }
  2949. function wrapTrackingFunction(range, loc) {
  2950. return function (parseFunction) {
  2951. function isBinary(node) {
  2952. return node.type === Syntax.LogicalExpression ||
  2953. node.type === Syntax.BinaryExpression;
  2954. }
  2955. function visit(node) {
  2956. var start, end;
  2957. if (isBinary(node.left)) {
  2958. visit(node.left);
  2959. }
  2960. if (isBinary(node.right)) {
  2961. visit(node.right);
  2962. }
  2963. if (range) {
  2964. if (node.left.groupRange || node.right.groupRange) {
  2965. start = node.left.groupRange ? node.left.groupRange[0] : node.left.range[0];
  2966. end = node.right.groupRange ? node.right.groupRange[1] : node.right.range[1];
  2967. node.range = [start, end];
  2968. } else if (typeof node.range === 'undefined') {
  2969. start = node.left.range[0];
  2970. end = node.right.range[1];
  2971. node.range = [start, end];
  2972. }
  2973. }
  2974. if (loc) {
  2975. if (node.left.groupLoc || node.right.groupLoc) {
  2976. start = node.left.groupLoc ? node.left.groupLoc.start : node.left.loc.start;
  2977. end = node.right.groupLoc ? node.right.groupLoc.end : node.right.loc.end;
  2978. node.loc = {
  2979. start: start,
  2980. end: end
  2981. };
  2982. } else if (typeof node.loc === 'undefined') {
  2983. node.loc = {
  2984. start: node.left.loc.start,
  2985. end: node.right.loc.end
  2986. };
  2987. }
  2988. }
  2989. }
  2990. return function () {
  2991. var marker, node;
  2992. skipComment();
  2993. marker = createLocationMarker();
  2994. node = parseFunction.apply(null, arguments);
  2995. marker.end();
  2996. if (range && typeof node.range === 'undefined') {
  2997. marker.apply(node);
  2998. }
  2999. if (loc && typeof node.loc === 'undefined') {
  3000. marker.apply(node);
  3001. }
  3002. if (isBinary(node)) {
  3003. visit(node);
  3004. }
  3005. return node;
  3006. };
  3007. };
  3008. }
  3009. function patch() {
  3010. var wrapTracking;
  3011. if (extra.comments) {
  3012. extra.skipComment = skipComment;
  3013. skipComment = scanComment;
  3014. }
  3015. if (extra.raw) {
  3016. extra.createLiteral = createLiteral;
  3017. createLiteral = createRawLiteral;
  3018. }
  3019. if (extra.range || extra.loc) {
  3020. extra.parseGroupExpression = parseGroupExpression;
  3021. extra.parseLeftHandSideExpression = parseLeftHandSideExpression;
  3022. extra.parseLeftHandSideExpressionAllowCall = parseLeftHandSideExpressionAllowCall;
  3023. parseGroupExpression = trackGroupExpression;
  3024. parseLeftHandSideExpression = trackLeftHandSideExpression;
  3025. parseLeftHandSideExpressionAllowCall = trackLeftHandSideExpressionAllowCall;
  3026. wrapTracking = wrapTrackingFunction(extra.range, extra.loc);
  3027. extra.parseAdditiveExpression = parseAdditiveExpression;
  3028. extra.parseAssignmentExpression = parseAssignmentExpression;
  3029. extra.parseBitwiseANDExpression = parseBitwiseANDExpression;
  3030. extra.parseBitwiseORExpression = parseBitwiseORExpression;
  3031. extra.parseBitwiseXORExpression = parseBitwiseXORExpression;
  3032. extra.parseBlock = parseBlock;
  3033. extra.parseFunctionSourceElements = parseFunctionSourceElements;
  3034. extra.parseCatchClause = parseCatchClause;
  3035. extra.parseComputedMember = parseComputedMember;
  3036. extra.parseConditionalExpression = parseConditionalExpression;
  3037. extra.parseConstLetDeclaration = parseConstLetDeclaration;
  3038. extra.parseEqualityExpression = parseEqualityExpression;
  3039. extra.parseExpression = parseExpression;
  3040. extra.parseForVariableDeclaration = parseForVariableDeclaration;
  3041. extra.parseFunctionDeclaration = parseFunctionDeclaration;
  3042. extra.parseFunctionExpression = parseFunctionExpression;
  3043. extra.parseLogicalANDExpression = parseLogicalANDExpression;
  3044. extra.parseLogicalORExpression = parseLogicalORExpression;
  3045. extra.parseMultiplicativeExpression = parseMultiplicativeExpression;
  3046. extra.parseNewExpression = parseNewExpression;
  3047. extra.parseNonComputedProperty = parseNonComputedProperty;
  3048. extra.parseObjectProperty = parseObjectProperty;
  3049. extra.parseObjectPropertyKey = parseObjectPropertyKey;
  3050. extra.parsePostfixExpression = parsePostfixExpression;
  3051. extra.parsePrimaryExpression = parsePrimaryExpression;
  3052. extra.parseProgram = parseProgram;
  3053. extra.parsePropertyFunction = parsePropertyFunction;
  3054. extra.parseRelationalExpression = parseRelationalExpression;
  3055. extra.parseStatement = parseStatement;
  3056. extra.parseShiftExpression = parseShiftExpression;
  3057. extra.parseSwitchCase = parseSwitchCase;
  3058. extra.parseUnaryExpression = parseUnaryExpression;
  3059. extra.parseVariableDeclaration = parseVariableDeclaration;
  3060. extra.parseVariableIdentifier = parseVariableIdentifier;
  3061. parseAdditiveExpression = wrapTracking(extra.parseAdditiveExpression);
  3062. parseAssignmentExpression = wrapTracking(extra.parseAssignmentExpression);
  3063. parseBitwiseANDExpression = wrapTracking(extra.parseBitwiseANDExpression);
  3064. parseBitwiseORExpression = wrapTracking(extra.parseBitwiseORExpression);
  3065. parseBitwiseXORExpression = wrapTracking(extra.parseBitwiseXORExpression);
  3066. parseBlock = wrapTracking(extra.parseBlock);
  3067. parseFunctionSourceElements = wrapTracking(extra.parseFunctionSourceElements);
  3068. parseCatchClause = wrapTracking(extra.parseCatchClause);
  3069. parseComputedMember = wrapTracking(extra.parseComputedMember);
  3070. parseConditionalExpression = wrapTracking(extra.parseConditionalExpression);
  3071. parseConstLetDeclaration = wrapTracking(extra.parseConstLetDeclaration);
  3072. parseEqualityExpression = wrapTracking(extra.parseEqualityExpression);
  3073. parseExpression = wrapTracking(extra.parseExpression);
  3074. parseForVariableDeclaration = wrapTracking(extra.parseForVariableDeclaration);
  3075. parseFunctionDeclaration = wrapTracking(extra.parseFunctionDeclaration);
  3076. parseFunctionExpression = wrapTracking(extra.parseFunctionExpression);
  3077. parseLeftHandSideExpression = wrapTracking(parseLeftHandSideExpression);
  3078. parseLogicalANDExpression = wrapTracking(extra.parseLogicalANDExpression);
  3079. parseLogicalORExpression = wrapTracking(extra.parseLogicalORExpression);
  3080. parseMultiplicativeExpression = wrapTracking(extra.parseMultiplicativeExpression);
  3081. parseNewExpression = wrapTracking(extra.parseNewExpression);
  3082. parseNonComputedProperty = wrapTracking(extra.parseNonComputedProperty);
  3083. parseObjectProperty = wrapTracking(extra.parseObjectProperty);
  3084. parseObjectPropertyKey = wrapTracking(extra.parseObjectPropertyKey);
  3085. parsePostfixExpression = wrapTracking(extra.parsePostfixExpression);
  3086. parsePrimaryExpression = wrapTracking(extra.parsePrimaryExpression);
  3087. parseProgram = wrapTracking(extra.parseProgram);
  3088. parsePropertyFunction = wrapTracking(extra.parsePropertyFunction);
  3089. parseRelationalExpression = wrapTracking(extra.parseRelationalExpression);
  3090. parseStatement = wrapTracking(extra.parseStatement);
  3091. parseShiftExpression = wrapTracking(extra.parseShiftExpression);
  3092. parseSwitchCase = wrapTracking(extra.parseSwitchCase);
  3093. parseUnaryExpression = wrapTracking(extra.parseUnaryExpression);
  3094. parseVariableDeclaration = wrapTracking(extra.parseVariableDeclaration);
  3095. parseVariableIdentifier = wrapTracking(extra.parseVariableIdentifier);
  3096. }
  3097. if (typeof extra.tokens !== 'undefined') {
  3098. extra.advance = advance;
  3099. extra.scanRegExp = scanRegExp;
  3100. advance = collectToken;
  3101. scanRegExp = collectRegex;
  3102. }
  3103. }
  3104. function unpatch() {
  3105. if (typeof extra.skipComment === 'function') {
  3106. skipComment = extra.skipComment;
  3107. }
  3108. if (extra.raw) {
  3109. createLiteral = extra.createLiteral;
  3110. }
  3111. if (extra.range || extra.loc) {
  3112. parseAdditiveExpression = extra.parseAdditiveExpression;
  3113. parseAssignmentExpression = extra.parseAssignmentExpression;
  3114. parseBitwiseANDExpression = extra.parseBitwiseANDExpression;
  3115. parseBitwiseORExpression = extra.parseBitwiseORExpression;
  3116. parseBitwiseXORExpression = extra.parseBitwiseXORExpression;
  3117. parseBlock = extra.parseBlock;
  3118. parseFunctionSourceElements = extra.parseFunctionSourceElements;
  3119. parseCatchClause = extra.parseCatchClause;
  3120. parseComputedMember = extra.parseComputedMember;
  3121. parseConditionalExpression = extra.parseConditionalExpression;
  3122. parseConstLetDeclaration = extra.parseConstLetDeclaration;
  3123. parseEqualityExpression = extra.parseEqualityExpression;
  3124. parseExpression = extra.parseExpression;
  3125. parseForVariableDeclaration = extra.parseForVariableDeclaration;
  3126. parseFunctionDeclaration = extra.parseFunctionDeclaration;
  3127. parseFunctionExpression = extra.parseFunctionExpression;
  3128. parseGroupExpression = extra.parseGroupExpression;
  3129. parseLeftHandSideExpression = extra.parseLeftHandSideExpression;
  3130. parseLeftHandSideExpressionAllowCall = extra.parseLeftHandSideExpressionAllowCall;
  3131. parseLogicalANDExpression = extra.parseLogicalANDExpression;
  3132. parseLogicalORExpression = extra.parseLogicalORExpression;
  3133. parseMultiplicativeExpression = extra.parseMultiplicativeExpression;
  3134. parseNewExpression = extra.parseNewExpression;
  3135. parseNonComputedProperty = extra.parseNonComputedProperty;
  3136. parseObjectProperty = extra.parseObjectProperty;
  3137. parseObjectPropertyKey = extra.parseObjectPropertyKey;
  3138. parsePrimaryExpression = extra.parsePrimaryExpression;
  3139. parsePostfixExpression = extra.parsePostfixExpression;
  3140. parseProgram = extra.parseProgram;
  3141. parsePropertyFunction = extra.parsePropertyFunction;
  3142. parseRelationalExpression = extra.parseRelationalExpression;
  3143. parseStatement = extra.parseStatement;
  3144. parseShiftExpression = extra.parseShiftExpression;
  3145. parseSwitchCase = extra.parseSwitchCase;
  3146. parseUnaryExpression = extra.parseUnaryExpression;
  3147. parseVariableDeclaration = extra.parseVariableDeclaration;
  3148. parseVariableIdentifier = extra.parseVariableIdentifier;
  3149. }
  3150. if (typeof extra.scanRegExp === 'function') {
  3151. advance = extra.advance;
  3152. scanRegExp = extra.scanRegExp;
  3153. }
  3154. }
  3155. function stringToArray(str) {
  3156. var length = str.length,
  3157. result = [],
  3158. i;
  3159. for (i = 0; i < length; ++i) {
  3160. result[i] = str.charAt(i);
  3161. }
  3162. return result;
  3163. }
  3164. function parse(code, options) {
  3165. var program, toString;
  3166. toString = String;
  3167. if (typeof code !== 'string' && !(code instanceof String)) {
  3168. code = toString(code);
  3169. }
  3170. source = code;
  3171. index = 0;
  3172. lineNumber = (source.length > 0) ? 1 : 0;
  3173. lineStart = 0;
  3174. length = source.length;
  3175. buffer = null;
  3176. state = {
  3177. allowIn: true,
  3178. labelSet: {},
  3179. inFunctionBody: false,
  3180. inIteration: false,
  3181. inSwitch: false
  3182. };
  3183. extra = {};
  3184. if (typeof options !== 'undefined') {
  3185. extra.range = (typeof options.range === 'boolean') && options.range;
  3186. extra.loc = (typeof options.loc === 'boolean') && options.loc;
  3187. extra.raw = (typeof options.raw === 'boolean') && options.raw;
  3188. if (typeof options.tokens === 'boolean' && options.tokens) {
  3189. extra.tokens = [];
  3190. }
  3191. if (typeof options.comment === 'boolean' && options.comment) {
  3192. extra.comments = [];
  3193. }
  3194. if (typeof options.tolerant === 'boolean' && options.tolerant) {
  3195. extra.errors = [];
  3196. }
  3197. }
  3198. if (length > 0) {
  3199. if (typeof source[0] === 'undefined') {
  3200. // Try first to convert to a string. This is good as fast path
  3201. // for old IE which understands string indexing for string
  3202. // literals only and not for string object.
  3203. if (code instanceof String) {
  3204. source = code.valueOf();
  3205. }
  3206. // Force accessing the characters via an array.
  3207. if (typeof source[0] === 'undefined') {
  3208. source = stringToArray(code);
  3209. }
  3210. }
  3211. }
  3212. patch();
  3213. try {
  3214. program = parseProgram();
  3215. if (typeof extra.comments !== 'undefined') {
  3216. filterCommentLocation();
  3217. program.comments = extra.comments;
  3218. }
  3219. if (typeof extra.tokens !== 'undefined') {
  3220. filterTokenLocation();
  3221. program.tokens = extra.tokens;
  3222. }
  3223. if (typeof extra.errors !== 'undefined') {
  3224. program.errors = extra.errors;
  3225. }
  3226. if (extra.range || extra.loc) {
  3227. program.body = filterGroup(program.body);
  3228. }
  3229. } catch (e) {
  3230. throw e;
  3231. } finally {
  3232. unpatch();
  3233. extra = {};
  3234. }
  3235. return program;
  3236. }
  3237. // Sync with package.json.
  3238. exports.version = '1.0.2';
  3239. exports.parse = parse;
  3240. // Deep copy.
  3241. exports.Syntax = (function () {
  3242. var name, types = {};
  3243. if (typeof Object.create === 'function') {
  3244. types = Object.create(null);
  3245. }
  3246. for (name in Syntax) {
  3247. if (Syntax.hasOwnProperty(name)) {
  3248. types[name] = Syntax[name];
  3249. }
  3250. }
  3251. if (typeof Object.freeze === 'function') {
  3252. Object.freeze(types);
  3253. }
  3254. return types;
  3255. }());
  3256. }));
  3257. /* vim: set sw=4 ts=4 et tw=80 : */
  3258. })(null);
  3259. (function(require,module){
  3260. var parse = require('esprima').parse;
  3261. var objectKeys = Object.keys || function (obj) {
  3262. var keys = [];
  3263. for (var key in obj) keys.push(key);
  3264. return keys;
  3265. };
  3266. var forEach = function (xs, fn) {
  3267. if (xs.forEach) return xs.forEach(fn);
  3268. for (var i = 0; i < xs.length; i++) {
  3269. fn.call(xs, xs[i], i, xs);
  3270. }
  3271. };
  3272. var isArray = Array.isArray || function (xs) {
  3273. return Object.prototype.toString.call(xs) === '[object Array]';
  3274. };
  3275. module.exports = function (src, opts, fn) {
  3276. if (typeof opts === 'function') {
  3277. fn = opts;
  3278. opts = {};
  3279. }
  3280. if (typeof src === 'object') {
  3281. opts = src;
  3282. src = opts.source;
  3283. delete opts.source;
  3284. }
  3285. src = src === undefined ? opts.source : src;
  3286. opts.range = true;
  3287. if (typeof src !== 'string') src = String(src);
  3288. var ast = parse(src, opts);
  3289. var result = {
  3290. chunks : src.split(''),
  3291. toString : function () { return result.chunks.join('') },
  3292. inspect : function () { return result.toString() }
  3293. };
  3294. var index = 0;
  3295. (function walk (node, parent) {
  3296. insertHelpers(node, parent, result.chunks);
  3297. forEach(objectKeys(node), function (key) {
  3298. if (key === 'parent') return;
  3299. var child = node[key];
  3300. if (isArray(child)) {
  3301. forEach(child, function (c) {
  3302. if (c && typeof c.type === 'string') {
  3303. walk(c, node);
  3304. }
  3305. });
  3306. }
  3307. else if (child && typeof child.type === 'string') {
  3308. insertHelpers(child, node, result.chunks);
  3309. walk(child, node);
  3310. }
  3311. });
  3312. fn(node);
  3313. })(ast, undefined);
  3314. return result;
  3315. };
  3316. function insertHelpers (node, parent, chunks) {
  3317. if (!node.range) return;
  3318. node.parent = parent;
  3319. node.source = function () {
  3320. return chunks.slice(
  3321. node.range[0], node.range[1]
  3322. ).join('');
  3323. };
  3324. if (node.update && typeof node.update === 'object') {
  3325. var prev = node.update;
  3326. forEach(objectKeys(prev), function (key) {
  3327. update[key] = prev[key];
  3328. });
  3329. node.update = update;
  3330. }
  3331. else {
  3332. node.update = update;
  3333. }
  3334. function update (s) {
  3335. chunks[node.range[0]] = s;
  3336. for (var i = node.range[0] + 1; i < node.range[1]; i++) {
  3337. chunks[i] = '';
  3338. }
  3339. };
  3340. }
  3341. window.falafel = module.exports;})(function(){return {parse: esprima.parse};},{exports: {}});
  3342. var inBrowser = typeof window !== 'undefined' && this === window;
  3343. var parseAndModify = (inBrowser ? window.falafel : require("falafel"));
  3344. (inBrowser ? window : exports).blanket = (function(){
  3345. var linesToAddTracking = [
  3346. "ExpressionStatement",
  3347. "BreakStatement" ,
  3348. "ContinueStatement" ,
  3349. "VariableDeclaration",
  3350. "ReturnStatement" ,
  3351. "ThrowStatement" ,
  3352. "TryStatement" ,
  3353. "FunctionDeclaration" ,
  3354. "IfStatement" ,
  3355. "WhileStatement" ,
  3356. "DoWhileStatement" ,
  3357. "ForStatement" ,
  3358. "ForInStatement" ,
  3359. "SwitchStatement" ,
  3360. "WithStatement"
  3361. ],
  3362. linesToAddBrackets = [
  3363. "IfStatement" ,
  3364. "WhileStatement" ,
  3365. "DoWhileStatement" ,
  3366. "ForStatement" ,
  3367. "ForInStatement" ,
  3368. "WithStatement"
  3369. ],
  3370. __blanket,
  3371. copynumber = Math.floor(Math.random()*1000),
  3372. coverageInfo = {},options = {
  3373. reporter: null,
  3374. adapter:null,
  3375. filter: null,
  3376. customVariable: null,
  3377. loader: null,
  3378. ignoreScriptError: false,
  3379. existingRequireJS:false,
  3380. autoStart: false,
  3381. timeout: 180,
  3382. ignoreCors: false,
  3383. branchTracking: false,
  3384. sourceURL: false,
  3385. debug:false,
  3386. engineOnly:false,
  3387. testReadyCallback:null,
  3388. commonJS:false,
  3389. instrumentCache:false,
  3390. modulePattern: null
  3391. };
  3392. if (inBrowser && typeof window.blanket !== 'undefined'){
  3393. __blanket = window.blanket.noConflict();
  3394. }
  3395. _blanket = {
  3396. noConflict: function(){
  3397. if (__blanket){
  3398. return __blanket;
  3399. }
  3400. return _blanket;
  3401. },
  3402. _getCopyNumber: function(){
  3403. //internal method
  3404. //for differentiating between instances
  3405. return copynumber;
  3406. },
  3407. extend: function(obj) {
  3408. //borrowed from underscore
  3409. _blanket._extend(_blanket,obj);
  3410. },
  3411. _extend: function(dest,source){
  3412. if (source) {
  3413. for (var prop in source) {
  3414. if ( dest[prop] instanceof Object && typeof dest[prop] !== "function"){
  3415. _blanket._extend(dest[prop],source[prop]);
  3416. }else{
  3417. dest[prop] = source[prop];
  3418. }
  3419. }
  3420. }
  3421. },
  3422. getCovVar: function(){
  3423. var opt = _blanket.options("customVariable");
  3424. if (opt){
  3425. if (_blanket.options("debug")) {console.log("BLANKET-Using custom tracking variable:",opt);}
  3426. return inBrowser ? "window."+opt : opt;
  3427. }
  3428. return inBrowser ? "window._$blanket" : "_$jscoverage";
  3429. },
  3430. options: function(key,value){
  3431. if (typeof key !== "string"){
  3432. _blanket._extend(options,key);
  3433. }else if (typeof value === 'undefined'){
  3434. return options[key];
  3435. }else{
  3436. options[key]=value;
  3437. }
  3438. },
  3439. instrument: function(config, next){
  3440. //check instrumented hash table,
  3441. //return instrumented code if available.
  3442. var inFile = config.inputFile,
  3443. inFileName = config.inputFileName;
  3444. //check instrument cache
  3445. if (_blanket.options("instrumentCache") && sessionStorage && sessionStorage.getItem("blanket_instrument_store-"+inFileName)){
  3446. if (_blanket.options("debug")) {console.log("BLANKET-Reading instrumentation from cache: ",inFileName);}
  3447. next(sessionStorage.getItem("blanket_instrument_store-"+inFileName));
  3448. }else{
  3449. var sourceArray = _blanket._prepareSource(inFile);
  3450. _blanket._trackingArraySetup=[];
  3451. var instrumented = parseAndModify(inFile,{loc:true,comment:true}, _blanket._addTracking(inFileName));
  3452. instrumented = _blanket._trackingSetup(inFileName,sourceArray)+instrumented;
  3453. if (_blanket.options("sourceURL")){
  3454. instrumented += "\n//@ sourceURL="+inFileName.replace("http://","");
  3455. }
  3456. if (_blanket.options("debug")) {console.log("BLANKET-Instrumented file: ",inFileName);}
  3457. if (_blanket.options("instrumentCache") && sessionStorage){
  3458. if (_blanket.options("debug")) {console.log("BLANKET-Saving instrumentation to cache: ",inFileName);}
  3459. sessionStorage.setItem("blanket_instrument_store-"+inFileName,instrumented);
  3460. }
  3461. next(instrumented);
  3462. }
  3463. },
  3464. _trackingArraySetup: [],
  3465. _branchingArraySetup: [],
  3466. _prepareSource: function(source){
  3467. return source.replace(/\\/g,"\\\\").replace(/'/g,"\\'").replace(/(\r\n|\n|\r)/gm,"\n").split('\n');
  3468. },
  3469. _trackingSetup: function(filename,sourceArray){
  3470. var branches = _blanket.options("branchTracking");
  3471. var sourceString = sourceArray.join("',\n'");
  3472. var intro = "";
  3473. var covVar = _blanket.getCovVar();
  3474. intro += "if (typeof "+covVar+" === 'undefined') "+covVar+" = {};\n";
  3475. if (branches){
  3476. intro += "var _$branchFcn=function(f,l,c,r){ ";
  3477. intro += "if (!!r) { ";
  3478. intro += covVar+"[f].branchData[l][c][0] = "+covVar+"[f].branchData[l][c][0] || [];";
  3479. intro += covVar+"[f].branchData[l][c][0].push(r); }";
  3480. intro += "else { ";
  3481. intro += covVar+"[f].branchData[l][c][1] = "+covVar+"[f].branchData[l][c][1] || [];";
  3482. intro += covVar+"[f].branchData[l][c][1].push(r); }";
  3483. intro += "return r;};\n";
  3484. }
  3485. intro += "if (typeof "+covVar+"['"+filename+"'] === 'undefined'){";
  3486. intro += covVar+"['"+filename+"']=[];\n";
  3487. if (branches){
  3488. intro += covVar+"['"+filename+"'].branchData=[];\n";
  3489. }
  3490. intro += covVar+"['"+filename+"'].source=['"+sourceString+"'];\n";
  3491. //initialize array values
  3492. _blanket._trackingArraySetup.sort(function(a,b){
  3493. return parseInt(a,10) > parseInt(b,10);
  3494. }).forEach(function(item){
  3495. intro += covVar+"['"+filename+"']["+item+"]=0;\n";
  3496. });
  3497. if (branches){
  3498. _blanket._branchingArraySetup.sort(function(a,b){
  3499. return a.line > b.line;
  3500. }).sort(function(a,b){
  3501. return a.column > b.column;
  3502. }).forEach(function(item){
  3503. if (item.file === filename){
  3504. intro += "if (typeof "+ covVar+"['"+filename+"'].branchData["+item.line+"] === 'undefined'){\n";
  3505. intro += covVar+"['"+filename+"'].branchData["+item.line+"]=[];\n";
  3506. intro += "}";
  3507. intro += covVar+"['"+filename+"'].branchData["+item.line+"]["+item.column+"] = [];\n";
  3508. intro += covVar+"['"+filename+"'].branchData["+item.line+"]["+item.column+"].consequent = "+JSON.stringify(item.consequent)+";\n";
  3509. intro += covVar+"['"+filename+"'].branchData["+item.line+"]["+item.column+"].alternate = "+JSON.stringify(item.alternate)+";\n";
  3510. }
  3511. });
  3512. }
  3513. intro += "}";
  3514. return intro;
  3515. },
  3516. _blockifyIf: function(node){
  3517. if (linesToAddBrackets.indexOf(node.type) > -1){
  3518. var bracketsExistObject = node.consequent || node.body;
  3519. var bracketsExistAlt = node.alternate;
  3520. if( bracketsExistAlt && bracketsExistAlt.type !== "BlockStatement") {
  3521. bracketsExistAlt.update("{\n"+bracketsExistAlt.source()+"}\n");
  3522. }
  3523. if( bracketsExistObject && bracketsExistObject.type !== "BlockStatement") {
  3524. bracketsExistObject.update("{\n"+bracketsExistObject.source()+"}\n");
  3525. }
  3526. }
  3527. },
  3528. _trackBranch: function(node,filename){
  3529. //recursive on consequent and alternative
  3530. var line = node.loc.start.line;
  3531. var col = node.loc.start.column;
  3532. _blanket._branchingArraySetup.push({
  3533. line: line,
  3534. column: col,
  3535. file:filename,
  3536. consequent: node.consequent.loc,
  3537. alternate: node.alternate.loc
  3538. });
  3539. var source = node.source();
  3540. var updated = "_$branchFcn"+
  3541. "('"+filename+"',"+line+","+col+","+source.slice(0,source.indexOf("?"))+
  3542. ")"+source.slice(source.indexOf("?"));
  3543. node.update(updated);
  3544. },
  3545. _addTracking: function (filename) {
  3546. //falafel doesn't take a file name
  3547. //so we include the filename in a closure
  3548. //and return the function to falafel
  3549. var covVar = _blanket.getCovVar();
  3550. return function(node){
  3551. _blanket._blockifyIf(node);
  3552. if (linesToAddTracking.indexOf(node.type) > -1 && node.parent.type !== "LabeledStatement") {
  3553. _blanket._checkDefs(node,filename);
  3554. if (node.type === "VariableDeclaration" &&
  3555. (node.parent.type === "ForStatement" || node.parent.type === "ForInStatement")){
  3556. return;
  3557. }
  3558. if (node.loc && node.loc.start){
  3559. node.update(covVar+"['"+filename+"']["+node.loc.start.line+"]++;\n"+node.source());
  3560. _blanket._trackingArraySetup.push(node.loc.start.line);
  3561. }else{
  3562. //I don't think we can handle a node with no location
  3563. throw new Error("The instrumenter encountered a node with no location: "+Object.keys(node));
  3564. }
  3565. }else if (_blanket.options("branchTracking") && node.type === "ConditionalExpression"){
  3566. _blanket._trackBranch(node,filename);
  3567. }
  3568. };
  3569. },
  3570. _checkDefs: function(node,filename){
  3571. // Make sure developers don't redefine window. if they do, inform them it is wrong.
  3572. if (inBrowser){
  3573. if (node.type === "VariableDeclaration" && node.declarations) {
  3574. node.declarations.forEach(function(declaration) {
  3575. if (declaration.id.name === "window") {
  3576. throw new Error("Instrumentation error, you cannot redefine the 'window' variable in " + filename + ":" + node.loc.start.line);
  3577. }
  3578. });
  3579. }
  3580. if (node.type === "FunctionDeclaration" && node.params) {
  3581. node.params.forEach(function(param) {
  3582. if (param.name === "window") {
  3583. throw new Error("Instrumentation error, you cannot redefine the 'window' variable in " + filename + ":" + node.loc.start.line);
  3584. }
  3585. });
  3586. }
  3587. //Make sure developers don't redefine the coverage variable
  3588. if (node.type === "ExpressionStatement" &&
  3589. node.expression && node.expression.left &&
  3590. node.expression.left.object && node.expression.left.property &&
  3591. node.expression.left.object.name +
  3592. "." + node.expression.left.property.name === _blanket.getCovVar()) {
  3593. throw new Error("Instrumentation error, you cannot redefine the coverage variable in " + filename + ":" + node.loc.start.line);
  3594. }
  3595. }else{
  3596. //Make sure developers don't redefine the coverage variable in node
  3597. if (node.type === "ExpressionStatement" &&
  3598. node.expression && node.expression.left &&
  3599. !node.expression.left.object && !node.expression.left.property &&
  3600. node.expression.left.name === _blanket.getCovVar()) {
  3601. throw new Error("Instrumentation error, you cannot redefine the coverage variable in " + filename + ":" + node.loc.start.line);
  3602. }
  3603. }
  3604. },
  3605. setupCoverage: function(){
  3606. coverageInfo.instrumentation = "blanket";
  3607. coverageInfo.stats = {
  3608. "suites": 0,
  3609. "tests": 0,
  3610. "passes": 0,
  3611. "pending": 0,
  3612. "failures": 0,
  3613. "start": new Date()
  3614. };
  3615. },
  3616. _checkIfSetup: function(){
  3617. if (!coverageInfo.stats){
  3618. throw new Error("You must call blanket.setupCoverage() first.");
  3619. }
  3620. },
  3621. onTestStart: function(){
  3622. if (_blanket.options("debug")) {console.log("BLANKET-Test event started");}
  3623. this._checkIfSetup();
  3624. coverageInfo.stats.tests++;
  3625. coverageInfo.stats.pending++;
  3626. },
  3627. onTestDone: function(total,passed){
  3628. this._checkIfSetup();
  3629. if(passed === total){
  3630. coverageInfo.stats.passes++;
  3631. }else{
  3632. coverageInfo.stats.failures++;
  3633. }
  3634. coverageInfo.stats.pending--;
  3635. },
  3636. onModuleStart: function(){
  3637. this._checkIfSetup();
  3638. coverageInfo.stats.suites++;
  3639. },
  3640. onTestsDone: function(){
  3641. if (_blanket.options("debug")) {console.log("BLANKET-Test event done");}
  3642. this._checkIfSetup();
  3643. coverageInfo.stats.end = new Date();
  3644. if (inBrowser){
  3645. this.report(coverageInfo);
  3646. }else{
  3647. if (!_blanket.options("branchTracking")){
  3648. delete (inBrowser ? window : global)[_blanket.getCovVar()].branchFcn;
  3649. }
  3650. this.options("reporter").call(this,coverageInfo);
  3651. }
  3652. }
  3653. };
  3654. return _blanket;
  3655. })();
  3656. (function(_blanket){
  3657. var oldOptions = _blanket.options;
  3658. _blanket.extend({
  3659. outstandingRequireFiles:[],
  3660. options: function(key,value){
  3661. var newVal={};
  3662. if (typeof key !== "string"){
  3663. //key is key/value map
  3664. oldOptions(key);
  3665. newVal = key;
  3666. }else if (typeof value === 'undefined'){
  3667. //accessor
  3668. return oldOptions(key);
  3669. }else{
  3670. //setter
  3671. oldOptions(key,value);
  3672. newVal[key] = value;
  3673. }
  3674. if (newVal.adapter){
  3675. _blanket._loadFile(newVal.adapter);
  3676. }
  3677. if (newVal.loader){
  3678. _blanket._loadFile(newVal.loader);
  3679. }
  3680. },
  3681. requiringFile: function(filename,done){
  3682. if (typeof filename === "undefined"){
  3683. _blanket.outstandingRequireFiles=[];
  3684. }else if (typeof done === "undefined"){
  3685. _blanket.outstandingRequireFiles.push(filename);
  3686. }else{
  3687. _blanket.outstandingRequireFiles.splice(_blanket.outstandingRequireFiles.indexOf(filename),1);
  3688. }
  3689. },
  3690. requireFilesLoaded: function(){
  3691. return _blanket.outstandingRequireFiles.length === 0;
  3692. },
  3693. showManualLoader: function(){
  3694. if (document.getElementById("blanketLoaderDialog")){
  3695. return;
  3696. }
  3697. //copied from http://blog.avtex.com/2012/01/26/cross-browser-css-only-modal-box/
  3698. var loader = "<div class='blanketDialogOverlay'>";
  3699. loader += "&nbsp;</div>";
  3700. loader += "<div class='blanketDialogVerticalOffset'>";
  3701. loader += "<div class='blanketDialogBox'>";
  3702. loader += "<b>Error:</b> Blanket.js encountered a cross origin request error while instrumenting the source files. ";
  3703. loader += "<br><br>This is likely caused by the source files being referenced locally (using the file:// protocol). ";
  3704. loader += "<br><br>Some solutions include <a href='http://askubuntu.com/questions/160245/making-google-chrome-option-allow-file-access-from-files-permanent' target='_blank'>starting Chrome with special flags</a>, <a target='_blank' href='https://github.com/remy/servedir'>running a server locally</a>, or using a browser without these CORS restrictions (Safari).";
  3705. loader += "<br>";
  3706. if (typeof FileReader !== "undefined"){
  3707. loader += "<br>Or, try the experimental loader. When prompted, simply click on the directory containing all the source files you want covered.";
  3708. loader += "<a href='javascript:document.getElementById(\"fileInput\").click();'>Start Loader</a>";
  3709. loader += "<input type='file' type='application/x-javascript' accept='application/x-javascript' webkitdirectory id='fileInput' multiple onchange='window.blanket.manualFileLoader(this.files)' style='visibility:hidden;position:absolute;top:-50;left:-50'/>";
  3710. }
  3711. loader += "<br><span style='float:right;cursor:pointer;' onclick=document.getElementById('blanketLoaderDialog').style.display='none';>Close</span>";
  3712. loader += "<div style='clear:both'></div>";
  3713. loader += "</div></div>";
  3714. var css = ".blanketDialogWrapper {";
  3715. css += "display:block;";
  3716. css += "position:fixed;";
  3717. css += "z-index:40001; }";
  3718. css += ".blanketDialogOverlay {";
  3719. css += "position:fixed;";
  3720. css += "width:100%;";
  3721. css += "height:100%;";
  3722. css += "background-color:black;";
  3723. css += "opacity:.5; ";
  3724. css += "-ms-filter:'progid:DXImageTransform.Microsoft.Alpha(Opacity=50)'; ";
  3725. css += "filter:alpha(opacity=50); ";
  3726. css += "z-index:40001; }";
  3727. css += ".blanketDialogVerticalOffset { ";
  3728. css += "position:fixed;";
  3729. css += "top:30%;";
  3730. css += "width:100%;";
  3731. css += "z-index:40002; }";
  3732. css += ".blanketDialogBox { ";
  3733. css += "width:405px; ";
  3734. css += "position:relative;";
  3735. css += "margin:0 auto;";
  3736. css += "background-color:white;";
  3737. css += "padding:10px;";
  3738. css += "border:1px solid black; }";
  3739. var dom = document.createElement("style");
  3740. dom.innerHTML = css;
  3741. document.head.appendChild(dom);
  3742. var div = document.createElement("div");
  3743. div.id = "blanketLoaderDialog";
  3744. div.className = "blanketDialogWrapper";
  3745. div.innerHTML = loader;
  3746. document.body.insertBefore(div,document.body.firstChild);
  3747. },
  3748. manualFileLoader: function(files){
  3749. var toArray =Array.prototype.slice;
  3750. files = toArray.call(files).filter(function(item){
  3751. return item.type !== "";
  3752. });
  3753. var sessionLength = files.length-1;
  3754. var sessionIndx=0;
  3755. var sessionArray = {};
  3756. if (sessionStorage["blanketSessionLoader"]){
  3757. sessionArray = JSON.parse(sessionStorage["blanketSessionLoader"]);
  3758. }
  3759. var fileLoader = function(event){
  3760. var fileContent = event.currentTarget.result;
  3761. var file = files[sessionIndx];
  3762. var filename = file.webkitRelativePath && file.webkitRelativePath !== '' ? file.webkitRelativePath : file.name;
  3763. sessionArray[filename] = fileContent;
  3764. sessionIndx++;
  3765. if (sessionIndx === sessionLength){
  3766. sessionStorage.setItem("blanketSessionLoader", JSON.stringify(sessionArray));
  3767. document.location.reload();
  3768. }else{
  3769. readFile(files[sessionIndx]);
  3770. }
  3771. };
  3772. function readFile(file){
  3773. var reader = new FileReader();
  3774. reader.onload = fileLoader;
  3775. reader.readAsText(file);
  3776. }
  3777. readFile(files[sessionIndx]);
  3778. },
  3779. _loadFile: function(path){
  3780. if (typeof path !== "undefined"){
  3781. var request = new XMLHttpRequest();
  3782. request.open('GET', path, false);
  3783. request.send();
  3784. _blanket._addScript(request.responseText);
  3785. }
  3786. },
  3787. _addScript: function(data){
  3788. var script = document.createElement("script");
  3789. script.type = "text/javascript";
  3790. script.text = data;
  3791. (document.body || document.getElementsByTagName('head')[0]).appendChild(script);
  3792. },
  3793. hasAdapter: function(callback){
  3794. return _blanket.options("adapter") !== null;
  3795. },
  3796. report: function(coverage_data){
  3797. if (!document.getElementById("blanketLoaderDialog")){
  3798. //all found, clear it
  3799. _blanket.blanketSession = null;
  3800. }
  3801. coverage_data.files = window._$blanket;
  3802. var require = blanket.options("commonJS") ? blanket._commonjs.require : window.require;
  3803. // Check if we have any covered files that requires reporting
  3804. // otherwise just exit gracefully.
  3805. if (!coverage_data.files || !Object.keys(coverage_data.files).length) {
  3806. if (_blanket.options("debug")) {console.log("BLANKET-Reporting No files were instrumented.");}
  3807. return;
  3808. }
  3809. if (typeof coverage_data.files.branchFcn !== "undefined"){
  3810. delete coverage_data.files.branchFcn;
  3811. }
  3812. if (typeof _blanket.options("reporter") === "string"){
  3813. _blanket._loadFile(_blanket.options("reporter"));
  3814. _blanket.customReporter(coverage_data,_blanket.options("reporter_options"));
  3815. }else if (typeof _blanket.options("reporter") === "function"){
  3816. _blanket.options("reporter")(coverage_data);
  3817. }else if (typeof _blanket.defaultReporter === 'function'){
  3818. _blanket.defaultReporter(coverage_data);
  3819. }else{
  3820. throw new Error("no reporter defined.");
  3821. }
  3822. },
  3823. _bindStartTestRunner: function(bindEvent,startEvent){
  3824. if (bindEvent){
  3825. bindEvent(startEvent);
  3826. }else{
  3827. window.addEventListener("load",startEvent,false);
  3828. }
  3829. },
  3830. _loadSourceFiles: function(callback){
  3831. var require = blanket.options("commonJS") ? blanket._commonjs.require : window.require;
  3832. function copy(o){
  3833. var _copy = Object.create( Object.getPrototypeOf(o) );
  3834. var propNames = Object.getOwnPropertyNames(o);
  3835. propNames.forEach(function(name){
  3836. var desc = Object.getOwnPropertyDescriptor(o, name);
  3837. Object.defineProperty(_copy, name, desc);
  3838. });
  3839. return _copy;
  3840. }
  3841. if (_blanket.options("debug")) {console.log("BLANKET-Collecting page scripts");}
  3842. var scripts = _blanket.utils.collectPageScripts();
  3843. //_blanket.options("filter",scripts);
  3844. if (scripts.length === 0){
  3845. callback();
  3846. }else{
  3847. //check session state
  3848. if (sessionStorage["blanketSessionLoader"]){
  3849. _blanket.blanketSession = JSON.parse(sessionStorage["blanketSessionLoader"]);
  3850. }
  3851. scripts.forEach(function(file,indx){
  3852. _blanket.utils.cache[file+".js"]={
  3853. loaded:false
  3854. };
  3855. });
  3856. var currScript=-1;
  3857. _blanket.utils.loadAll(function(test){
  3858. if (test){
  3859. return typeof scripts[currScript+1] !== 'undefined';
  3860. }
  3861. currScript++;
  3862. if (currScript >= scripts.length){
  3863. return null;
  3864. }
  3865. return scripts[currScript]+".js";
  3866. },callback);
  3867. }
  3868. },
  3869. beforeStartTestRunner: function(opts){
  3870. opts = opts || {};
  3871. opts.checkRequirejs = typeof opts.checkRequirejs === "undefined" ? true : opts.checkRequirejs;
  3872. opts.callback = opts.callback || function() { };
  3873. opts.coverage = typeof opts.coverage === "undefined" ? true : opts.coverage;
  3874. if (opts.coverage) {
  3875. _blanket._bindStartTestRunner(opts.bindEvent,
  3876. function(){
  3877. _blanket._loadSourceFiles(function() {
  3878. var allLoaded = function(){
  3879. return opts.condition ? opts.condition() : _blanket.requireFilesLoaded();
  3880. };
  3881. var check = function() {
  3882. if (allLoaded()) {
  3883. if (_blanket.options("debug")) {console.log("BLANKET-All files loaded, init start test runner callback.");}
  3884. var cb = _blanket.options("testReadyCallback");
  3885. if (cb){
  3886. if (typeof cb === "function"){
  3887. cb(opts.callback);
  3888. }else if (typeof cb === "string"){
  3889. _blanket._addScript(cb);
  3890. opts.callback();
  3891. }
  3892. }else{
  3893. opts.callback();
  3894. }
  3895. } else {
  3896. setTimeout(check, 13);
  3897. }
  3898. };
  3899. check();
  3900. });
  3901. });
  3902. }else{
  3903. opts.callback();
  3904. }
  3905. },
  3906. utils: {
  3907. qualifyURL: function (url) {
  3908. //http://stackoverflow.com/questions/470832/getting-an-absolute-url-from-a-relative-one-ie6-issue
  3909. var a = document.createElement('a');
  3910. a.href = url;
  3911. return a.href;
  3912. }
  3913. }
  3914. });
  3915. })(blanket);
  3916. blanket.defaultReporter = function(coverage){
  3917. var cssSytle = "#blanket-main {margin:2px;background:#EEE;color:#333;clear:both;font-family:'Helvetica Neue Light', 'HelveticaNeue-Light', 'Helvetica Neue', Calibri, Helvetica, Arial, sans-serif; font-size:17px;} #blanket-main a {color:#333;text-decoration:none;} #blanket-main a:hover {text-decoration:underline;} .blanket {margin:0;padding:5px;clear:both;border-bottom: 1px solid #FFFFFF;} .bl-error {color:red;}.bl-success {color:#5E7D00;} .bl-file{width:auto;} .bl-cl{float:left;} .blanket div.rs {margin-left:50px; width:150px; float:right} .bl-nb {padding-right:10px;} #blanket-main a.bl-logo {color: #EB1764;cursor: pointer;font-weight: bold;text-decoration: none} .bl-source{ overflow-x:scroll; background-color: #FFFFFF; border: 1px solid #CBCBCB; color: #363636; margin: 25px 20px; width: 80%;} .bl-source div{white-space: pre;font-family: monospace;} .bl-source > div > span:first-child{background-color: #EAEAEA;color: #949494;display: inline-block;padding: 0 10px;text-align: center;width: 30px;} .bl-source .miss{background-color:#e6c3c7} .bl-source span.branchWarning{color:#000;background-color:yellow;} .bl-source span.branchOkay{color:#000;background-color:transparent;}",
  3918. successRate = 60,
  3919. head = document.head,
  3920. fileNumber = 0,
  3921. body = document.body,
  3922. headerContent,
  3923. hasBranchTracking = Object.keys(coverage.files).some(function(elem){
  3924. return typeof coverage.files[elem].branchData !== 'undefined';
  3925. }),
  3926. bodyContent = "<div id='blanket-main'><div class='blanket bl-title'><div class='bl-cl bl-file'><a href='http://alex-seville.github.com/blanket/' target='_blank' class='bl-logo'>Blanket.js</a> results</div><div class='bl-cl rs'>Coverage (%)</div><div class='bl-cl rs'>Covered/Total Smts.</div>"+(hasBranchTracking ? "<div class='bl-cl rs'>Covered/Total Branches</div>":"")+"<div style='clear:both;'></div></div>",
  3927. fileTemplate = "<div class='blanket {{statusclass}}'><div class='bl-cl bl-file'><span class='bl-nb'>{{fileNumber}}.</span><a href='javascript:blanket_toggleSource(\"file-{{fileNumber}}\")'>{{file}}</a></div><div class='bl-cl rs'>{{percentage}} %</div><div class='bl-cl rs'>{{numberCovered}}/{{totalSmts}}</div>"+( hasBranchTracking ? "<div class='bl-cl rs'>{{passedBranches}}/{{totalBranches}}</div>" : "" )+"<div id='file-{{fileNumber}}' class='bl-source' style='display:none;'>{{source}}</div><div style='clear:both;'></div></div>";
  3928. grandTotalTemplate = "<div class='blanket grand-total {{statusclass}}'><div class='bl-cl'>{{rowTitle}}</div><div class='bl-cl rs'>{{percentage}} %</div><div class='bl-cl rs'>{{numberCovered}}/{{totalSmts}}</div>"+( hasBranchTracking ? "<div class='bl-cl rs'>{{passedBranches}}/{{totalBranches}}</div>" : "" ) + "<div style='clear:both;'></div></div>";
  3929. function blanket_toggleSource(id) {
  3930. var element = document.getElementById(id);
  3931. if(element.style.display === 'block') {
  3932. element.style.display = 'none';
  3933. } else {
  3934. element.style.display = 'block';
  3935. }
  3936. }
  3937. var script = document.createElement("script");
  3938. script.type = "text/javascript";
  3939. script.text = blanket_toggleSource.toString().replace('function ' + blanket_toggleSource.name, 'function blanket_toggleSource');
  3940. body.appendChild(script);
  3941. var percentage = function(number, total) {
  3942. return (Math.round(((number/total) * 100)*100)/100);
  3943. };
  3944. var appendTag = function (type, el, str) {
  3945. var dom = document.createElement(type);
  3946. dom.innerHTML = str;
  3947. el.appendChild(dom);
  3948. };
  3949. function escapeInvalidXmlChars(str) {
  3950. return str.replace(/\&/g, "&amp;")
  3951. .replace(/</g, "&lt;")
  3952. .replace(/\>/g, "&gt;")
  3953. .replace(/\"/g, "&quot;")
  3954. .replace(/\'/g, "&apos;");
  3955. }
  3956. function isBranchFollowed(data,bool){
  3957. var mode = bool ? 0 : 1;
  3958. if (typeof data === 'undefined' ||
  3959. typeof data === null ||
  3960. typeof data[mode] === 'undefined'){
  3961. return false;
  3962. }
  3963. return data[mode].length > 0;
  3964. }
  3965. var branchStack = [];
  3966. function branchReport(colsIndex,src,cols,offset,lineNum){
  3967. var newsrc="";
  3968. var postfix="";
  3969. if (branchStack.length > 0){
  3970. newsrc += "<span class='" + (isBranchFollowed(branchStack[0][1],branchStack[0][1].consequent === branchStack[0][0]) ? 'branchOkay' : 'branchWarning') + "'>";
  3971. if (branchStack[0][0].end.line === lineNum){
  3972. newsrc += escapeInvalidXmlChars(src.slice(0,branchStack[0][0].end.column)) + "</span>";
  3973. src = src.slice(branchStack[0][0].end.column);
  3974. branchStack.shift();
  3975. if (branchStack.length > 0){
  3976. newsrc += "<span class='" + (isBranchFollowed(branchStack[0][1],false) ? 'branchOkay' : 'branchWarning') + "'>";
  3977. if (branchStack[0][0].end.line === lineNum){
  3978. newsrc += escapeInvalidXmlChars(src.slice(0,branchStack[0][0].end.column)) + "</span>";
  3979. src = src.slice(branchStack[0][0].end.column);
  3980. branchStack.shift();
  3981. if (!cols){
  3982. return {src: newsrc + escapeInvalidXmlChars(src) ,cols:cols};
  3983. }
  3984. }
  3985. else if (!cols){
  3986. return {src: newsrc + escapeInvalidXmlChars(src) + "</span>",cols:cols};
  3987. }
  3988. else{
  3989. postfix = "</span>";
  3990. }
  3991. }else if (!cols){
  3992. return {src: newsrc + escapeInvalidXmlChars(src) ,cols:cols};
  3993. }
  3994. }else if(!cols){
  3995. return {src: newsrc + escapeInvalidXmlChars(src) + "</span>",cols:cols};
  3996. }else{
  3997. postfix = "</span>";
  3998. }
  3999. }
  4000. var thisline = cols[colsIndex];
  4001. //consequent
  4002. var cons = thisline.consequent;
  4003. if (cons.start.line > lineNum){
  4004. branchStack.unshift([thisline.alternate,thisline]);
  4005. branchStack.unshift([cons,thisline]);
  4006. src = escapeInvalidXmlChars(src);
  4007. }else{
  4008. var style = "<span class='" + (isBranchFollowed(thisline,true) ? 'branchOkay' : 'branchWarning') + "'>";
  4009. newsrc += escapeInvalidXmlChars(src.slice(0,cons.start.column-offset)) + style;
  4010. if (cols.length > colsIndex+1 &&
  4011. cols[colsIndex+1].consequent.start.line === lineNum &&
  4012. cols[colsIndex+1].consequent.start.column-offset < cols[colsIndex].consequent.end.column-offset)
  4013. {
  4014. var res = branchReport(colsIndex+1,src.slice(cons.start.column-offset,cons.end.column-offset),cols,cons.start.column-offset,lineNum);
  4015. newsrc += res.src;
  4016. cols = res.cols;
  4017. cols[colsIndex+1] = cols[colsIndex+2];
  4018. cols.length--;
  4019. }else{
  4020. newsrc += escapeInvalidXmlChars(src.slice(cons.start.column-offset,cons.end.column-offset));
  4021. }
  4022. newsrc += "</span>";
  4023. var alt = thisline.alternate;
  4024. if (alt.start.line > lineNum){
  4025. newsrc += escapeInvalidXmlChars(src.slice(cons.end.column-offset));
  4026. branchStack.unshift([alt,thisline]);
  4027. }else{
  4028. newsrc += escapeInvalidXmlChars(src.slice(cons.end.column-offset,alt.start.column-offset));
  4029. style = "<span class='" + (isBranchFollowed(thisline,false) ? 'branchOkay' : 'branchWarning') + "'>";
  4030. newsrc += style;
  4031. if (cols.length > colsIndex+1 &&
  4032. cols[colsIndex+1].consequent.start.line === lineNum &&
  4033. cols[colsIndex+1].consequent.start.column-offset < cols[colsIndex].alternate.end.column-offset)
  4034. {
  4035. var res2 = branchReport(colsIndex+1,src.slice(alt.start.column-offset,alt.end.column-offset),cols,alt.start.column-offset,lineNum);
  4036. newsrc += res2.src;
  4037. cols = res2.cols;
  4038. cols[colsIndex+1] = cols[colsIndex+2];
  4039. cols.length--;
  4040. }else{
  4041. newsrc += escapeInvalidXmlChars(src.slice(alt.start.column-offset,alt.end.column-offset));
  4042. }
  4043. newsrc += "</span>";
  4044. newsrc += escapeInvalidXmlChars(src.slice(alt.end.column-offset));
  4045. src = newsrc;
  4046. }
  4047. }
  4048. return {src:src+postfix, cols:cols};
  4049. }
  4050. var isUndefined = function(item){
  4051. return typeof item !== 'undefined';
  4052. };
  4053. var files = coverage.files;
  4054. var totals = {
  4055. totalSmts: 0,
  4056. numberOfFilesCovered: 0,
  4057. passedBranches: 0,
  4058. totalBranches: 0,
  4059. moduleTotalStatements : {},
  4060. moduleTotalCoveredStatements : {},
  4061. moduleTotalBranches : {},
  4062. moduleTotalCoveredBranches : {}
  4063. };
  4064. // check if a data-cover-modulepattern was provided for per-module coverage reporting
  4065. var modulePattern = _blanket.options("modulePattern");
  4066. var modulePatternRegex = ( modulePattern ? new RegExp(modulePattern) : null );
  4067. for(var file in files)
  4068. {
  4069. fileNumber++;
  4070. var statsForFile = files[file],
  4071. totalSmts = 0,
  4072. numberOfFilesCovered = 0,
  4073. code = [],
  4074. i;
  4075. var end = [];
  4076. for(i = 0; i < statsForFile.source.length; i +=1){
  4077. var src = statsForFile.source[i];
  4078. if (branchStack.length > 0 ||
  4079. typeof statsForFile.branchData !== 'undefined')
  4080. {
  4081. if (typeof statsForFile.branchData[i+1] !== 'undefined')
  4082. {
  4083. var cols = statsForFile.branchData[i+1].filter(isUndefined);
  4084. var colsIndex=0;
  4085. src = branchReport(colsIndex,src,cols,0,i+1).src;
  4086. }else if (branchStack.length){
  4087. src = branchReport(0,src,null,0,i+1).src;
  4088. }else{
  4089. src = escapeInvalidXmlChars(src);
  4090. }
  4091. }else{
  4092. src = escapeInvalidXmlChars(src);
  4093. }
  4094. var lineClass="";
  4095. if(statsForFile[i+1]) {
  4096. numberOfFilesCovered += 1;
  4097. totalSmts += 1;
  4098. lineClass = 'hit';
  4099. }else{
  4100. if(statsForFile[i+1] === 0){
  4101. totalSmts++;
  4102. lineClass = 'miss';
  4103. }
  4104. }
  4105. code[i + 1] = "<div class='"+lineClass+"'><span class=''>"+(i + 1)+"</span>"+src+"</div>";
  4106. }
  4107. totals.totalSmts += totalSmts;
  4108. totals.numberOfFilesCovered += numberOfFilesCovered;
  4109. var totalBranches=0;
  4110. var passedBranches=0;
  4111. if (typeof statsForFile.branchData !== 'undefined'){
  4112. for(var j=0;j<statsForFile.branchData.length;j++){
  4113. if (typeof statsForFile.branchData[j] !== 'undefined'){
  4114. for(var k=0;k<statsForFile.branchData[j].length;k++){
  4115. if (typeof statsForFile.branchData[j][k] !== 'undefined'){
  4116. totalBranches++;
  4117. if (typeof statsForFile.branchData[j][k][0] !== 'undefined' &&
  4118. statsForFile.branchData[j][k][0].length > 0 &&
  4119. typeof statsForFile.branchData[j][k][1] !== 'undefined' &&
  4120. statsForFile.branchData[j][k][1].length > 0){
  4121. passedBranches++;
  4122. }
  4123. }
  4124. }
  4125. }
  4126. }
  4127. }
  4128. totals.passedBranches += passedBranches;
  4129. totals.totalBranches += totalBranches;
  4130. // if "data-cover-modulepattern" was provided,
  4131. // track totals per module name as well as globally
  4132. if (modulePatternRegex) {
  4133. var moduleName = file.match(modulePatternRegex)[1];
  4134. if(!totals.moduleTotalStatements.hasOwnProperty(moduleName)) {
  4135. totals.moduleTotalStatements[moduleName] = 0;
  4136. totals.moduleTotalCoveredStatements[moduleName] = 0;
  4137. }
  4138. totals.moduleTotalStatements[moduleName] += totalSmts;
  4139. totals.moduleTotalCoveredStatements[moduleName] += numberOfFilesCovered;
  4140. if(!totals.moduleTotalBranches.hasOwnProperty(moduleName)) {
  4141. totals.moduleTotalBranches[moduleName] = 0;
  4142. totals.moduleTotalCoveredBranches[moduleName] = 0;
  4143. }
  4144. totals.moduleTotalBranches[moduleName] += totalBranches;
  4145. totals.moduleTotalCoveredBranches[moduleName] += passedBranches;
  4146. }
  4147. var result = percentage(numberOfFilesCovered, totalSmts);
  4148. var output = fileTemplate.replace("{{file}}", file)
  4149. .replace("{{percentage}}",result)
  4150. .replace("{{numberCovered}}", numberOfFilesCovered)
  4151. .replace(/\{\{fileNumber\}\}/g, fileNumber)
  4152. .replace("{{totalSmts}}", totalSmts)
  4153. .replace("{{totalBranches}}", totalBranches)
  4154. .replace("{{passedBranches}}", passedBranches)
  4155. .replace("{{source}}", code.join(" "));
  4156. if(result < successRate)
  4157. {
  4158. output = output.replace("{{statusclass}}", "bl-error");
  4159. } else {
  4160. output = output.replace("{{statusclass}}", "bl-success");
  4161. }
  4162. bodyContent += output;
  4163. }
  4164. // create temporary function for use by the global totals reporter,
  4165. // as well as the per-module totals reporter
  4166. var createAggregateTotal = function(numSt, numCov, numBranch, numCovBr, moduleName) {
  4167. var totalPercent = percentage(numCov, numSt);
  4168. var statusClass = totalPercent < successRate ? "bl-error" : "bl-success";
  4169. var rowTitle = ( moduleName ? "Total for module: " + moduleName : "Global total" );
  4170. var totalsOutput = grandTotalTemplate.replace("{{rowTitle}}", rowTitle)
  4171. .replace("{{percentage}}", totalPercent)
  4172. .replace("{{numberCovered}}", numCov)
  4173. .replace("{{totalSmts}}", numSt)
  4174. .replace("{{passedBranches}}", numCovBr)
  4175. .replace("{{totalBranches}}", numBranch)
  4176. .replace("{{statusclass}}", statusClass);
  4177. bodyContent += totalsOutput;
  4178. };
  4179. // if "data-cover-modulepattern" was provided,
  4180. // output the per-module totals alongside the global totals
  4181. if (modulePatternRegex) {
  4182. for (var thisModuleName in totals.moduleTotalStatements) {
  4183. if (totals.moduleTotalStatements.hasOwnProperty(thisModuleName)) {
  4184. var moduleTotalSt = totals.moduleTotalStatements[thisModuleName];
  4185. var moduleTotalCovSt = totals.moduleTotalCoveredStatements[thisModuleName];
  4186. var moduleTotalBr = totals.moduleTotalBranches[thisModuleName];
  4187. var moduleTotalCovBr = totals.moduleTotalCoveredBranches[thisModuleName];
  4188. createAggregateTotal(moduleTotalSt, moduleTotalCovSt, moduleTotalBr, moduleTotalCovBr, thisModuleName);
  4189. }
  4190. }
  4191. }
  4192. createAggregateTotal(totals.totalSmts, totals.numberOfFilesCovered, totals.totalBranches, totals.passedBranches, null);
  4193. bodyContent += "</div>"; //closing main
  4194. appendTag('style', head, cssSytle);
  4195. //appendStyle(body, headerContent);
  4196. if (document.getElementById("blanket-main")){
  4197. document.getElementById("blanket-main").innerHTML=
  4198. bodyContent.slice(23,-6);
  4199. }else{
  4200. appendTag('div', body, bodyContent);
  4201. }
  4202. //appendHtml(body, '</div>');
  4203. };
  4204. (function(){
  4205. var newOptions={};
  4206. //http://stackoverflow.com/a/2954896
  4207. var toArray =Array.prototype.slice;
  4208. var scripts = toArray.call(document.scripts);
  4209. toArray.call(scripts[scripts.length - 1].attributes)
  4210. .forEach(function(es){
  4211. if(es.nodeName === "data-cover-only"){
  4212. newOptions.filter = es.nodeValue;
  4213. }
  4214. if(es.nodeName === "data-cover-never"){
  4215. newOptions.antifilter = es.nodeValue;
  4216. }
  4217. if(es.nodeName === "data-cover-reporter"){
  4218. newOptions.reporter = es.nodeValue;
  4219. }
  4220. if (es.nodeName === "data-cover-adapter"){
  4221. newOptions.adapter = es.nodeValue;
  4222. }
  4223. if (es.nodeName === "data-cover-loader"){
  4224. newOptions.loader = es.nodeValue;
  4225. }
  4226. if (es.nodeName === "data-cover-timeout"){
  4227. newOptions.timeout = es.nodeValue;
  4228. }
  4229. if (es.nodeName === "data-cover-modulepattern") {
  4230. newOptions.modulePattern = es.nodeValue;
  4231. }
  4232. if (es.nodeName === "data-cover-reporter-options"){
  4233. try{
  4234. newOptions.reporter_options = JSON.parse(es.nodeValue);
  4235. }catch(e){
  4236. if (blanket.options("debug")){
  4237. throw new Error("Invalid reporter options. Must be a valid stringified JSON object.");
  4238. }
  4239. }
  4240. }
  4241. if (es.nodeName === "data-cover-testReadyCallback"){
  4242. newOptions.testReadyCallback = es.nodeValue;
  4243. }
  4244. if (es.nodeName === "data-cover-customVariable"){
  4245. newOptions.customVariable = es.nodeValue;
  4246. }
  4247. if (es.nodeName === "data-cover-flags"){
  4248. var flags = " "+es.nodeValue+" ";
  4249. if (flags.indexOf(" ignoreError ") > -1){
  4250. newOptions.ignoreScriptError = true;
  4251. }
  4252. if (flags.indexOf(" autoStart ") > -1){
  4253. newOptions.autoStart = true;
  4254. }
  4255. if (flags.indexOf(" ignoreCors ") > -1){
  4256. newOptions.ignoreCors = true;
  4257. }
  4258. if (flags.indexOf(" branchTracking ") > -1){
  4259. newOptions.branchTracking = true;
  4260. }
  4261. if (flags.indexOf(" sourceURL ") > -1){
  4262. newOptions.sourceURL = true;
  4263. }
  4264. if (flags.indexOf(" debug ") > -1){
  4265. newOptions.debug = true;
  4266. }
  4267. if (flags.indexOf(" engineOnly ") > -1){
  4268. newOptions.engineOnly = true;
  4269. }
  4270. if (flags.indexOf(" commonJS ") > -1){
  4271. newOptions.commonJS = true;
  4272. }
  4273. if (flags.indexOf(" instrumentCache ") > -1){
  4274. newOptions.instrumentCache = true;
  4275. }
  4276. }
  4277. });
  4278. blanket.options(newOptions);
  4279. if (typeof requirejs !== 'undefined'){
  4280. blanket.options("existingRequireJS",true);
  4281. }
  4282. /* setup requirejs loader, if needed */
  4283. if (blanket.options("commonJS")){
  4284. blanket._commonjs = {};
  4285. }
  4286. })();
  4287. (function(_blanket){
  4288. _blanket.extend({
  4289. utils: {
  4290. normalizeBackslashes: function(str) {
  4291. return str.replace(/\\/g, '/');
  4292. },
  4293. matchPatternAttribute: function(filename,pattern){
  4294. if (typeof pattern === 'string'){
  4295. if (pattern.indexOf("[") === 0){
  4296. //treat as array
  4297. var pattenArr = pattern.slice(1,pattern.length-1).split(",");
  4298. return pattenArr.some(function(elem){
  4299. return _blanket.utils.matchPatternAttribute(filename,_blanket.utils.normalizeBackslashes(elem.slice(1,-1)));
  4300. //return filename.indexOf(_blanket.utils.normalizeBackslashes(elem.slice(1,-1))) > -1;
  4301. });
  4302. }else if ( pattern.indexOf("//") === 0){
  4303. var ex = pattern.slice(2,pattern.lastIndexOf('/'));
  4304. var mods = pattern.slice(pattern.lastIndexOf('/')+1);
  4305. var regex = new RegExp(ex,mods);
  4306. return regex.test(filename);
  4307. }else if (pattern.indexOf("#") === 0){
  4308. return window[pattern.slice(1)].call(window,filename);
  4309. }else{
  4310. return filename.indexOf(_blanket.utils.normalizeBackslashes(pattern)) > -1;
  4311. }
  4312. }else if ( pattern instanceof Array ){
  4313. return pattern.some(function(elem){
  4314. return _blanket.utils.matchPatternAttribute(filename,elem);
  4315. });
  4316. }else if (pattern instanceof RegExp){
  4317. return pattern.test(filename);
  4318. }else if (typeof pattern === "function"){
  4319. return pattern.call(window,filename);
  4320. }
  4321. },
  4322. blanketEval: function(data){
  4323. _blanket._addScript(data);
  4324. },
  4325. collectPageScripts: function(){
  4326. var toArray = Array.prototype.slice;
  4327. var scripts = toArray.call(document.scripts);
  4328. var selectedScripts=[],scriptNames=[];
  4329. var filter = _blanket.options("filter");
  4330. if(filter != null){
  4331. //global filter in place, data-cover-only
  4332. var antimatch = _blanket.options("antifilter");
  4333. selectedScripts = toArray.call(document.scripts)
  4334. .filter(function(s){
  4335. return toArray.call(s.attributes).filter(function(sn){
  4336. return sn.nodeName === "src" && _blanket.utils.matchPatternAttribute(sn.nodeValue,filter) &&
  4337. (typeof antimatch === "undefined" || !_blanket.utils.matchPatternAttribute(sn.nodeValue,antimatch));
  4338. }).length === 1;
  4339. });
  4340. }else{
  4341. selectedScripts = toArray.call(document.querySelectorAll("script[data-cover]"));
  4342. }
  4343. scriptNames = selectedScripts.map(function(s){
  4344. return _blanket.utils.qualifyURL(
  4345. toArray.call(s.attributes).filter(
  4346. function(sn){
  4347. return sn.nodeName === "src";
  4348. })[0].nodeValue).replace(".js","");
  4349. });
  4350. if (!filter){
  4351. _blanket.options("filter","['"+scriptNames.join("','")+"']");
  4352. }
  4353. return scriptNames;
  4354. },
  4355. loadAll: function(nextScript,cb,preprocessor){
  4356. /**
  4357. * load dependencies
  4358. * @param {nextScript} factory for priority level
  4359. * @param {cb} the done callback
  4360. */
  4361. var currScript=nextScript();
  4362. var isLoaded = _blanket.utils.scriptIsLoaded(
  4363. currScript,
  4364. _blanket.utils.ifOrdered,
  4365. nextScript,
  4366. cb
  4367. );
  4368. if (!(_blanket.utils.cache[currScript] && _blanket.utils.cache[currScript].loaded)){
  4369. var attach = function(){
  4370. if (_blanket.options("debug")) {console.log("BLANKET-Mark script:"+currScript+", as loaded and move to next script.");}
  4371. isLoaded();
  4372. };
  4373. var whenDone = function(result){
  4374. if (_blanket.options("debug")) {console.log("BLANKET-File loading finished");}
  4375. if (typeof result !== 'undefined'){
  4376. if (_blanket.options("debug")) {console.log("BLANKET-Add file to DOM.");}
  4377. _blanket._addScript(result);
  4378. }
  4379. attach();
  4380. };
  4381. _blanket.utils.attachScript(
  4382. {
  4383. url: currScript
  4384. },
  4385. function (content){
  4386. _blanket.utils.processFile(
  4387. content,
  4388. currScript,
  4389. whenDone,
  4390. whenDone
  4391. );
  4392. }
  4393. );
  4394. }else{
  4395. isLoaded();
  4396. }
  4397. },
  4398. attachScript: function(options,cb){
  4399. var timeout = _blanket.options("timeout") || 3000;
  4400. setTimeout(function(){
  4401. if (!_blanket.utils.cache[options.url].loaded){
  4402. throw new Error("error loading source script");
  4403. }
  4404. },timeout);
  4405. _blanket.utils.getFile(
  4406. options.url,
  4407. cb,
  4408. function(){ throw new Error("error loading source script");}
  4409. );
  4410. },
  4411. ifOrdered: function(nextScript,cb){
  4412. /**
  4413. * ordered loading callback
  4414. * @param {nextScript} factory for priority level
  4415. * @param {cb} the done callback
  4416. */
  4417. var currScript = nextScript(true);
  4418. if (currScript){
  4419. _blanket.utils.loadAll(nextScript,cb);
  4420. }else{
  4421. cb(new Error("Error in loading chain."));
  4422. }
  4423. },
  4424. scriptIsLoaded: function(url,orderedCb,nextScript,cb){
  4425. /**
  4426. * returns a callback that checks a loading list to see if a script is loaded.
  4427. * @param {orderedCb} callback if ordered loading is being done
  4428. * @param {nextScript} factory for next priority level
  4429. * @param {cb} the done callback
  4430. */
  4431. if (_blanket.options("debug")) {console.log("BLANKET-Returning function");}
  4432. return function(){
  4433. if (_blanket.options("debug")) {console.log("BLANKET-Marking file as loaded: "+url);}
  4434. _blanket.utils.cache[url].loaded=true;
  4435. if (_blanket.utils.allLoaded()){
  4436. if (_blanket.options("debug")) {console.log("BLANKET-All files loaded");}
  4437. cb();
  4438. }else if (orderedCb){
  4439. //if it's ordered we need to
  4440. //traverse down to the next
  4441. //priority level
  4442. if (_blanket.options("debug")) {console.log("BLANKET-Load next file.");}
  4443. orderedCb(nextScript,cb);
  4444. }
  4445. };
  4446. },
  4447. cache: {},
  4448. allLoaded: function (){
  4449. /**
  4450. * check if depdencies are loaded in cache
  4451. */
  4452. var cached = Object.keys(_blanket.utils.cache);
  4453. for (var i=0;i<cached.length;i++){
  4454. if (!_blanket.utils.cache[cached[i]].loaded){
  4455. return false;
  4456. }
  4457. }
  4458. return true;
  4459. },
  4460. processFile: function (content,url,cb,oldCb) {
  4461. var match = _blanket.options("filter");
  4462. //we check the never matches first
  4463. var antimatch = _blanket.options("antifilter");
  4464. if (typeof antimatch !== "undefined" &&
  4465. _blanket.utils.matchPatternAttribute(url.replace(/\.js$/,""),antimatch)
  4466. ){
  4467. oldCb(content);
  4468. if (_blanket.options("debug")) {console.log("BLANKET-File will never be instrumented:"+url);}
  4469. _blanket.requiringFile(url,true);
  4470. }else if (_blanket.utils.matchPatternAttribute(url.replace(/\.js$/,""),match)){
  4471. if (_blanket.options("debug")) {console.log("BLANKET-Attempting instrument of:"+url);}
  4472. _blanket.instrument({
  4473. inputFile: content,
  4474. inputFileName: url
  4475. },function(instrumented){
  4476. try{
  4477. if (_blanket.options("debug")) {console.log("BLANKET-instrument of:"+url+" was successfull.");}
  4478. _blanket.utils.blanketEval(instrumented);
  4479. cb();
  4480. _blanket.requiringFile(url,true);
  4481. }
  4482. catch(err){
  4483. if (_blanket.options("ignoreScriptError")){
  4484. //we can continue like normal if
  4485. //we're ignoring script errors,
  4486. //but otherwise we don't want
  4487. //to completeLoad or the error might be
  4488. //missed.
  4489. if (_blanket.options("debug")) { console.log("BLANKET-There was an error loading the file:"+url); }
  4490. cb(content);
  4491. _blanket.requiringFile(url,true);
  4492. }else{
  4493. throw new Error("Error parsing instrumented code: "+err);
  4494. }
  4495. }
  4496. });
  4497. }else{
  4498. if (_blanket.options("debug")) { console.log("BLANKET-Loading (without instrumenting) the file:"+url);}
  4499. oldCb(content);
  4500. _blanket.requiringFile(url,true);
  4501. }
  4502. },
  4503. createXhr: function(){
  4504. var xhr, i, progId;
  4505. if (typeof XMLHttpRequest !== "undefined") {
  4506. return new XMLHttpRequest();
  4507. } else if (typeof ActiveXObject !== "undefined") {
  4508. for (i = 0; i < 3; i += 1) {
  4509. progId = progIds[i];
  4510. try {
  4511. xhr = new ActiveXObject(progId);
  4512. } catch (e) {}
  4513. if (xhr) {
  4514. progIds = [progId]; // so faster next time
  4515. break;
  4516. }
  4517. }
  4518. }
  4519. return xhr;
  4520. },
  4521. getFile: function(url, callback, errback, onXhr){
  4522. var foundInSession = false;
  4523. if (_blanket.blanketSession){
  4524. var files = Object.keys(_blanket.blanketSession);
  4525. for (var i=0; i<files.length;i++ ){
  4526. var key = files[i];
  4527. if (url.indexOf(key) > -1){
  4528. callback(_blanket.blanketSession[key]);
  4529. foundInSession=true;
  4530. return;
  4531. }
  4532. }
  4533. }
  4534. if (!foundInSession){
  4535. var xhr = _blanket.utils.createXhr();
  4536. xhr.open('GET', url, true);
  4537. //Allow overrides specified in config
  4538. if (onXhr) {
  4539. onXhr(xhr, url);
  4540. }
  4541. xhr.onreadystatechange = function (evt) {
  4542. var status, err;
  4543. //Do not explicitly handle errors, those should be
  4544. //visible via console output in the browser.
  4545. if (xhr.readyState === 4) {
  4546. status = xhr.status;
  4547. if ((status > 399 && status < 600) /*||
  4548. (status === 0 &&
  4549. navigator.userAgent.toLowerCase().indexOf('firefox') > -1)
  4550. */ ) {
  4551. //An http 4xx or 5xx error. Signal an error.
  4552. err = new Error(url + ' HTTP status: ' + status);
  4553. err.xhr = xhr;
  4554. errback(err);
  4555. } else {
  4556. callback(xhr.responseText);
  4557. }
  4558. }
  4559. };
  4560. try{
  4561. xhr.send(null);
  4562. }catch(e){
  4563. if (e.code && (e.code === 101 || e.code === 1012) && _blanket.options("ignoreCors") === false){
  4564. //running locally and getting error from browser
  4565. _blanket.showManualLoader();
  4566. } else {
  4567. throw e;
  4568. }
  4569. }
  4570. }
  4571. }
  4572. }
  4573. });
  4574. (function(){
  4575. var require = blanket.options("commonJS") ? blanket._commonjs.require : window.require;
  4576. var requirejs = blanket.options("commonJS") ? blanket._commonjs.requirejs : window.requirejs;
  4577. if (!_blanket.options("engineOnly") && _blanket.options("existingRequireJS")){
  4578. _blanket.utils.oldloader = requirejs.load;
  4579. requirejs.load = function (context, moduleName, url) {
  4580. _blanket.requiringFile(url);
  4581. _blanket.utils.getFile(url,
  4582. function(content){
  4583. _blanket.utils.processFile(
  4584. content,
  4585. url,
  4586. function newLoader(){
  4587. context.completeLoad(moduleName);
  4588. },
  4589. function oldLoader(){
  4590. _blanket.utils.oldloader(context, moduleName, url);
  4591. }
  4592. );
  4593. }, function (err) {
  4594. _blanket.requiringFile();
  4595. throw err;
  4596. });
  4597. };
  4598. }
  4599. })();
  4600. })(blanket);
  4601. (function() {
  4602. if (! jasmine) {
  4603. throw new Exception("jasmine library does not exist in global namespace!");
  4604. }
  4605. function elapsed(startTime, endTime) {
  4606. return (endTime - startTime)/1000;
  4607. }
  4608. function ISODateString(d) {
  4609. function pad(n) { return n < 10 ? '0'+n : n; }
  4610. return d.getFullYear() + '-' +
  4611. pad(d.getMonth()+1) + '-' +
  4612. pad(d.getDate()) + 'T' +
  4613. pad(d.getHours()) + ':' +
  4614. pad(d.getMinutes()) + ':' +
  4615. pad(d.getSeconds());
  4616. }
  4617. function trim(str) {
  4618. return str.replace(/^\s+/, "" ).replace(/\s+$/, "" );
  4619. }
  4620. function escapeInvalidXmlChars(str) {
  4621. return str.replace(/\&/g, "&amp;")
  4622. .replace(/</g, "&lt;")
  4623. .replace(/\>/g, "&gt;")
  4624. .replace(/\"/g, "&quot;")
  4625. .replace(/\'/g, "&apos;");
  4626. }
  4627. /**
  4628. * based on https://raw.github.com/larrymyers/jasmine-reporters/master/src/jasmine.junit_reporter.js
  4629. */
  4630. var BlanketReporter = function(savePath, consolidate, useDotNotation) {
  4631. blanket.setupCoverage();
  4632. };
  4633. BlanketReporter.finished_at = null; // will be updated after all files have been written
  4634. BlanketReporter.prototype = {
  4635. reportSpecStarting: function(spec) {
  4636. blanket.onTestStart();
  4637. },
  4638. reportSpecResults: function(suite) {
  4639. var results = suite.results();
  4640. blanket.onTestDone(results.totalCount,results.passed());
  4641. },
  4642. reportRunnerResults: function(runner) {
  4643. blanket.onTestsDone();
  4644. },
  4645. log: function(str) {
  4646. var console = jasmine.getGlobal().console;
  4647. if (console && console.log) {
  4648. console.log(str);
  4649. }
  4650. }
  4651. };
  4652. // export public
  4653. jasmine.BlanketReporter = BlanketReporter;
  4654. //override existing jasmine execute
  4655. jasmine.getEnv().execute = function(){ console.log("waiting for blanket..."); };
  4656. //check to make sure requirejs is completed before we start the test runner
  4657. var allLoaded = function() {
  4658. return window.jasmine.getEnv().currentRunner().specs().length > 0 && blanket.requireFilesLoaded();
  4659. };
  4660. blanket.beforeStartTestRunner({
  4661. checkRequirejs:true,
  4662. condition: allLoaded,
  4663. callback:function(){
  4664. jasmine.getEnv().addReporter(new jasmine.BlanketReporter());
  4665. window.jasmine.getEnv().currentRunner().execute();
  4666. jasmine.getEnv().execute = function () {
  4667. jasmine.getEnv().currentRunner().execute();
  4668. };
  4669. }
  4670. });
  4671. })();