PageRenderTime 90ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 1ms

/dist/mocha/blanket_mocha.js

https://github.com/timplourde/blanket
JavaScript | 5287 lines | 4925 code | 198 blank | 164 comment | 335 complexity | c6b9975cfff3cb5cbe4435d3d0735eff MD5 | raw file
Possible License(s): MIT
  1. /*! blanket - v1.1.5 */
  2. (function(define){
  3. /*
  4. Copyright (C) 2013 Ariya Hidayat <ariya.hidayat@gmail.com>
  5. Copyright (C) 2013 Thaddee Tyl <thaddee.tyl@gmail.com>
  6. Copyright (C) 2013 Mathias Bynens <mathias@qiwi.be>
  7. Copyright (C) 2012 Ariya Hidayat <ariya.hidayat@gmail.com>
  8. Copyright (C) 2012 Mathias Bynens <mathias@qiwi.be>
  9. Copyright (C) 2012 Joost-Wim Boekesteijn <joost-wim@boekesteijn.nl>
  10. Copyright (C) 2012 Kris Kowal <kris.kowal@cixar.com>
  11. Copyright (C) 2012 Yusuke Suzuki <utatane.tea@gmail.com>
  12. Copyright (C) 2012 Arpad Borsos <arpad.borsos@googlemail.com>
  13. Copyright (C) 2011 Ariya Hidayat <ariya.hidayat@gmail.com>
  14. Redistribution and use in source and binary forms, with or without
  15. modification, are permitted provided that the following conditions are met:
  16. * Redistributions of source code must retain the above copyright
  17. notice, this list of conditions and the following disclaimer.
  18. * Redistributions in binary form must reproduce the above copyright
  19. notice, this list of conditions and the following disclaimer in the
  20. documentation and/or other materials provided with the distribution.
  21. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  22. AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  23. IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  24. ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
  25. DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  26. (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  27. LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  28. ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  29. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  30. THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  31. */
  32. /*jslint bitwise:true plusplus:true */
  33. /*global esprima:true, define:true, exports:true, window: true,
  34. throwErrorTolerant: true,
  35. throwError: true, generateStatement: true, peek: true,
  36. parseAssignmentExpression: true, parseBlock: true, parseExpression: true,
  37. parseFunctionDeclaration: true, parseFunctionExpression: true,
  38. parseFunctionSourceElements: true, parseVariableIdentifier: true,
  39. parseLeftHandSideExpression: true,
  40. parseUnaryExpression: true,
  41. parseStatement: true, parseSourceElement: true */
  42. (function (root, factory) {
  43. 'use strict';
  44. // Universal Module Definition (UMD) to support AMD, CommonJS/Node.js,
  45. // Rhino, and plain browser loading.
  46. /* istanbul ignore next */
  47. if (typeof define === 'function' && define.amd) {
  48. define(['exports'], factory);
  49. } else if (typeof exports !== 'undefined') {
  50. factory(exports);
  51. } else {
  52. factory((root.esprima = {}));
  53. }
  54. }(this, function (exports) {
  55. 'use strict';
  56. var Token,
  57. TokenName,
  58. FnExprTokens,
  59. Syntax,
  60. PropertyKind,
  61. Messages,
  62. Regex,
  63. SyntaxTreeDelegate,
  64. source,
  65. strict,
  66. index,
  67. lineNumber,
  68. lineStart,
  69. length,
  70. delegate,
  71. lookahead,
  72. state,
  73. extra;
  74. Token = {
  75. BooleanLiteral: 1,
  76. EOF: 2,
  77. Identifier: 3,
  78. Keyword: 4,
  79. NullLiteral: 5,
  80. NumericLiteral: 6,
  81. Punctuator: 7,
  82. StringLiteral: 8,
  83. RegularExpression: 9
  84. };
  85. TokenName = {};
  86. TokenName[Token.BooleanLiteral] = 'Boolean';
  87. TokenName[Token.EOF] = '<end>';
  88. TokenName[Token.Identifier] = 'Identifier';
  89. TokenName[Token.Keyword] = 'Keyword';
  90. TokenName[Token.NullLiteral] = 'Null';
  91. TokenName[Token.NumericLiteral] = 'Numeric';
  92. TokenName[Token.Punctuator] = 'Punctuator';
  93. TokenName[Token.StringLiteral] = 'String';
  94. TokenName[Token.RegularExpression] = 'RegularExpression';
  95. // A function following one of those tokens is an expression.
  96. FnExprTokens = ['(', '{', '[', 'in', 'typeof', 'instanceof', 'new',
  97. 'return', 'case', 'delete', 'throw', 'void',
  98. // assignment operators
  99. '=', '+=', '-=', '*=', '/=', '%=', '<<=', '>>=', '>>>=',
  100. '&=', '|=', '^=', ',',
  101. // binary/unary operators
  102. '+', '-', '*', '/', '%', '++', '--', '<<', '>>', '>>>', '&',
  103. '|', '^', '!', '~', '&&', '||', '?', ':', '===', '==', '>=',
  104. '<=', '<', '>', '!=', '!=='];
  105. Syntax = {
  106. AssignmentExpression: 'AssignmentExpression',
  107. ArrayExpression: 'ArrayExpression',
  108. BlockStatement: 'BlockStatement',
  109. BinaryExpression: 'BinaryExpression',
  110. BreakStatement: 'BreakStatement',
  111. CallExpression: 'CallExpression',
  112. CatchClause: 'CatchClause',
  113. ConditionalExpression: 'ConditionalExpression',
  114. ContinueStatement: 'ContinueStatement',
  115. DoWhileStatement: 'DoWhileStatement',
  116. DebuggerStatement: 'DebuggerStatement',
  117. EmptyStatement: 'EmptyStatement',
  118. ExpressionStatement: 'ExpressionStatement',
  119. ForStatement: 'ForStatement',
  120. ForInStatement: 'ForInStatement',
  121. FunctionDeclaration: 'FunctionDeclaration',
  122. FunctionExpression: 'FunctionExpression',
  123. Identifier: 'Identifier',
  124. IfStatement: 'IfStatement',
  125. Literal: 'Literal',
  126. LabeledStatement: 'LabeledStatement',
  127. LogicalExpression: 'LogicalExpression',
  128. MemberExpression: 'MemberExpression',
  129. NewExpression: 'NewExpression',
  130. ObjectExpression: 'ObjectExpression',
  131. Program: 'Program',
  132. Property: 'Property',
  133. ReturnStatement: 'ReturnStatement',
  134. SequenceExpression: 'SequenceExpression',
  135. SwitchStatement: 'SwitchStatement',
  136. SwitchCase: 'SwitchCase',
  137. ThisExpression: 'ThisExpression',
  138. ThrowStatement: 'ThrowStatement',
  139. TryStatement: 'TryStatement',
  140. UnaryExpression: 'UnaryExpression',
  141. UpdateExpression: 'UpdateExpression',
  142. VariableDeclaration: 'VariableDeclaration',
  143. VariableDeclarator: 'VariableDeclarator',
  144. WhileStatement: 'WhileStatement',
  145. WithStatement: 'WithStatement'
  146. };
  147. PropertyKind = {
  148. Data: 1,
  149. Get: 2,
  150. Set: 4
  151. };
  152. // Error messages should be identical to V8.
  153. Messages = {
  154. UnexpectedToken: 'Unexpected token %0',
  155. UnexpectedNumber: 'Unexpected number',
  156. UnexpectedString: 'Unexpected string',
  157. UnexpectedIdentifier: 'Unexpected identifier',
  158. UnexpectedReserved: 'Unexpected reserved word',
  159. UnexpectedEOS: 'Unexpected end of input',
  160. NewlineAfterThrow: 'Illegal newline after throw',
  161. InvalidRegExp: 'Invalid regular expression',
  162. UnterminatedRegExp: 'Invalid regular expression: missing /',
  163. InvalidLHSInAssignment: 'Invalid left-hand side in assignment',
  164. InvalidLHSInForIn: 'Invalid left-hand side in for-in',
  165. MultipleDefaultsInSwitch: 'More than one default clause in switch statement',
  166. NoCatchOrFinally: 'Missing catch or finally after try',
  167. UnknownLabel: 'Undefined label \'%0\'',
  168. Redeclaration: '%0 \'%1\' has already been declared',
  169. IllegalContinue: 'Illegal continue statement',
  170. IllegalBreak: 'Illegal break statement',
  171. IllegalReturn: 'Illegal return statement',
  172. StrictModeWith: 'Strict mode code may not include a with statement',
  173. StrictCatchVariable: 'Catch variable may not be eval or arguments in strict mode',
  174. StrictVarName: 'Variable name may not be eval or arguments in strict mode',
  175. StrictParamName: 'Parameter name eval or arguments is not allowed in strict mode',
  176. StrictParamDupe: 'Strict mode function may not have duplicate parameter names',
  177. StrictFunctionName: 'Function name may not be eval or arguments in strict mode',
  178. StrictOctalLiteral: 'Octal literals are not allowed in strict mode.',
  179. StrictDelete: 'Delete of an unqualified identifier in strict mode.',
  180. StrictDuplicateProperty: 'Duplicate data property in object literal not allowed in strict mode',
  181. AccessorDataProperty: 'Object literal may not have data and accessor property with the same name',
  182. AccessorGetSet: 'Object literal may not have multiple get/set accessors with the same name',
  183. StrictLHSAssignment: 'Assignment to eval or arguments is not allowed in strict mode',
  184. StrictLHSPostfix: 'Postfix increment/decrement may not have eval or arguments operand in strict mode',
  185. StrictLHSPrefix: 'Prefix increment/decrement may not have eval or arguments operand in strict mode',
  186. StrictReservedWord: 'Use of future reserved word in strict mode'
  187. };
  188. // See also tools/generate-unicode-regex.py.
  189. Regex = {
  190. 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]'),
  191. 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]')
  192. };
  193. // Ensure the condition is true, otherwise throw an error.
  194. // This is only to have a better contract semantic, i.e. another safety net
  195. // to catch a logic error. The condition shall be fulfilled in normal case.
  196. // Do NOT use this to enforce a certain condition on any user input.
  197. function assert(condition, message) {
  198. /* istanbul ignore if */
  199. if (!condition) {
  200. throw new Error('ASSERT: ' + message);
  201. }
  202. }
  203. function isDecimalDigit(ch) {
  204. return (ch >= 48 && ch <= 57); // 0..9
  205. }
  206. function isHexDigit(ch) {
  207. return '0123456789abcdefABCDEF'.indexOf(ch) >= 0;
  208. }
  209. function isOctalDigit(ch) {
  210. return '01234567'.indexOf(ch) >= 0;
  211. }
  212. // 7.2 White Space
  213. function isWhiteSpace(ch) {
  214. return (ch === 0x20) || (ch === 0x09) || (ch === 0x0B) || (ch === 0x0C) || (ch === 0xA0) ||
  215. (ch >= 0x1680 && [0x1680, 0x180E, 0x2000, 0x2001, 0x2002, 0x2003, 0x2004, 0x2005, 0x2006, 0x2007, 0x2008, 0x2009, 0x200A, 0x202F, 0x205F, 0x3000, 0xFEFF].indexOf(ch) >= 0);
  216. }
  217. // 7.3 Line Terminators
  218. function isLineTerminator(ch) {
  219. return (ch === 0x0A) || (ch === 0x0D) || (ch === 0x2028) || (ch === 0x2029);
  220. }
  221. // 7.6 Identifier Names and Identifiers
  222. function isIdentifierStart(ch) {
  223. return (ch === 0x24) || (ch === 0x5F) || // $ (dollar) and _ (underscore)
  224. (ch >= 0x41 && ch <= 0x5A) || // A..Z
  225. (ch >= 0x61 && ch <= 0x7A) || // a..z
  226. (ch === 0x5C) || // \ (backslash)
  227. ((ch >= 0x80) && Regex.NonAsciiIdentifierStart.test(String.fromCharCode(ch)));
  228. }
  229. function isIdentifierPart(ch) {
  230. return (ch === 0x24) || (ch === 0x5F) || // $ (dollar) and _ (underscore)
  231. (ch >= 0x41 && ch <= 0x5A) || // A..Z
  232. (ch >= 0x61 && ch <= 0x7A) || // a..z
  233. (ch >= 0x30 && ch <= 0x39) || // 0..9
  234. (ch === 0x5C) || // \ (backslash)
  235. ((ch >= 0x80) && Regex.NonAsciiIdentifierPart.test(String.fromCharCode(ch)));
  236. }
  237. // 7.6.1.2 Future Reserved Words
  238. function isFutureReservedWord(id) {
  239. switch (id) {
  240. case 'class':
  241. case 'enum':
  242. case 'export':
  243. case 'extends':
  244. case 'import':
  245. case 'super':
  246. return true;
  247. default:
  248. return false;
  249. }
  250. }
  251. function isStrictModeReservedWord(id) {
  252. switch (id) {
  253. case 'implements':
  254. case 'interface':
  255. case 'package':
  256. case 'private':
  257. case 'protected':
  258. case 'public':
  259. case 'static':
  260. case 'yield':
  261. case 'let':
  262. return true;
  263. default:
  264. return false;
  265. }
  266. }
  267. function isRestrictedWord(id) {
  268. return id === 'eval' || id === 'arguments';
  269. }
  270. // 7.6.1.1 Keywords
  271. function isKeyword(id) {
  272. if (strict && isStrictModeReservedWord(id)) {
  273. return true;
  274. }
  275. // 'const' is specialized as Keyword in V8.
  276. // 'yield' and 'let' are for compatiblity with SpiderMonkey and ES.next.
  277. // Some others are from future reserved words.
  278. switch (id.length) {
  279. case 2:
  280. return (id === 'if') || (id === 'in') || (id === 'do');
  281. case 3:
  282. return (id === 'var') || (id === 'for') || (id === 'new') ||
  283. (id === 'try') || (id === 'let');
  284. case 4:
  285. return (id === 'this') || (id === 'else') || (id === 'case') ||
  286. (id === 'void') || (id === 'with') || (id === 'enum');
  287. case 5:
  288. return (id === 'while') || (id === 'break') || (id === 'catch') ||
  289. (id === 'throw') || (id === 'const') || (id === 'yield') ||
  290. (id === 'class') || (id === 'super');
  291. case 6:
  292. return (id === 'return') || (id === 'typeof') || (id === 'delete') ||
  293. (id === 'switch') || (id === 'export') || (id === 'import');
  294. case 7:
  295. return (id === 'default') || (id === 'finally') || (id === 'extends');
  296. case 8:
  297. return (id === 'function') || (id === 'continue') || (id === 'debugger');
  298. case 10:
  299. return (id === 'instanceof');
  300. default:
  301. return false;
  302. }
  303. }
  304. // 7.4 Comments
  305. function addComment(type, value, start, end, loc) {
  306. var comment, attacher;
  307. assert(typeof start === 'number', 'Comment must have valid position');
  308. // Because the way the actual token is scanned, often the comments
  309. // (if any) are skipped twice during the lexical analysis.
  310. // Thus, we need to skip adding a comment if the comment array already
  311. // handled it.
  312. if (state.lastCommentStart >= start) {
  313. return;
  314. }
  315. state.lastCommentStart = start;
  316. comment = {
  317. type: type,
  318. value: value
  319. };
  320. if (extra.range) {
  321. comment.range = [start, end];
  322. }
  323. if (extra.loc) {
  324. comment.loc = loc;
  325. }
  326. extra.comments.push(comment);
  327. if (extra.attachComment) {
  328. extra.leadingComments.push(comment);
  329. extra.trailingComments.push(comment);
  330. }
  331. }
  332. function skipSingleLineComment(offset) {
  333. var start, loc, ch, comment;
  334. start = index - offset;
  335. loc = {
  336. start: {
  337. line: lineNumber,
  338. column: index - lineStart - offset
  339. }
  340. };
  341. while (index < length) {
  342. ch = source.charCodeAt(index);
  343. ++index;
  344. if (isLineTerminator(ch)) {
  345. if (extra.comments) {
  346. comment = source.slice(start + offset, index - 1);
  347. loc.end = {
  348. line: lineNumber,
  349. column: index - lineStart - 1
  350. };
  351. addComment('Line', comment, start, index - 1, loc);
  352. }
  353. if (ch === 13 && source.charCodeAt(index) === 10) {
  354. ++index;
  355. }
  356. ++lineNumber;
  357. lineStart = index;
  358. return;
  359. }
  360. }
  361. if (extra.comments) {
  362. comment = source.slice(start + offset, index);
  363. loc.end = {
  364. line: lineNumber,
  365. column: index - lineStart
  366. };
  367. addComment('Line', comment, start, index, loc);
  368. }
  369. }
  370. function skipMultiLineComment() {
  371. var start, loc, ch, comment;
  372. if (extra.comments) {
  373. start = index - 2;
  374. loc = {
  375. start: {
  376. line: lineNumber,
  377. column: index - lineStart - 2
  378. }
  379. };
  380. }
  381. while (index < length) {
  382. ch = source.charCodeAt(index);
  383. if (isLineTerminator(ch)) {
  384. if (ch === 0x0D && source.charCodeAt(index + 1) === 0x0A) {
  385. ++index;
  386. }
  387. ++lineNumber;
  388. ++index;
  389. lineStart = index;
  390. if (index >= length) {
  391. throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
  392. }
  393. } else if (ch === 0x2A) {
  394. // Block comment ends with '*/'.
  395. if (source.charCodeAt(index + 1) === 0x2F) {
  396. ++index;
  397. ++index;
  398. if (extra.comments) {
  399. comment = source.slice(start + 2, index - 2);
  400. loc.end = {
  401. line: lineNumber,
  402. column: index - lineStart
  403. };
  404. addComment('Block', comment, start, index, loc);
  405. }
  406. return;
  407. }
  408. ++index;
  409. } else {
  410. ++index;
  411. }
  412. }
  413. throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
  414. }
  415. function skipComment() {
  416. var ch, start;
  417. start = (index === 0);
  418. while (index < length) {
  419. ch = source.charCodeAt(index);
  420. if (isWhiteSpace(ch)) {
  421. ++index;
  422. } else if (isLineTerminator(ch)) {
  423. ++index;
  424. if (ch === 0x0D && source.charCodeAt(index) === 0x0A) {
  425. ++index;
  426. }
  427. ++lineNumber;
  428. lineStart = index;
  429. start = true;
  430. } else if (ch === 0x2F) { // U+002F is '/'
  431. ch = source.charCodeAt(index + 1);
  432. if (ch === 0x2F) {
  433. ++index;
  434. ++index;
  435. skipSingleLineComment(2);
  436. start = true;
  437. } else if (ch === 0x2A) { // U+002A is '*'
  438. ++index;
  439. ++index;
  440. skipMultiLineComment();
  441. } else {
  442. break;
  443. }
  444. } else if (start && ch === 0x2D) { // U+002D is '-'
  445. // U+003E is '>'
  446. if ((source.charCodeAt(index + 1) === 0x2D) && (source.charCodeAt(index + 2) === 0x3E)) {
  447. // '-->' is a single-line comment
  448. index += 3;
  449. skipSingleLineComment(3);
  450. } else {
  451. break;
  452. }
  453. } else if (ch === 0x3C) { // U+003C is '<'
  454. if (source.slice(index + 1, index + 4) === '!--') {
  455. ++index; // `<`
  456. ++index; // `!`
  457. ++index; // `-`
  458. ++index; // `-`
  459. skipSingleLineComment(4);
  460. } else {
  461. break;
  462. }
  463. } else {
  464. break;
  465. }
  466. }
  467. }
  468. function scanHexEscape(prefix) {
  469. var i, len, ch, code = 0;
  470. len = (prefix === 'u') ? 4 : 2;
  471. for (i = 0; i < len; ++i) {
  472. if (index < length && isHexDigit(source[index])) {
  473. ch = source[index++];
  474. code = code * 16 + '0123456789abcdef'.indexOf(ch.toLowerCase());
  475. } else {
  476. return '';
  477. }
  478. }
  479. return String.fromCharCode(code);
  480. }
  481. function getEscapedIdentifier() {
  482. var ch, id;
  483. ch = source.charCodeAt(index++);
  484. id = String.fromCharCode(ch);
  485. // '\u' (U+005C, U+0075) denotes an escaped character.
  486. if (ch === 0x5C) {
  487. if (source.charCodeAt(index) !== 0x75) {
  488. throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
  489. }
  490. ++index;
  491. ch = scanHexEscape('u');
  492. if (!ch || ch === '\\' || !isIdentifierStart(ch.charCodeAt(0))) {
  493. throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
  494. }
  495. id = ch;
  496. }
  497. while (index < length) {
  498. ch = source.charCodeAt(index);
  499. if (!isIdentifierPart(ch)) {
  500. break;
  501. }
  502. ++index;
  503. id += String.fromCharCode(ch);
  504. // '\u' (U+005C, U+0075) denotes an escaped character.
  505. if (ch === 0x5C) {
  506. id = id.substr(0, id.length - 1);
  507. if (source.charCodeAt(index) !== 0x75) {
  508. throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
  509. }
  510. ++index;
  511. ch = scanHexEscape('u');
  512. if (!ch || ch === '\\' || !isIdentifierPart(ch.charCodeAt(0))) {
  513. throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
  514. }
  515. id += ch;
  516. }
  517. }
  518. return id;
  519. }
  520. function getIdentifier() {
  521. var start, ch;
  522. start = index++;
  523. while (index < length) {
  524. ch = source.charCodeAt(index);
  525. if (ch === 0x5C) {
  526. // Blackslash (U+005C) marks Unicode escape sequence.
  527. index = start;
  528. return getEscapedIdentifier();
  529. }
  530. if (isIdentifierPart(ch)) {
  531. ++index;
  532. } else {
  533. break;
  534. }
  535. }
  536. return source.slice(start, index);
  537. }
  538. function scanIdentifier() {
  539. var start, id, type;
  540. start = index;
  541. // Backslash (U+005C) starts an escaped character.
  542. id = (source.charCodeAt(index) === 0x5C) ? getEscapedIdentifier() : getIdentifier();
  543. // There is no keyword or literal with only one character.
  544. // Thus, it must be an identifier.
  545. if (id.length === 1) {
  546. type = Token.Identifier;
  547. } else if (isKeyword(id)) {
  548. type = Token.Keyword;
  549. } else if (id === 'null') {
  550. type = Token.NullLiteral;
  551. } else if (id === 'true' || id === 'false') {
  552. type = Token.BooleanLiteral;
  553. } else {
  554. type = Token.Identifier;
  555. }
  556. return {
  557. type: type,
  558. value: id,
  559. lineNumber: lineNumber,
  560. lineStart: lineStart,
  561. start: start,
  562. end: index
  563. };
  564. }
  565. // 7.7 Punctuators
  566. function scanPunctuator() {
  567. var start = index,
  568. code = source.charCodeAt(index),
  569. code2,
  570. ch1 = source[index],
  571. ch2,
  572. ch3,
  573. ch4;
  574. switch (code) {
  575. // Check for most common single-character punctuators.
  576. case 0x2E: // . dot
  577. case 0x28: // ( open bracket
  578. case 0x29: // ) close bracket
  579. case 0x3B: // ; semicolon
  580. case 0x2C: // , comma
  581. case 0x7B: // { open curly brace
  582. case 0x7D: // } close curly brace
  583. case 0x5B: // [
  584. case 0x5D: // ]
  585. case 0x3A: // :
  586. case 0x3F: // ?
  587. case 0x7E: // ~
  588. ++index;
  589. if (extra.tokenize) {
  590. if (code === 0x28) {
  591. extra.openParenToken = extra.tokens.length;
  592. } else if (code === 0x7B) {
  593. extra.openCurlyToken = extra.tokens.length;
  594. }
  595. }
  596. return {
  597. type: Token.Punctuator,
  598. value: String.fromCharCode(code),
  599. lineNumber: lineNumber,
  600. lineStart: lineStart,
  601. start: start,
  602. end: index
  603. };
  604. default:
  605. code2 = source.charCodeAt(index + 1);
  606. // '=' (U+003D) marks an assignment or comparison operator.
  607. if (code2 === 0x3D) {
  608. switch (code) {
  609. case 0x2B: // +
  610. case 0x2D: // -
  611. case 0x2F: // /
  612. case 0x3C: // <
  613. case 0x3E: // >
  614. case 0x5E: // ^
  615. case 0x7C: // |
  616. case 0x25: // %
  617. case 0x26: // &
  618. case 0x2A: // *
  619. index += 2;
  620. return {
  621. type: Token.Punctuator,
  622. value: String.fromCharCode(code) + String.fromCharCode(code2),
  623. lineNumber: lineNumber,
  624. lineStart: lineStart,
  625. start: start,
  626. end: index
  627. };
  628. case 0x21: // !
  629. case 0x3D: // =
  630. index += 2;
  631. // !== and ===
  632. if (source.charCodeAt(index) === 0x3D) {
  633. ++index;
  634. }
  635. return {
  636. type: Token.Punctuator,
  637. value: source.slice(start, index),
  638. lineNumber: lineNumber,
  639. lineStart: lineStart,
  640. start: start,
  641. end: index
  642. };
  643. }
  644. }
  645. }
  646. // 4-character punctuator: >>>=
  647. ch4 = source.substr(index, 4);
  648. if (ch4 === '>>>=') {
  649. index += 4;
  650. return {
  651. type: Token.Punctuator,
  652. value: ch4,
  653. lineNumber: lineNumber,
  654. lineStart: lineStart,
  655. start: start,
  656. end: index
  657. };
  658. }
  659. // 3-character punctuators: === !== >>> <<= >>=
  660. ch3 = ch4.substr(0, 3);
  661. if (ch3 === '>>>' || ch3 === '<<=' || ch3 === '>>=') {
  662. index += 3;
  663. return {
  664. type: Token.Punctuator,
  665. value: ch3,
  666. lineNumber: lineNumber,
  667. lineStart: lineStart,
  668. start: start,
  669. end: index
  670. };
  671. }
  672. // Other 2-character punctuators: ++ -- << >> && ||
  673. ch2 = ch3.substr(0, 2);
  674. if ((ch1 === ch2[1] && ('+-<>&|'.indexOf(ch1) >= 0)) || ch2 === '=>') {
  675. index += 2;
  676. return {
  677. type: Token.Punctuator,
  678. value: ch2,
  679. lineNumber: lineNumber,
  680. lineStart: lineStart,
  681. start: start,
  682. end: index
  683. };
  684. }
  685. // 1-character punctuators: < > = ! + - * % & | ^ /
  686. if ('<>=!+-*%&|^/'.indexOf(ch1) >= 0) {
  687. ++index;
  688. return {
  689. type: Token.Punctuator,
  690. value: ch1,
  691. lineNumber: lineNumber,
  692. lineStart: lineStart,
  693. start: start,
  694. end: index
  695. };
  696. }
  697. throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
  698. }
  699. // 7.8.3 Numeric Literals
  700. function scanHexLiteral(start) {
  701. var number = '';
  702. while (index < length) {
  703. if (!isHexDigit(source[index])) {
  704. break;
  705. }
  706. number += source[index++];
  707. }
  708. if (number.length === 0) {
  709. throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
  710. }
  711. if (isIdentifierStart(source.charCodeAt(index))) {
  712. throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
  713. }
  714. return {
  715. type: Token.NumericLiteral,
  716. value: parseInt('0x' + number, 16),
  717. lineNumber: lineNumber,
  718. lineStart: lineStart,
  719. start: start,
  720. end: index
  721. };
  722. }
  723. function scanOctalLiteral(start) {
  724. var number = '0' + source[index++];
  725. while (index < length) {
  726. if (!isOctalDigit(source[index])) {
  727. break;
  728. }
  729. number += source[index++];
  730. }
  731. if (isIdentifierStart(source.charCodeAt(index)) || isDecimalDigit(source.charCodeAt(index))) {
  732. throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
  733. }
  734. return {
  735. type: Token.NumericLiteral,
  736. value: parseInt(number, 8),
  737. octal: true,
  738. lineNumber: lineNumber,
  739. lineStart: lineStart,
  740. start: start,
  741. end: index
  742. };
  743. }
  744. function scanNumericLiteral() {
  745. var number, start, ch;
  746. ch = source[index];
  747. assert(isDecimalDigit(ch.charCodeAt(0)) || (ch === '.'),
  748. 'Numeric literal must start with a decimal digit or a decimal point');
  749. start = index;
  750. number = '';
  751. if (ch !== '.') {
  752. number = source[index++];
  753. ch = source[index];
  754. // Hex number starts with '0x'.
  755. // Octal number starts with '0'.
  756. if (number === '0') {
  757. if (ch === 'x' || ch === 'X') {
  758. ++index;
  759. return scanHexLiteral(start);
  760. }
  761. if (isOctalDigit(ch)) {
  762. return scanOctalLiteral(start);
  763. }
  764. // decimal number starts with '0' such as '09' is illegal.
  765. if (ch && isDecimalDigit(ch.charCodeAt(0))) {
  766. throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
  767. }
  768. }
  769. while (isDecimalDigit(source.charCodeAt(index))) {
  770. number += source[index++];
  771. }
  772. ch = source[index];
  773. }
  774. if (ch === '.') {
  775. number += source[index++];
  776. while (isDecimalDigit(source.charCodeAt(index))) {
  777. number += source[index++];
  778. }
  779. ch = source[index];
  780. }
  781. if (ch === 'e' || ch === 'E') {
  782. number += source[index++];
  783. ch = source[index];
  784. if (ch === '+' || ch === '-') {
  785. number += source[index++];
  786. }
  787. if (isDecimalDigit(source.charCodeAt(index))) {
  788. while (isDecimalDigit(source.charCodeAt(index))) {
  789. number += source[index++];
  790. }
  791. } else {
  792. throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
  793. }
  794. }
  795. if (isIdentifierStart(source.charCodeAt(index))) {
  796. throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
  797. }
  798. return {
  799. type: Token.NumericLiteral,
  800. value: parseFloat(number),
  801. lineNumber: lineNumber,
  802. lineStart: lineStart,
  803. start: start,
  804. end: index
  805. };
  806. }
  807. // 7.8.4 String Literals
  808. function scanStringLiteral() {
  809. var str = '', quote, start, ch, code, unescaped, restore, octal = false, startLineNumber, startLineStart;
  810. startLineNumber = lineNumber;
  811. startLineStart = lineStart;
  812. quote = source[index];
  813. assert((quote === '\'' || quote === '"'),
  814. 'String literal must starts with a quote');
  815. start = index;
  816. ++index;
  817. while (index < length) {
  818. ch = source[index++];
  819. if (ch === quote) {
  820. quote = '';
  821. break;
  822. } else if (ch === '\\') {
  823. ch = source[index++];
  824. if (!ch || !isLineTerminator(ch.charCodeAt(0))) {
  825. switch (ch) {
  826. case 'u':
  827. case 'x':
  828. restore = index;
  829. unescaped = scanHexEscape(ch);
  830. if (unescaped) {
  831. str += unescaped;
  832. } else {
  833. index = restore;
  834. str += ch;
  835. }
  836. break;
  837. case 'n':
  838. str += '\n';
  839. break;
  840. case 'r':
  841. str += '\r';
  842. break;
  843. case 't':
  844. str += '\t';
  845. break;
  846. case 'b':
  847. str += '\b';
  848. break;
  849. case 'f':
  850. str += '\f';
  851. break;
  852. case 'v':
  853. str += '\x0B';
  854. break;
  855. default:
  856. if (isOctalDigit(ch)) {
  857. code = '01234567'.indexOf(ch);
  858. // \0 is not octal escape sequence
  859. if (code !== 0) {
  860. octal = true;
  861. }
  862. if (index < length && isOctalDigit(source[index])) {
  863. octal = true;
  864. code = code * 8 + '01234567'.indexOf(source[index++]);
  865. // 3 digits are only allowed when string starts
  866. // with 0, 1, 2, 3
  867. if ('0123'.indexOf(ch) >= 0 &&
  868. index < length &&
  869. isOctalDigit(source[index])) {
  870. code = code * 8 + '01234567'.indexOf(source[index++]);
  871. }
  872. }
  873. str += String.fromCharCode(code);
  874. } else {
  875. str += ch;
  876. }
  877. break;
  878. }
  879. } else {
  880. ++lineNumber;
  881. if (ch === '\r' && source[index] === '\n') {
  882. ++index;
  883. }
  884. lineStart = index;
  885. }
  886. } else if (isLineTerminator(ch.charCodeAt(0))) {
  887. break;
  888. } else {
  889. str += ch;
  890. }
  891. }
  892. if (quote !== '') {
  893. throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
  894. }
  895. return {
  896. type: Token.StringLiteral,
  897. value: str,
  898. octal: octal,
  899. startLineNumber: startLineNumber,
  900. startLineStart: startLineStart,
  901. lineNumber: lineNumber,
  902. lineStart: lineStart,
  903. start: start,
  904. end: index
  905. };
  906. }
  907. function testRegExp(pattern, flags) {
  908. var value;
  909. try {
  910. value = new RegExp(pattern, flags);
  911. } catch (e) {
  912. throwError({}, Messages.InvalidRegExp);
  913. }
  914. return value;
  915. }
  916. function scanRegExpBody() {
  917. var ch, str, classMarker, terminated, body;
  918. ch = source[index];
  919. assert(ch === '/', 'Regular expression literal must start with a slash');
  920. str = source[index++];
  921. classMarker = false;
  922. terminated = false;
  923. while (index < length) {
  924. ch = source[index++];
  925. str += ch;
  926. if (ch === '\\') {
  927. ch = source[index++];
  928. // ECMA-262 7.8.5
  929. if (isLineTerminator(ch.charCodeAt(0))) {
  930. throwError({}, Messages.UnterminatedRegExp);
  931. }
  932. str += ch;
  933. } else if (isLineTerminator(ch.charCodeAt(0))) {
  934. throwError({}, Messages.UnterminatedRegExp);
  935. } else if (classMarker) {
  936. if (ch === ']') {
  937. classMarker = false;
  938. }
  939. } else {
  940. if (ch === '/') {
  941. terminated = true;
  942. break;
  943. } else if (ch === '[') {
  944. classMarker = true;
  945. }
  946. }
  947. }
  948. if (!terminated) {
  949. throwError({}, Messages.UnterminatedRegExp);
  950. }
  951. // Exclude leading and trailing slash.
  952. body = str.substr(1, str.length - 2);
  953. return {
  954. value: body,
  955. literal: str
  956. };
  957. }
  958. function scanRegExpFlags() {
  959. var ch, str, flags, restore;
  960. str = '';
  961. flags = '';
  962. while (index < length) {
  963. ch = source[index];
  964. if (!isIdentifierPart(ch.charCodeAt(0))) {
  965. break;
  966. }
  967. ++index;
  968. if (ch === '\\' && index < length) {
  969. ch = source[index];
  970. if (ch === 'u') {
  971. ++index;
  972. restore = index;
  973. ch = scanHexEscape('u');
  974. if (ch) {
  975. flags += ch;
  976. for (str += '\\u'; restore < index; ++restore) {
  977. str += source[restore];
  978. }
  979. } else {
  980. index = restore;
  981. flags += 'u';
  982. str += '\\u';
  983. }
  984. throwErrorTolerant({}, Messages.UnexpectedToken, 'ILLEGAL');
  985. } else {
  986. str += '\\';
  987. throwErrorTolerant({}, Messages.UnexpectedToken, 'ILLEGAL');
  988. }
  989. } else {
  990. flags += ch;
  991. str += ch;
  992. }
  993. }
  994. return {
  995. value: flags,
  996. literal: str
  997. };
  998. }
  999. function scanRegExp() {
  1000. var start, body, flags, pattern, value;
  1001. lookahead = null;
  1002. skipComment();
  1003. start = index;
  1004. body = scanRegExpBody();
  1005. flags = scanRegExpFlags();
  1006. value = testRegExp(body.value, flags.value);
  1007. if (extra.tokenize) {
  1008. return {
  1009. type: Token.RegularExpression,
  1010. value: value,
  1011. lineNumber: lineNumber,
  1012. lineStart: lineStart,
  1013. start: start,
  1014. end: index
  1015. };
  1016. }
  1017. return {
  1018. literal: body.literal + flags.literal,
  1019. value: value,
  1020. start: start,
  1021. end: index
  1022. };
  1023. }
  1024. function collectRegex() {
  1025. var pos, loc, regex, token;
  1026. skipComment();
  1027. pos = index;
  1028. loc = {
  1029. start: {
  1030. line: lineNumber,
  1031. column: index - lineStart
  1032. }
  1033. };
  1034. regex = scanRegExp();
  1035. loc.end = {
  1036. line: lineNumber,
  1037. column: index - lineStart
  1038. };
  1039. /* istanbul ignore next */
  1040. if (!extra.tokenize) {
  1041. // Pop the previous token, which is likely '/' or '/='
  1042. if (extra.tokens.length > 0) {
  1043. token = extra.tokens[extra.tokens.length - 1];
  1044. if (token.range[0] === pos && token.type === 'Punctuator') {
  1045. if (token.value === '/' || token.value === '/=') {
  1046. extra.tokens.pop();
  1047. }
  1048. }
  1049. }
  1050. extra.tokens.push({
  1051. type: 'RegularExpression',
  1052. value: regex.literal,
  1053. range: [pos, index],
  1054. loc: loc
  1055. });
  1056. }
  1057. return regex;
  1058. }
  1059. function isIdentifierName(token) {
  1060. return token.type === Token.Identifier ||
  1061. token.type === Token.Keyword ||
  1062. token.type === Token.BooleanLiteral ||
  1063. token.type === Token.NullLiteral;
  1064. }
  1065. function advanceSlash() {
  1066. var prevToken,
  1067. checkToken;
  1068. // Using the following algorithm:
  1069. // https://github.com/mozilla/sweet.js/wiki/design
  1070. prevToken = extra.tokens[extra.tokens.length - 1];
  1071. if (!prevToken) {
  1072. // Nothing before that: it cannot be a division.
  1073. return collectRegex();
  1074. }
  1075. if (prevToken.type === 'Punctuator') {
  1076. if (prevToken.value === ']') {
  1077. return scanPunctuator();
  1078. }
  1079. if (prevToken.value === ')') {
  1080. checkToken = extra.tokens[extra.openParenToken - 1];
  1081. if (checkToken &&
  1082. checkToken.type === 'Keyword' &&
  1083. (checkToken.value === 'if' ||
  1084. checkToken.value === 'while' ||
  1085. checkToken.value === 'for' ||
  1086. checkToken.value === 'with')) {
  1087. return collectRegex();
  1088. }
  1089. return scanPunctuator();
  1090. }
  1091. if (prevToken.value === '}') {
  1092. // Dividing a function by anything makes little sense,
  1093. // but we have to check for that.
  1094. if (extra.tokens[extra.openCurlyToken - 3] &&
  1095. extra.tokens[extra.openCurlyToken - 3].type === 'Keyword') {
  1096. // Anonymous function.
  1097. checkToken = extra.tokens[extra.openCurlyToken - 4];
  1098. if (!checkToken) {
  1099. return scanPunctuator();
  1100. }
  1101. } else if (extra.tokens[extra.openCurlyToken - 4] &&
  1102. extra.tokens[extra.openCurlyToken - 4].type === 'Keyword') {
  1103. // Named function.
  1104. checkToken = extra.tokens[extra.openCurlyToken - 5];
  1105. if (!checkToken) {
  1106. return collectRegex();
  1107. }
  1108. } else {
  1109. return scanPunctuator();
  1110. }
  1111. // checkToken determines whether the function is
  1112. // a declaration or an expression.
  1113. if (FnExprTokens.indexOf(checkToken.value) >= 0) {
  1114. // It is an expression.
  1115. return scanPunctuator();
  1116. }
  1117. // It is a declaration.
  1118. return collectRegex();
  1119. }
  1120. return collectRegex();
  1121. }
  1122. if (prevToken.type === 'Keyword') {
  1123. return collectRegex();
  1124. }
  1125. return scanPunctuator();
  1126. }
  1127. function advance() {
  1128. var ch;
  1129. skipComment();
  1130. if (index >= length) {
  1131. return {
  1132. type: Token.EOF,
  1133. lineNumber: lineNumber,
  1134. lineStart: lineStart,
  1135. start: index,
  1136. end: index
  1137. };
  1138. }
  1139. ch = source.charCodeAt(index);
  1140. if (isIdentifierStart(ch)) {
  1141. return scanIdentifier();
  1142. }
  1143. // Very common: ( and ) and ;
  1144. if (ch === 0x28 || ch === 0x29 || ch === 0x3B) {
  1145. return scanPunctuator();
  1146. }
  1147. // String literal starts with single quote (U+0027) or double quote (U+0022).
  1148. if (ch === 0x27 || ch === 0x22) {
  1149. return scanStringLiteral();
  1150. }
  1151. // Dot (.) U+002E can also start a floating-point number, hence the need
  1152. // to check the next character.
  1153. if (ch === 0x2E) {
  1154. if (isDecimalDigit(source.charCodeAt(index + 1))) {
  1155. return scanNumericLiteral();
  1156. }
  1157. return scanPunctuator();
  1158. }
  1159. if (isDecimalDigit(ch)) {
  1160. return scanNumericLiteral();
  1161. }
  1162. // Slash (/) U+002F can also start a regex.
  1163. if (extra.tokenize && ch === 0x2F) {
  1164. return advanceSlash();
  1165. }
  1166. return scanPunctuator();
  1167. }
  1168. function collectToken() {
  1169. var loc, token, range, value;
  1170. skipComment();
  1171. loc = {
  1172. start: {
  1173. line: lineNumber,
  1174. column: index - lineStart
  1175. }
  1176. };
  1177. token = advance();
  1178. loc.end = {
  1179. line: lineNumber,
  1180. column: index - lineStart
  1181. };
  1182. if (token.type !== Token.EOF) {
  1183. value = source.slice(token.start, token.end);
  1184. extra.tokens.push({
  1185. type: TokenName[token.type],
  1186. value: value,
  1187. range: [token.start, token.end],
  1188. loc: loc
  1189. });
  1190. }
  1191. return token;
  1192. }
  1193. function lex() {
  1194. var token;
  1195. token = lookahead;
  1196. index = token.end;
  1197. lineNumber = token.lineNumber;
  1198. lineStart = token.lineStart;
  1199. lookahead = (typeof extra.tokens !== 'undefined') ? collectToken() : advance();
  1200. index = token.end;
  1201. lineNumber = token.lineNumber;
  1202. lineStart = token.lineStart;
  1203. return token;
  1204. }
  1205. function peek() {
  1206. var pos, line, start;
  1207. pos = index;
  1208. line = lineNumber;
  1209. start = lineStart;
  1210. lookahead = (typeof extra.tokens !== 'undefined') ? collectToken() : advance();
  1211. index = pos;
  1212. lineNumber = line;
  1213. lineStart = start;
  1214. }
  1215. function Position(line, column) {
  1216. this.line = line;
  1217. this.column = column;
  1218. }
  1219. function SourceLocation(startLine, startColumn, line, column) {
  1220. this.start = new Position(startLine, startColumn);
  1221. this.end = new Position(line, column);
  1222. }
  1223. SyntaxTreeDelegate = {
  1224. name: 'SyntaxTree',
  1225. processComment: function (node) {
  1226. var lastChild, trailingComments;
  1227. if (node.type === Syntax.Program) {
  1228. if (node.body.length > 0) {
  1229. return;
  1230. }
  1231. }
  1232. if (extra.trailingComments.length > 0) {
  1233. if (extra.trailingComments[0].range[0] >= node.range[1]) {
  1234. trailingComments = extra.trailingComments;
  1235. extra.trailingComments = [];
  1236. } else {
  1237. extra.trailingComments.length = 0;
  1238. }
  1239. } else {
  1240. if (extra.bottomRightStack.length > 0 &&
  1241. extra.bottomRightStack[extra.bottomRightStack.length - 1].trailingComments &&
  1242. extra.bottomRightStack[extra.bottomRightStack.length - 1].trailingComments[0].range[0] >= node.range[1]) {
  1243. trailingComments = extra.bottomRightStack[extra.bottomRightStack.length - 1].trailingComments;
  1244. delete extra.bottomRightStack[extra.bottomRightStack.length - 1].trailingComments;
  1245. }
  1246. }
  1247. // Eating the stack.
  1248. while (extra.bottomRightStack.length > 0 && extra.bottomRightStack[extra.bottomRightStack.length - 1].range[0] >= node.range[0]) {
  1249. lastChild = extra.bottomRightStack.pop();
  1250. }
  1251. if (lastChild) {
  1252. if (lastChild.leadingComments && lastChild.leadingComments[lastChild.leadingComments.length - 1].range[1] <= node.range[0]) {
  1253. node.leadingComments = lastChild.leadingComments;
  1254. delete lastChild.leadingComments;
  1255. }
  1256. } else if (extra.leadingComments.length > 0 && extra.leadingComments[extra.leadingComments.length - 1].range[1] <= node.range[0]) {
  1257. node.leadingComments = extra.leadingComments;
  1258. extra.leadingComments = [];
  1259. }
  1260. if (trailingComments) {
  1261. node.trailingComments = trailingComments;
  1262. }
  1263. extra.bottomRightStack.push(node);
  1264. },
  1265. markEnd: function (node, startToken) {
  1266. if (extra.range) {
  1267. node.range = [startToken.start, index];
  1268. }
  1269. if (extra.loc) {
  1270. node.loc = new SourceLocation(
  1271. startToken.startLineNumber === undefined ? startToken.lineNumber : startToken.startLineNumber,
  1272. startToken.start - (startToken.startLineStart === undefined ? startToken.lineStart : startToken.startLineStart),
  1273. lineNumber,
  1274. index - lineStart
  1275. );
  1276. this.postProcess(node);
  1277. }
  1278. if (extra.attachComment) {
  1279. this.processComment(node);
  1280. }
  1281. return node;
  1282. },
  1283. postProcess: function (node) {
  1284. if (extra.source) {
  1285. node.loc.source = extra.source;
  1286. }
  1287. return node;
  1288. },
  1289. createArrayExpression: function (elements) {
  1290. return {
  1291. type: Syntax.ArrayExpression,
  1292. elements: elements
  1293. };
  1294. },
  1295. createAssignmentExpression: function (operator, left, right) {
  1296. return {
  1297. type: Syntax.AssignmentExpression,
  1298. operator: operator,
  1299. left: left,
  1300. right: right
  1301. };
  1302. },
  1303. createBinaryExpression: function (operator, left, right) {
  1304. var type = (operator === '||' || operator === '&&') ? Syntax.LogicalExpression :
  1305. Syntax.BinaryExpression;
  1306. return {
  1307. type: type,
  1308. operator: operator,
  1309. left: left,
  1310. right: right
  1311. };
  1312. },
  1313. createBlockStatement: function (body) {
  1314. return {
  1315. type: Syntax.BlockStatement,
  1316. body: body
  1317. };
  1318. },
  1319. createBreakStatement: function (label) {
  1320. return {
  1321. type: Syntax.BreakStatement,
  1322. label: label
  1323. };
  1324. },
  1325. createCallExpression: function (callee, args) {
  1326. return {
  1327. type: Syntax.CallExpression,
  1328. callee: callee,
  1329. 'arguments': args
  1330. };
  1331. },
  1332. createCatchClause: function (param, body) {
  1333. return {
  1334. type: Syntax.CatchClause,
  1335. param: param,
  1336. body: body
  1337. };
  1338. },
  1339. createConditionalExpression: function (test, consequent, alternate) {
  1340. return {
  1341. type: Syntax.ConditionalExpression,
  1342. test: test,
  1343. consequent: consequent,
  1344. alternate: alternate
  1345. };
  1346. },
  1347. createContinueStatement: function (label) {
  1348. return {
  1349. type: Syntax.ContinueStatement,
  1350. label: label
  1351. };
  1352. },
  1353. createDebuggerStatement: function () {
  1354. return {
  1355. type: Syntax.DebuggerStatement
  1356. };
  1357. },
  1358. createDoWhileStatement: function (body, test) {
  1359. return {
  1360. type: Syntax.DoWhileStatement,
  1361. body: body,
  1362. test: test
  1363. };
  1364. },
  1365. createEmptyStatement: function () {
  1366. return {
  1367. type: Syntax.EmptyStatement
  1368. };
  1369. },
  1370. createExpressionStatement: function (expression) {
  1371. return {
  1372. type: Syntax.ExpressionStatement,
  1373. expression: expression
  1374. };
  1375. },
  1376. createForStatement: function (init, test, update, body) {
  1377. return {
  1378. type: Syntax.ForStatement,
  1379. init: init,
  1380. test: test,
  1381. update: update,
  1382. body: body
  1383. };
  1384. },
  1385. createForInStatement: function (left, right, body) {
  1386. return {
  1387. type: Syntax.ForInStatement,
  1388. left: left,
  1389. right: right,
  1390. body: body,
  1391. each: false
  1392. };
  1393. },
  1394. createFunctionDeclaration: function (id, params, defaults, body) {
  1395. return {
  1396. type: Syntax.FunctionDeclaration,
  1397. id: id,
  1398. params: params,
  1399. defaults: defaults,
  1400. body: body,
  1401. rest: null,
  1402. generator: false,
  1403. expression: false
  1404. };
  1405. },
  1406. createFunctionExpression: function (id, params, defaults, body) {
  1407. return {
  1408. type: Syntax.FunctionExpression,
  1409. id: id,
  1410. params: params,
  1411. defaults: defaults,
  1412. body: body,
  1413. rest: null,
  1414. generator: false,
  1415. expression: false
  1416. };
  1417. },
  1418. createIdentifier: function (name) {
  1419. return {
  1420. type: Syntax.Identifier,
  1421. name: name
  1422. };
  1423. },
  1424. createIfStatement: function (test, consequent, alternate) {
  1425. return {
  1426. type: Syntax.IfStatement,
  1427. test: test,
  1428. consequent: consequent,
  1429. alternate: alternate
  1430. };
  1431. },
  1432. createLabeledStatement: function (label, body) {
  1433. return {
  1434. type: Syntax.LabeledStatement,
  1435. label: label,
  1436. body: body
  1437. };
  1438. },
  1439. createLiteral: function (token) {
  1440. return {
  1441. type: Syntax.Literal,
  1442. value: token.value,
  1443. raw: source.slice(token.start, token.end)
  1444. };
  1445. },
  1446. createMemberExpression: function (accessor, object, property) {
  1447. return {
  1448. type: Syntax.MemberExpression,
  1449. computed: accessor === '[',
  1450. object: object,
  1451. property: property
  1452. };
  1453. },
  1454. createNewExpression: function (callee, args) {
  1455. return {
  1456. type: Syntax.NewExpression,
  1457. callee: callee,
  1458. 'arguments': args
  1459. };
  1460. },
  1461. createObjectExpression: function (properties) {
  1462. return {
  1463. type: Syntax.ObjectExpression,
  1464. properties: properties
  1465. };
  1466. },
  1467. createPostfixExpression: function (operator, argument) {
  1468. return {
  1469. type: Syntax.UpdateExpression,
  1470. operator: operator,
  1471. argument: argument,
  1472. prefix: false
  1473. };
  1474. },
  1475. createProgram: function (body) {
  1476. return {
  1477. type: Syntax.Program,
  1478. body: body
  1479. };
  1480. },
  1481. createProperty: function (kind, key, value) {
  1482. return {
  1483. type: Syntax.Property,
  1484. key: key,
  1485. value: value,
  1486. kind: kind
  1487. };
  1488. },
  1489. createReturnStatement: function (argument) {
  1490. return {
  1491. type: Syntax.ReturnStatement,
  1492. argument: argument
  1493. };
  1494. },
  1495. createSequenceExpression: function (expressions) {
  1496. return {
  1497. type: Syntax.SequenceExpression,
  1498. expressions: expressions
  1499. };
  1500. },
  1501. createSwitchCase: function (test, consequent) {
  1502. return {
  1503. type: Syntax.SwitchCase,
  1504. test: test,
  1505. consequent: consequent
  1506. };
  1507. },
  1508. createSwitchStatement: function (discriminant, cases) {
  1509. return {
  1510. type: Syntax.SwitchStatement,
  1511. discriminant: discriminant,
  1512. cases: cases
  1513. };
  1514. },
  1515. createThisExpression: function () {
  1516. return {
  1517. type: Syntax.ThisExpression
  1518. };
  1519. },
  1520. createThrowStatement: function (argument) {
  1521. return {
  1522. type: Syntax.ThrowStatement,
  1523. argument: argument
  1524. };
  1525. },
  1526. createTryStatement: function (block, guardedHandlers, handlers, finalizer) {
  1527. return {
  1528. type: Syntax.TryStatement,
  1529. block: block,
  1530. guardedHandlers: guardedHandlers,
  1531. handlers: handlers,
  1532. finalizer: finalizer
  1533. };
  1534. },
  1535. createUnaryExpression: function (operator, argument) {
  1536. if (operator === '++' || operator === '--') {
  1537. return {
  1538. type: Syntax.UpdateExpression,
  1539. operator: operator,
  1540. argument: argument,
  1541. prefix: true
  1542. };
  1543. }
  1544. return {
  1545. type: Syntax.UnaryExpression,
  1546. operator: operator,
  1547. argument: argument,
  1548. prefix: true
  1549. };
  1550. },
  1551. createVariableDeclaration: function (declarations, kind) {
  1552. return {
  1553. type: Syntax.VariableDeclaration,
  1554. declarations: declarations,
  1555. kind: kind
  1556. };
  1557. },
  1558. createVariableDeclarator: function (id, init) {
  1559. return {
  1560. type: Syntax.VariableDeclarator,
  1561. id: id,
  1562. init: init
  1563. };
  1564. },
  1565. createWhileStatement: function (test, body) {
  1566. return {
  1567. type: Syntax.WhileStatement,
  1568. test: test,
  1569. body: body
  1570. };
  1571. },
  1572. createWithStatement: function (object, body) {
  1573. return {
  1574. type: Syntax.WithStatement,
  1575. object: object,
  1576. body: body
  1577. };
  1578. }
  1579. };
  1580. // Return true if there is a line terminator before the next token.
  1581. function peekLineTerminator() {
  1582. var pos, line, start, found;
  1583. pos = index;
  1584. line = lineNumber;
  1585. start = lineStart;
  1586. skipComment();
  1587. found = lineNumber !== line;
  1588. index = pos;
  1589. lineNumber = line;
  1590. lineStart = start;
  1591. return found;
  1592. }
  1593. // Throw an exception
  1594. function throwError(token, messageFormat) {
  1595. var error,
  1596. args = Array.prototype.slice.call(arguments, 2),
  1597. msg = messageFormat.replace(
  1598. /%(\d)/g,
  1599. function (whole, index) {
  1600. assert(index < args.length, 'Message reference must be in range');
  1601. return args[index];
  1602. }
  1603. );
  1604. if (typeof token.lineNumber === 'number') {
  1605. error = new Error('Line ' + token.lineNumber + ': ' + msg);
  1606. error.index = token.start;
  1607. error.lineNumber = token.lineNumber;
  1608. error.column = token.start - lineStart + 1;
  1609. } else {
  1610. error = new Error('Line ' + lineNumber + ': ' + msg);
  1611. error.index = index;
  1612. error.lineNumber = lineNumber;
  1613. error.column = index - lineStart + 1;
  1614. }
  1615. error.description = msg;
  1616. throw error;
  1617. }
  1618. function throwErrorTolerant() {
  1619. try {
  1620. throwError.apply(null, arguments);
  1621. } catch (e) {
  1622. if (extra.errors) {
  1623. extra.errors.push(e);
  1624. } else {
  1625. throw e;
  1626. }
  1627. }
  1628. }
  1629. // Throw an exception because of the token.
  1630. function throwUnexpected(token) {
  1631. if (token.type === Token.EOF) {
  1632. throwError(token, Messages.UnexpectedEOS);
  1633. }
  1634. if (token.type === Token.NumericLiteral) {
  1635. throwError(token, Messages.UnexpectedNumber);
  1636. }
  1637. if (token.type === Token.StringLiteral) {
  1638. throwError(token, Messages.UnexpectedString);
  1639. }
  1640. if (token.type === Token.Identifier) {
  1641. throwError(token, Messages.UnexpectedIdentifier);
  1642. }
  1643. if (token.type === Token.Keyword) {
  1644. if (isFutureReservedWord(token.value)) {
  1645. throwError(token, Messages.UnexpectedReserved);
  1646. } else if (strict && isStrictModeReservedWord(token.value)) {
  1647. throwErrorTolerant(token, Messages.StrictReservedWord);
  1648. return;
  1649. }
  1650. throwError(token, Messages.UnexpectedToken, token.value);
  1651. }
  1652. // BooleanLiteral, NullLiteral, or Punctuator.
  1653. throwError(token, Messages.UnexpectedToken, token.value);
  1654. }
  1655. // Expect the next token to match the specified punctuator.
  1656. // If not, an exception will be thrown.
  1657. function expect(value) {
  1658. var token = lex();
  1659. if (token.type !== Token.Punctuator || token.value !== value) {
  1660. throwUnexpected(token);
  1661. }
  1662. }
  1663. // Expect the next token to match the specified keyword.
  1664. // If not, an exception will be thrown.
  1665. function expectKeyword(keyword) {
  1666. var token = lex();
  1667. if (token.type !== Token.Keyword || token.value !== keyword) {
  1668. throwUnexpected(token);
  1669. }
  1670. }
  1671. // Return true if the next token matches the specified punctuator.
  1672. function match(value) {
  1673. return lookahead.type === Token.Punctuator && lookahead.value === value;
  1674. }
  1675. // Return true if the next token matches the specified keyword
  1676. function matchKeyword(keyword) {
  1677. return lookahead.type === Token.Keyword && lookahead.value === keyword;
  1678. }
  1679. // Return true if the next token is an assignment operator
  1680. function matchAssign() {
  1681. var op;
  1682. if (lookahead.type !== Token.Punctuator) {
  1683. return false;
  1684. }
  1685. op = lookahead.value;
  1686. return op === '=' ||
  1687. op === '*=' ||
  1688. op === '/=' ||
  1689. op === '%=' ||
  1690. op === '+=' ||
  1691. op === '-=' ||
  1692. op === '<<=' ||
  1693. op === '>>=' ||
  1694. op === '>>>=' ||
  1695. op === '&=' ||
  1696. op === '^=' ||
  1697. op === '|=';
  1698. }
  1699. function consumeSemicolon() {
  1700. var line;
  1701. // Catch the very common case first: immediately a semicolon (U+003B).
  1702. if (source.charCodeAt(index) === 0x3B || match(';')) {
  1703. lex();
  1704. return;
  1705. }
  1706. line = lineNumber;
  1707. skipComment();
  1708. if (lineNumber !== line) {
  1709. return;
  1710. }
  1711. if (lookahead.type !== Token.EOF && !match('}')) {
  1712. throwUnexpected(lookahead);
  1713. }
  1714. }
  1715. // Return true if provided expression is LeftHandSideExpression
  1716. function isLeftHandSide(expr) {
  1717. return expr.type === Syntax.Identifier || expr.type === Syntax.MemberExpression;
  1718. }
  1719. // 11.1.4 Array Initialiser
  1720. function parseArrayInitialiser() {
  1721. var elements = [], startToken;
  1722. startToken = lookahead;
  1723. expect('[');
  1724. while (!match(']')) {
  1725. if (match(',')) {
  1726. lex();
  1727. elements.push(null);
  1728. } else {
  1729. elements.push(parseAssignmentExpression());
  1730. if (!match(']')) {
  1731. expect(',');
  1732. }
  1733. }
  1734. }
  1735. lex();
  1736. return delegate.markEnd(delegate.createArrayExpression(elements), startToken);
  1737. }
  1738. // 11.1.5 Object Initialiser
  1739. function parsePropertyFunction(param, first) {
  1740. var previousStrict, body, startToken;
  1741. previousStrict = strict;
  1742. startToken = lookahead;
  1743. body = parseFunctionSourceElements();
  1744. if (first && strict && isRestrictedWord(param[0].name)) {
  1745. throwErrorTolerant(first, Messages.StrictParamName);
  1746. }
  1747. strict = previousStrict;
  1748. return delegate.markEnd(delegate.createFunctionExpression(null, param, [], body), startToken);
  1749. }
  1750. function parseObjectPropertyKey() {
  1751. var token, startToken;
  1752. startToken = lookahead;
  1753. token = lex();
  1754. // Note: This function is called only from parseObjectProperty(), where
  1755. // EOF and Punctuator tokens are already filtered out.
  1756. if (token.type === Token.StringLiteral || token.type === Token.NumericLiteral) {
  1757. if (strict && token.octal) {
  1758. throwErrorTolerant(token, Messages.StrictOctalLiteral);
  1759. }
  1760. return delegate.markEnd(delegate.createLiteral(token), startToken);
  1761. }
  1762. return delegate.markEnd(delegate.createIdentifier(token.value), startToken);
  1763. }
  1764. function parseObjectProperty() {
  1765. var token, key, id, value, param, startToken;
  1766. token = lookahead;
  1767. startToken = lookahead;
  1768. if (token.type === Token.Identifier) {
  1769. id = parseObjectPropertyKey();
  1770. // Property Assignment: Getter and Setter.
  1771. if (token.value === 'get' && !match(':')) {
  1772. key = parseObjectPropertyKey();
  1773. expect('(');
  1774. expect(')');
  1775. value = parsePropertyFunction([]);
  1776. return delegate.markEnd(delegate.createProperty('get', key, value), startToken);
  1777. }
  1778. if (token.value === 'set' && !match(':')) {
  1779. key = parseObjectPropertyKey();
  1780. expect('(');
  1781. token = lookahead;
  1782. if (token.type !== Token.Identifier) {
  1783. expect(')');
  1784. throwErrorTolerant(token, Messages.UnexpectedToken, token.value);
  1785. value = parsePropertyFunction([]);
  1786. } else {
  1787. param = [ parseVariableIdentifier() ];
  1788. expect(')');
  1789. value = parsePropertyFunction(param, token);
  1790. }
  1791. return delegate.markEnd(delegate.createProperty('set', key, value), startToken);
  1792. }
  1793. expect(':');
  1794. value = parseAssignmentExpression();
  1795. return delegate.markEnd(delegate.createProperty('init', id, value), startToken);
  1796. }
  1797. if (token.type === Token.EOF || token.type === Token.Punctuator) {
  1798. throwUnexpected(token);
  1799. } else {
  1800. key = parseObjectPropertyKey();
  1801. expect(':');
  1802. value = parseAssignmentExpression();
  1803. return delegate.markEnd(delegate.createProperty('init', key, value), startToken);
  1804. }
  1805. }
  1806. function parseObjectInitialiser() {
  1807. var properties = [], property, name, key, kind, map = {}, toString = String, startToken;
  1808. startToken = lookahead;
  1809. expect('{');
  1810. while (!match('}')) {
  1811. property = parseObjectProperty();
  1812. if (property.key.type === Syntax.Identifier) {
  1813. name = property.key.name;
  1814. } else {
  1815. name = toString(property.key.value);
  1816. }
  1817. kind = (property.kind === 'init') ? PropertyKind.Data : (property.kind === 'get') ? PropertyKind.Get : PropertyKind.Set;
  1818. key = '$' + name;
  1819. if (Object.prototype.hasOwnProperty.call(map, key)) {
  1820. if (map[key] === PropertyKind.Data) {
  1821. if (strict && kind === PropertyKind.Data) {
  1822. throwErrorTolerant({}, Messages.StrictDuplicateProperty);
  1823. } else if (kind !== PropertyKind.Data) {
  1824. throwErrorTolerant({}, Messages.AccessorDataProperty);
  1825. }
  1826. } else {
  1827. if (kind === PropertyKind.Data) {
  1828. throwErrorTolerant({}, Messages.AccessorDataProperty);
  1829. } else if (map[key] & kind) {
  1830. throwErrorTolerant({}, Messages.AccessorGetSet);
  1831. }
  1832. }
  1833. map[key] |= kind;
  1834. } else {
  1835. map[key] = kind;
  1836. }
  1837. properties.push(property);
  1838. if (!match('}')) {
  1839. expect(',');
  1840. }
  1841. }
  1842. expect('}');
  1843. return delegate.markEnd(delegate.createObjectExpression(properties), startToken);
  1844. }
  1845. // 11.1.6 The Grouping Operator
  1846. function parseGroupExpression() {
  1847. var expr;
  1848. expect('(');
  1849. expr = parseExpression();
  1850. expect(')');
  1851. return expr;
  1852. }
  1853. // 11.1 Primary Expressions
  1854. function parsePrimaryExpression() {
  1855. var type, token, expr, startToken;
  1856. if (match('(')) {
  1857. return parseGroupExpression();
  1858. }
  1859. if (match('[')) {
  1860. return parseArrayInitialiser();
  1861. }
  1862. if (match('{')) {
  1863. return parseObjectInitialiser();
  1864. }
  1865. type = lookahead.type;
  1866. startToken = lookahead;
  1867. if (type === Token.Identifier) {
  1868. expr = delegate.createIdentifier(lex().value);
  1869. } else if (type === Token.StringLiteral || type === Token.NumericLiteral) {
  1870. if (strict && lookahead.octal) {
  1871. throwErrorTolerant(lookahead, Messages.StrictOctalLiteral);
  1872. }
  1873. expr = delegate.createLiteral(lex());
  1874. } else if (type === Token.Keyword) {
  1875. if (matchKeyword('function')) {
  1876. return parseFunctionExpression();
  1877. }
  1878. if (matchKeyword('this')) {
  1879. lex();
  1880. expr = delegate.createThisExpression();
  1881. } else {
  1882. throwUnexpected(lex());
  1883. }
  1884. } else if (type === Token.BooleanLiteral) {
  1885. token = lex();
  1886. token.value = (token.value === 'true');
  1887. expr = delegate.createLiteral(token);
  1888. } else if (type === Token.NullLiteral) {
  1889. token = lex();
  1890. token.value = null;
  1891. expr = delegate.createLiteral(token);
  1892. } else if (match('/') || match('/=')) {
  1893. if (typeof extra.tokens !== 'undefined') {
  1894. expr = delegate.createLiteral(collectRegex());
  1895. } else {
  1896. expr = delegate.createLiteral(scanRegExp());
  1897. }
  1898. peek();
  1899. } else {
  1900. throwUnexpected(lex());
  1901. }
  1902. return delegate.markEnd(expr, startToken);
  1903. }
  1904. // 11.2 Left-Hand-Side Expressions
  1905. function parseArguments() {
  1906. var args = [];
  1907. expect('(');
  1908. if (!match(')')) {
  1909. while (index < length) {
  1910. args.push(parseAssignmentExpression());
  1911. if (match(')')) {
  1912. break;
  1913. }
  1914. expect(',');
  1915. }
  1916. }
  1917. expect(')');
  1918. return args;
  1919. }
  1920. function parseNonComputedProperty() {
  1921. var token, startToken;
  1922. startToken = lookahead;
  1923. token = lex();
  1924. if (!isIdentifierName(token)) {
  1925. throwUnexpected(token);
  1926. }
  1927. return delegate.markEnd(delegate.createIdentifier(token.value), startToken);
  1928. }
  1929. function parseNonComputedMember() {
  1930. expect('.');
  1931. return parseNonComputedProperty();
  1932. }
  1933. function parseComputedMember() {
  1934. var expr;
  1935. expect('[');
  1936. expr = parseExpression();
  1937. expect(']');
  1938. return expr;
  1939. }
  1940. function parseNewExpression() {
  1941. var callee, args, startToken;
  1942. startToken = lookahead;
  1943. expectKeyword('new');
  1944. callee = parseLeftHandSideExpression();
  1945. args = match('(') ? parseArguments() : [];
  1946. return delegate.markEnd(delegate.createNewExpression(callee, args), startToken);
  1947. }
  1948. function parseLeftHandSideExpressionAllowCall() {
  1949. var previousAllowIn, expr, args, property, startToken;
  1950. startToken = lookahead;
  1951. previousAllowIn = state.allowIn;
  1952. state.allowIn = true;
  1953. expr = matchKeyword('new') ? parseNewExpression() : parsePrimaryExpression();
  1954. state.allowIn = previousAllowIn;
  1955. for (;;) {
  1956. if (match('.')) {
  1957. property = parseNonComputedMember();
  1958. expr = delegate.createMemberExpression('.', expr, property);
  1959. } else if (match('(')) {
  1960. args = parseArguments();
  1961. expr = delegate.createCallExpression(expr, args);
  1962. } else if (match('[')) {
  1963. property = parseComputedMember();
  1964. expr = delegate.createMemberExpression('[', expr, property);
  1965. } else {
  1966. break;
  1967. }
  1968. delegate.markEnd(expr, startToken);
  1969. }
  1970. return expr;
  1971. }
  1972. function parseLeftHandSideExpression() {
  1973. var previousAllowIn, expr, property, startToken;
  1974. startToken = lookahead;
  1975. previousAllowIn = state.allowIn;
  1976. expr = matchKeyword('new') ? parseNewExpression() : parsePrimaryExpression();
  1977. state.allowIn = previousAllowIn;
  1978. while (match('.') || match('[')) {
  1979. if (match('[')) {
  1980. property = parseComputedMember();
  1981. expr = delegate.createMemberExpression('[', expr, property);
  1982. } else {
  1983. property = parseNonComputedMember();
  1984. expr = delegate.createMemberExpression('.', expr, property);
  1985. }
  1986. delegate.markEnd(expr, startToken);
  1987. }
  1988. return expr;
  1989. }
  1990. // 11.3 Postfix Expressions
  1991. function parsePostfixExpression() {
  1992. var expr, token, startToken = lookahead;
  1993. expr = parseLeftHandSideExpressionAllowCall();
  1994. if (lookahead.type === Token.Punctuator) {
  1995. if ((match('++') || match('--')) && !peekLineTerminator()) {
  1996. // 11.3.1, 11.3.2
  1997. if (strict && expr.type === Syntax.Identifier && isRestrictedWord(expr.name)) {
  1998. throwErrorTolerant({}, Messages.StrictLHSPostfix);
  1999. }
  2000. if (!isLeftHandSide(expr)) {
  2001. throwErrorTolerant({}, Messages.InvalidLHSInAssignment);
  2002. }
  2003. token = lex();
  2004. expr = delegate.markEnd(delegate.createPostfixExpression(token.value, expr), startToken);
  2005. }
  2006. }
  2007. return expr;
  2008. }
  2009. // 11.4 Unary Operators
  2010. function parseUnaryExpression() {
  2011. var token, expr, startToken;
  2012. if (lookahead.type !== Token.Punctuator && lookahead.type !== Token.Keyword) {
  2013. expr = parsePostfixExpression();
  2014. } else if (match('++') || match('--')) {
  2015. startToken = lookahead;
  2016. token = lex();
  2017. expr = parseUnaryExpression();
  2018. // 11.4.4, 11.4.5
  2019. if (strict && expr.type === Syntax.Identifier && isRestrictedWord(expr.name)) {
  2020. throwErrorTolerant({}, Messages.StrictLHSPrefix);
  2021. }
  2022. if (!isLeftHandSide(expr)) {
  2023. throwErrorTolerant({}, Messages.InvalidLHSInAssignment);
  2024. }
  2025. expr = delegate.createUnaryExpression(token.value, expr);
  2026. expr = delegate.markEnd(expr, startToken);
  2027. } else if (match('+') || match('-') || match('~') || match('!')) {
  2028. startToken = lookahead;
  2029. token = lex();
  2030. expr = parseUnaryExpression();
  2031. expr = delegate.createUnaryExpression(token.value, expr);
  2032. expr = delegate.markEnd(expr, startToken);
  2033. } else if (matchKeyword('delete') || matchKeyword('void') || matchKeyword('typeof')) {
  2034. startToken = lookahead;
  2035. token = lex();
  2036. expr = parseUnaryExpression();
  2037. expr = delegate.createUnaryExpression(token.value, expr);
  2038. expr = delegate.markEnd(expr, startToken);
  2039. if (strict && expr.operator === 'delete' && expr.argument.type === Syntax.Identifier) {
  2040. throwErrorTolerant({}, Messages.StrictDelete);
  2041. }
  2042. } else {
  2043. expr = parsePostfixExpression();
  2044. }
  2045. return expr;
  2046. }
  2047. function binaryPrecedence(token, allowIn) {
  2048. var prec = 0;
  2049. if (token.type !== Token.Punctuator && token.type !== Token.Keyword) {
  2050. return 0;
  2051. }
  2052. switch (token.value) {
  2053. case '||':
  2054. prec = 1;
  2055. break;
  2056. case '&&':
  2057. prec = 2;
  2058. break;
  2059. case '|':
  2060. prec = 3;
  2061. break;
  2062. case '^':
  2063. prec = 4;
  2064. break;
  2065. case '&':
  2066. prec = 5;
  2067. break;
  2068. case '==':
  2069. case '!=':
  2070. case '===':
  2071. case '!==':
  2072. prec = 6;
  2073. break;
  2074. case '<':
  2075. case '>':
  2076. case '<=':
  2077. case '>=':
  2078. case 'instanceof':
  2079. prec = 7;
  2080. break;
  2081. case 'in':
  2082. prec = allowIn ? 7 : 0;
  2083. break;
  2084. case '<<':
  2085. case '>>':
  2086. case '>>>':
  2087. prec = 8;
  2088. break;
  2089. case '+':
  2090. case '-':
  2091. prec = 9;
  2092. break;
  2093. case '*':
  2094. case '/':
  2095. case '%':
  2096. prec = 11;
  2097. break;
  2098. default:
  2099. break;
  2100. }
  2101. return prec;
  2102. }
  2103. // 11.5 Multiplicative Operators
  2104. // 11.6 Additive Operators
  2105. // 11.7 Bitwise Shift Operators
  2106. // 11.8 Relational Operators
  2107. // 11.9 Equality Operators
  2108. // 11.10 Binary Bitwise Operators
  2109. // 11.11 Binary Logical Operators
  2110. function parseBinaryExpression() {
  2111. var marker, markers, expr, token, prec, stack, right, operator, left, i;
  2112. marker = lookahead;
  2113. left = parseUnaryExpression();
  2114. token = lookahead;
  2115. prec = binaryPrecedence(token, state.allowIn);
  2116. if (prec === 0) {
  2117. return left;
  2118. }
  2119. token.prec = prec;
  2120. lex();
  2121. markers = [marker, lookahead];
  2122. right = parseUnaryExpression();
  2123. stack = [left, token, right];
  2124. while ((prec = binaryPrecedence(lookahead, state.allowIn)) > 0) {
  2125. // Reduce: make a binary expression from the three topmost entries.
  2126. while ((stack.length > 2) && (prec <= stack[stack.length - 2].prec)) {
  2127. right = stack.pop();
  2128. operator = stack.pop().value;
  2129. left = stack.pop();
  2130. expr = delegate.createBinaryExpression(operator, left, right);
  2131. markers.pop();
  2132. marker = markers[markers.length - 1];
  2133. delegate.markEnd(expr, marker);
  2134. stack.push(expr);
  2135. }
  2136. // Shift.
  2137. token = lex();
  2138. token.prec = prec;
  2139. stack.push(token);
  2140. markers.push(lookahead);
  2141. expr = parseUnaryExpression();
  2142. stack.push(expr);
  2143. }
  2144. // Final reduce to clean-up the stack.
  2145. i = stack.length - 1;
  2146. expr = stack[i];
  2147. markers.pop();
  2148. while (i > 1) {
  2149. expr = delegate.createBinaryExpression(stack[i - 1].value, stack[i - 2], expr);
  2150. i -= 2;
  2151. marker = markers.pop();
  2152. delegate.markEnd(expr, marker);
  2153. }
  2154. return expr;
  2155. }
  2156. // 11.12 Conditional Operator
  2157. function parseConditionalExpression() {
  2158. var expr, previousAllowIn, consequent, alternate, startToken;
  2159. startToken = lookahead;
  2160. expr = parseBinaryExpression();
  2161. if (match('?')) {
  2162. lex();
  2163. previousAllowIn = state.allowIn;
  2164. state.allowIn = true;
  2165. consequent = parseAssignmentExpression();
  2166. state.allowIn = previousAllowIn;
  2167. expect(':');
  2168. alternate = parseAssignmentExpression();
  2169. expr = delegate.createConditionalExpression(expr, consequent, alternate);
  2170. delegate.markEnd(expr, startToken);
  2171. }
  2172. return expr;
  2173. }
  2174. // 11.13 Assignment Operators
  2175. function parseAssignmentExpression() {
  2176. var token, left, right, node, startToken;
  2177. token = lookahead;
  2178. startToken = lookahead;
  2179. node = left = parseConditionalExpression();
  2180. if (matchAssign()) {
  2181. // LeftHandSideExpression
  2182. if (!isLeftHandSide(left)) {
  2183. throwErrorTolerant({}, Messages.InvalidLHSInAssignment);
  2184. }
  2185. // 11.13.1
  2186. if (strict && left.type === Syntax.Identifier && isRestrictedWord(left.name)) {
  2187. throwErrorTolerant(token, Messages.StrictLHSAssignment);
  2188. }
  2189. token = lex();
  2190. right = parseAssignmentExpression();
  2191. node = delegate.markEnd(delegate.createAssignmentExpression(token.value, left, right), startToken);
  2192. }
  2193. return node;
  2194. }
  2195. // 11.14 Comma Operator
  2196. function parseExpression() {
  2197. var expr, startToken = lookahead;
  2198. expr = parseAssignmentExpression();
  2199. if (match(',')) {
  2200. expr = delegate.createSequenceExpression([ expr ]);
  2201. while (index < length) {
  2202. if (!match(',')) {
  2203. break;
  2204. }
  2205. lex();
  2206. expr.expressions.push(parseAssignmentExpression());
  2207. }
  2208. delegate.markEnd(expr, startToken);
  2209. }
  2210. return expr;
  2211. }
  2212. // 12.1 Block
  2213. function parseStatementList() {
  2214. var list = [],
  2215. statement;
  2216. while (index < length) {
  2217. if (match('}')) {
  2218. break;
  2219. }
  2220. statement = parseSourceElement();
  2221. if (typeof statement === 'undefined') {
  2222. break;
  2223. }
  2224. list.push(statement);
  2225. }
  2226. return list;
  2227. }
  2228. function parseBlock() {
  2229. var block, startToken;
  2230. startToken = lookahead;
  2231. expect('{');
  2232. block = parseStatementList();
  2233. expect('}');
  2234. return delegate.markEnd(delegate.createBlockStatement(block), startToken);
  2235. }
  2236. // 12.2 Variable Statement
  2237. function parseVariableIdentifier() {
  2238. var token, startToken;
  2239. startToken = lookahead;
  2240. token = lex();
  2241. if (token.type !== Token.Identifier) {
  2242. throwUnexpected(token);
  2243. }
  2244. return delegate.markEnd(delegate.createIdentifier(token.value), startToken);
  2245. }
  2246. function parseVariableDeclaration(kind) {
  2247. var init = null, id, startToken;
  2248. startToken = lookahead;
  2249. id = parseVariableIdentifier();
  2250. // 12.2.1
  2251. if (strict && isRestrictedWord(id.name)) {
  2252. throwErrorTolerant({}, Messages.StrictVarName);
  2253. }
  2254. if (kind === 'const') {
  2255. expect('=');
  2256. init = parseAssignmentExpression();
  2257. } else if (match('=')) {
  2258. lex();
  2259. init = parseAssignmentExpression();
  2260. }
  2261. return delegate.markEnd(delegate.createVariableDeclarator(id, init), startToken);
  2262. }
  2263. function parseVariableDeclarationList(kind) {
  2264. var list = [];
  2265. do {
  2266. list.push(parseVariableDeclaration(kind));
  2267. if (!match(',')) {
  2268. break;
  2269. }
  2270. lex();
  2271. } while (index < length);
  2272. return list;
  2273. }
  2274. function parseVariableStatement() {
  2275. var declarations;
  2276. expectKeyword('var');
  2277. declarations = parseVariableDeclarationList();
  2278. consumeSemicolon();
  2279. return delegate.createVariableDeclaration(declarations, 'var');
  2280. }
  2281. // kind may be `const` or `let`
  2282. // Both are experimental and not in the specification yet.
  2283. // see http://wiki.ecmascript.org/doku.php?id=harmony:const
  2284. // and http://wiki.ecmascript.org/doku.php?id=harmony:let
  2285. function parseConstLetDeclaration(kind) {
  2286. var declarations, startToken;
  2287. startToken = lookahead;
  2288. expectKeyword(kind);
  2289. declarations = parseVariableDeclarationList(kind);
  2290. consumeSemicolon();
  2291. return delegate.markEnd(delegate.createVariableDeclaration(declarations, kind), startToken);
  2292. }
  2293. // 12.3 Empty Statement
  2294. function parseEmptyStatement() {
  2295. expect(';');
  2296. return delegate.createEmptyStatement();
  2297. }
  2298. // 12.4 Expression Statement
  2299. function parseExpressionStatement() {
  2300. var expr = parseExpression();
  2301. consumeSemicolon();
  2302. return delegate.createExpressionStatement(expr);
  2303. }
  2304. // 12.5 If statement
  2305. function parseIfStatement() {
  2306. var test, consequent, alternate;
  2307. expectKeyword('if');
  2308. expect('(');
  2309. test = parseExpression();
  2310. expect(')');
  2311. consequent = parseStatement();
  2312. if (matchKeyword('else')) {
  2313. lex();
  2314. alternate = parseStatement();
  2315. } else {
  2316. alternate = null;
  2317. }
  2318. return delegate.createIfStatement(test, consequent, alternate);
  2319. }
  2320. // 12.6 Iteration Statements
  2321. function parseDoWhileStatement() {
  2322. var body, test, oldInIteration;
  2323. expectKeyword('do');
  2324. oldInIteration = state.inIteration;
  2325. state.inIteration = true;
  2326. body = parseStatement();
  2327. state.inIteration = oldInIteration;
  2328. expectKeyword('while');
  2329. expect('(');
  2330. test = parseExpression();
  2331. expect(')');
  2332. if (match(';')) {
  2333. lex();
  2334. }
  2335. return delegate.createDoWhileStatement(body, test);
  2336. }
  2337. function parseWhileStatement() {
  2338. var test, body, oldInIteration;
  2339. expectKeyword('while');
  2340. expect('(');
  2341. test = parseExpression();
  2342. expect(')');
  2343. oldInIteration = state.inIteration;
  2344. state.inIteration = true;
  2345. body = parseStatement();
  2346. state.inIteration = oldInIteration;
  2347. return delegate.createWhileStatement(test, body);
  2348. }
  2349. function parseForVariableDeclaration() {
  2350. var token, declarations, startToken;
  2351. startToken = lookahead;
  2352. token = lex();
  2353. declarations = parseVariableDeclarationList();
  2354. return delegate.markEnd(delegate.createVariableDeclaration(declarations, token.value), startToken);
  2355. }
  2356. function parseForStatement() {
  2357. var init, test, update, left, right, body, oldInIteration;
  2358. init = test = update = null;
  2359. expectKeyword('for');
  2360. expect('(');
  2361. if (match(';')) {
  2362. lex();
  2363. } else {
  2364. if (matchKeyword('var') || matchKeyword('let')) {
  2365. state.allowIn = false;
  2366. init = parseForVariableDeclaration();
  2367. state.allowIn = true;
  2368. if (init.declarations.length === 1 && matchKeyword('in')) {
  2369. lex();
  2370. left = init;
  2371. right = parseExpression();
  2372. init = null;
  2373. }
  2374. } else {
  2375. state.allowIn = false;
  2376. init = parseExpression();
  2377. state.allowIn = true;
  2378. if (matchKeyword('in')) {
  2379. // LeftHandSideExpression
  2380. if (!isLeftHandSide(init)) {
  2381. throwErrorTolerant({}, Messages.InvalidLHSInForIn);
  2382. }
  2383. lex();
  2384. left = init;
  2385. right = parseExpression();
  2386. init = null;
  2387. }
  2388. }
  2389. if (typeof left === 'undefined') {
  2390. expect(';');
  2391. }
  2392. }
  2393. if (typeof left === 'undefined') {
  2394. if (!match(';')) {
  2395. test = parseExpression();
  2396. }
  2397. expect(';');
  2398. if (!match(')')) {
  2399. update = parseExpression();
  2400. }
  2401. }
  2402. expect(')');
  2403. oldInIteration = state.inIteration;
  2404. state.inIteration = true;
  2405. body = parseStatement();
  2406. state.inIteration = oldInIteration;
  2407. return (typeof left === 'undefined') ?
  2408. delegate.createForStatement(init, test, update, body) :
  2409. delegate.createForInStatement(left, right, body);
  2410. }
  2411. // 12.7 The continue statement
  2412. function parseContinueStatement() {
  2413. var label = null, key;
  2414. expectKeyword('continue');
  2415. // Optimize the most common form: 'continue;'.
  2416. if (source.charCodeAt(index) === 0x3B) {
  2417. lex();
  2418. if (!state.inIteration) {
  2419. throwError({}, Messages.IllegalContinue);
  2420. }
  2421. return delegate.createContinueStatement(null);
  2422. }
  2423. if (peekLineTerminator()) {
  2424. if (!state.inIteration) {
  2425. throwError({}, Messages.IllegalContinue);
  2426. }
  2427. return delegate.createContinueStatement(null);
  2428. }
  2429. if (lookahead.type === Token.Identifier) {
  2430. label = parseVariableIdentifier();
  2431. key = '$' + label.name;
  2432. if (!Object.prototype.hasOwnProperty.call(state.labelSet, key)) {
  2433. throwError({}, Messages.UnknownLabel, label.name);
  2434. }
  2435. }
  2436. consumeSemicolon();
  2437. if (label === null && !state.inIteration) {
  2438. throwError({}, Messages.IllegalContinue);
  2439. }
  2440. return delegate.createContinueStatement(label);
  2441. }
  2442. // 12.8 The break statement
  2443. function parseBreakStatement() {
  2444. var label = null, key;
  2445. expectKeyword('break');
  2446. // Catch the very common case first: immediately a semicolon (U+003B).
  2447. if (source.charCodeAt(index) === 0x3B) {
  2448. lex();
  2449. if (!(state.inIteration || state.inSwitch)) {
  2450. throwError({}, Messages.IllegalBreak);
  2451. }
  2452. return delegate.createBreakStatement(null);
  2453. }
  2454. if (peekLineTerminator()) {
  2455. if (!(state.inIteration || state.inSwitch)) {
  2456. throwError({}, Messages.IllegalBreak);
  2457. }
  2458. return delegate.createBreakStatement(null);
  2459. }
  2460. if (lookahead.type === Token.Identifier) {
  2461. label = parseVariableIdentifier();
  2462. key = '$' + label.name;
  2463. if (!Object.prototype.hasOwnProperty.call(state.labelSet, key)) {
  2464. throwError({}, Messages.UnknownLabel, label.name);
  2465. }
  2466. }
  2467. consumeSemicolon();
  2468. if (label === null && !(state.inIteration || state.inSwitch)) {
  2469. throwError({}, Messages.IllegalBreak);
  2470. }
  2471. return delegate.createBreakStatement(label);
  2472. }
  2473. // 12.9 The return statement
  2474. function parseReturnStatement() {
  2475. var argument = null;
  2476. expectKeyword('return');
  2477. if (!state.inFunctionBody) {
  2478. throwErrorTolerant({}, Messages.IllegalReturn);
  2479. }
  2480. // 'return' followed by a space and an identifier is very common.
  2481. if (source.charCodeAt(index) === 0x20) {
  2482. if (isIdentifierStart(source.charCodeAt(index + 1))) {
  2483. argument = parseExpression();
  2484. consumeSemicolon();
  2485. return delegate.createReturnStatement(argument);
  2486. }
  2487. }
  2488. if (peekLineTerminator()) {
  2489. return delegate.createReturnStatement(null);
  2490. }
  2491. if (!match(';')) {
  2492. if (!match('}') && lookahead.type !== Token.EOF) {
  2493. argument = parseExpression();
  2494. }
  2495. }
  2496. consumeSemicolon();
  2497. return delegate.createReturnStatement(argument);
  2498. }
  2499. // 12.10 The with statement
  2500. function parseWithStatement() {
  2501. var object, body;
  2502. if (strict) {
  2503. // TODO(ikarienator): Should we update the test cases instead?
  2504. skipComment();
  2505. throwErrorTolerant({}, Messages.StrictModeWith);
  2506. }
  2507. expectKeyword('with');
  2508. expect('(');
  2509. object = parseExpression();
  2510. expect(')');
  2511. body = parseStatement();
  2512. return delegate.createWithStatement(object, body);
  2513. }
  2514. // 12.10 The swith statement
  2515. function parseSwitchCase() {
  2516. var test, consequent = [], statement, startToken;
  2517. startToken = lookahead;
  2518. if (matchKeyword('default')) {
  2519. lex();
  2520. test = null;
  2521. } else {
  2522. expectKeyword('case');
  2523. test = parseExpression();
  2524. }
  2525. expect(':');
  2526. while (index < length) {
  2527. if (match('}') || matchKeyword('default') || matchKeyword('case')) {
  2528. break;
  2529. }
  2530. statement = parseStatement();
  2531. consequent.push(statement);
  2532. }
  2533. return delegate.markEnd(delegate.createSwitchCase(test, consequent), startToken);
  2534. }
  2535. function parseSwitchStatement() {
  2536. var discriminant, cases, clause, oldInSwitch, defaultFound;
  2537. expectKeyword('switch');
  2538. expect('(');
  2539. discriminant = parseExpression();
  2540. expect(')');
  2541. expect('{');
  2542. cases = [];
  2543. if (match('}')) {
  2544. lex();
  2545. return delegate.createSwitchStatement(discriminant, cases);
  2546. }
  2547. oldInSwitch = state.inSwitch;
  2548. state.inSwitch = true;
  2549. defaultFound = false;
  2550. while (index < length) {
  2551. if (match('}')) {
  2552. break;
  2553. }
  2554. clause = parseSwitchCase();
  2555. if (clause.test === null) {
  2556. if (defaultFound) {
  2557. throwError({}, Messages.MultipleDefaultsInSwitch);
  2558. }
  2559. defaultFound = true;
  2560. }
  2561. cases.push(clause);
  2562. }
  2563. state.inSwitch = oldInSwitch;
  2564. expect('}');
  2565. return delegate.createSwitchStatement(discriminant, cases);
  2566. }
  2567. // 12.13 The throw statement
  2568. function parseThrowStatement() {
  2569. var argument;
  2570. expectKeyword('throw');
  2571. if (peekLineTerminator()) {
  2572. throwError({}, Messages.NewlineAfterThrow);
  2573. }
  2574. argument = parseExpression();
  2575. consumeSemicolon();
  2576. return delegate.createThrowStatement(argument);
  2577. }
  2578. // 12.14 The try statement
  2579. function parseCatchClause() {
  2580. var param, body, startToken;
  2581. startToken = lookahead;
  2582. expectKeyword('catch');
  2583. expect('(');
  2584. if (match(')')) {
  2585. throwUnexpected(lookahead);
  2586. }
  2587. param = parseVariableIdentifier();
  2588. // 12.14.1
  2589. if (strict && isRestrictedWord(param.name)) {
  2590. throwErrorTolerant({}, Messages.StrictCatchVariable);
  2591. }
  2592. expect(')');
  2593. body = parseBlock();
  2594. return delegate.markEnd(delegate.createCatchClause(param, body), startToken);
  2595. }
  2596. function parseTryStatement() {
  2597. var block, handlers = [], finalizer = null;
  2598. expectKeyword('try');
  2599. block = parseBlock();
  2600. if (matchKeyword('catch')) {
  2601. handlers.push(parseCatchClause());
  2602. }
  2603. if (matchKeyword('finally')) {
  2604. lex();
  2605. finalizer = parseBlock();
  2606. }
  2607. if (handlers.length === 0 && !finalizer) {
  2608. throwError({}, Messages.NoCatchOrFinally);
  2609. }
  2610. return delegate.createTryStatement(block, [], handlers, finalizer);
  2611. }
  2612. // 12.15 The debugger statement
  2613. function parseDebuggerStatement() {
  2614. expectKeyword('debugger');
  2615. consumeSemicolon();
  2616. return delegate.createDebuggerStatement();
  2617. }
  2618. // 12 Statements
  2619. function parseStatement() {
  2620. var type = lookahead.type,
  2621. expr,
  2622. labeledBody,
  2623. key,
  2624. startToken;
  2625. if (type === Token.EOF) {
  2626. throwUnexpected(lookahead);
  2627. }
  2628. if (type === Token.Punctuator && lookahead.value === '{') {
  2629. return parseBlock();
  2630. }
  2631. startToken = lookahead;
  2632. if (type === Token.Punctuator) {
  2633. switch (lookahead.value) {
  2634. case ';':
  2635. return delegate.markEnd(parseEmptyStatement(), startToken);
  2636. case '(':
  2637. return delegate.markEnd(parseExpressionStatement(), startToken);
  2638. default:
  2639. break;
  2640. }
  2641. }
  2642. if (type === Token.Keyword) {
  2643. switch (lookahead.value) {
  2644. case 'break':
  2645. return delegate.markEnd(parseBreakStatement(), startToken);
  2646. case 'continue':
  2647. return delegate.markEnd(parseContinueStatement(), startToken);
  2648. case 'debugger':
  2649. return delegate.markEnd(parseDebuggerStatement(), startToken);
  2650. case 'do':
  2651. return delegate.markEnd(parseDoWhileStatement(), startToken);
  2652. case 'for':
  2653. return delegate.markEnd(parseForStatement(), startToken);
  2654. case 'function':
  2655. return delegate.markEnd(parseFunctionDeclaration(), startToken);
  2656. case 'if':
  2657. return delegate.markEnd(parseIfStatement(), startToken);
  2658. case 'return':
  2659. return delegate.markEnd(parseReturnStatement(), startToken);
  2660. case 'switch':
  2661. return delegate.markEnd(parseSwitchStatement(), startToken);
  2662. case 'throw':
  2663. return delegate.markEnd(parseThrowStatement(), startToken);
  2664. case 'try':
  2665. return delegate.markEnd(parseTryStatement(), startToken);
  2666. case 'var':
  2667. return delegate.markEnd(parseVariableStatement(), startToken);
  2668. case 'while':
  2669. return delegate.markEnd(parseWhileStatement(), startToken);
  2670. case 'with':
  2671. return delegate.markEnd(parseWithStatement(), startToken);
  2672. default:
  2673. break;
  2674. }
  2675. }
  2676. expr = parseExpression();
  2677. // 12.12 Labelled Statements
  2678. if ((expr.type === Syntax.Identifier) && match(':')) {
  2679. lex();
  2680. key = '$' + expr.name;
  2681. if (Object.prototype.hasOwnProperty.call(state.labelSet, key)) {
  2682. throwError({}, Messages.Redeclaration, 'Label', expr.name);
  2683. }
  2684. state.labelSet[key] = true;
  2685. labeledBody = parseStatement();
  2686. delete state.labelSet[key];
  2687. return delegate.markEnd(delegate.createLabeledStatement(expr, labeledBody), startToken);
  2688. }
  2689. consumeSemicolon();
  2690. return delegate.markEnd(delegate.createExpressionStatement(expr), startToken);
  2691. }
  2692. // 13 Function Definition
  2693. function parseFunctionSourceElements() {
  2694. var sourceElement, sourceElements = [], token, directive, firstRestricted,
  2695. oldLabelSet, oldInIteration, oldInSwitch, oldInFunctionBody, startToken;
  2696. startToken = lookahead;
  2697. expect('{');
  2698. while (index < length) {
  2699. if (lookahead.type !== Token.StringLiteral) {
  2700. break;
  2701. }
  2702. token = lookahead;
  2703. sourceElement = parseSourceElement();
  2704. sourceElements.push(sourceElement);
  2705. if (sourceElement.expression.type !== Syntax.Literal) {
  2706. // this is not directive
  2707. break;
  2708. }
  2709. directive = source.slice(token.start + 1, token.end - 1);
  2710. if (directive === 'use strict') {
  2711. strict = true;
  2712. if (firstRestricted) {
  2713. throwErrorTolerant(firstRestricted, Messages.StrictOctalLiteral);
  2714. }
  2715. } else {
  2716. if (!firstRestricted && token.octal) {
  2717. firstRestricted = token;
  2718. }
  2719. }
  2720. }
  2721. oldLabelSet = state.labelSet;
  2722. oldInIteration = state.inIteration;
  2723. oldInSwitch = state.inSwitch;
  2724. oldInFunctionBody = state.inFunctionBody;
  2725. state.labelSet = {};
  2726. state.inIteration = false;
  2727. state.inSwitch = false;
  2728. state.inFunctionBody = true;
  2729. while (index < length) {
  2730. if (match('}')) {
  2731. break;
  2732. }
  2733. sourceElement = parseSourceElement();
  2734. if (typeof sourceElement === 'undefined') {
  2735. break;
  2736. }
  2737. sourceElements.push(sourceElement);
  2738. }
  2739. expect('}');
  2740. state.labelSet = oldLabelSet;
  2741. state.inIteration = oldInIteration;
  2742. state.inSwitch = oldInSwitch;
  2743. state.inFunctionBody = oldInFunctionBody;
  2744. return delegate.markEnd(delegate.createBlockStatement(sourceElements), startToken);
  2745. }
  2746. function parseParams(firstRestricted) {
  2747. var param, params = [], token, stricted, paramSet, key, message;
  2748. expect('(');
  2749. if (!match(')')) {
  2750. paramSet = {};
  2751. while (index < length) {
  2752. token = lookahead;
  2753. param = parseVariableIdentifier();
  2754. key = '$' + token.value;
  2755. if (strict) {
  2756. if (isRestrictedWord(token.value)) {
  2757. stricted = token;
  2758. message = Messages.StrictParamName;
  2759. }
  2760. if (Object.prototype.hasOwnProperty.call(paramSet, key)) {
  2761. stricted = token;
  2762. message = Messages.StrictParamDupe;
  2763. }
  2764. } else if (!firstRestricted) {
  2765. if (isRestrictedWord(token.value)) {
  2766. firstRestricted = token;
  2767. message = Messages.StrictParamName;
  2768. } else if (isStrictModeReservedWord(token.value)) {
  2769. firstRestricted = token;
  2770. message = Messages.StrictReservedWord;
  2771. } else if (Object.prototype.hasOwnProperty.call(paramSet, key)) {
  2772. firstRestricted = token;
  2773. message = Messages.StrictParamDupe;
  2774. }
  2775. }
  2776. params.push(param);
  2777. paramSet[key] = true;
  2778. if (match(')')) {
  2779. break;
  2780. }
  2781. expect(',');
  2782. }
  2783. }
  2784. expect(')');
  2785. return {
  2786. params: params,
  2787. stricted: stricted,
  2788. firstRestricted: firstRestricted,
  2789. message: message
  2790. };
  2791. }
  2792. function parseFunctionDeclaration() {
  2793. var id, params = [], body, token, stricted, tmp, firstRestricted, message, previousStrict, startToken;
  2794. startToken = lookahead;
  2795. expectKeyword('function');
  2796. token = lookahead;
  2797. id = parseVariableIdentifier();
  2798. if (strict) {
  2799. if (isRestrictedWord(token.value)) {
  2800. throwErrorTolerant(token, Messages.StrictFunctionName);
  2801. }
  2802. } else {
  2803. if (isRestrictedWord(token.value)) {
  2804. firstRestricted = token;
  2805. message = Messages.StrictFunctionName;
  2806. } else if (isStrictModeReservedWord(token.value)) {
  2807. firstRestricted = token;
  2808. message = Messages.StrictReservedWord;
  2809. }
  2810. }
  2811. tmp = parseParams(firstRestricted);
  2812. params = tmp.params;
  2813. stricted = tmp.stricted;
  2814. firstRestricted = tmp.firstRestricted;
  2815. if (tmp.message) {
  2816. message = tmp.message;
  2817. }
  2818. previousStrict = strict;
  2819. body = parseFunctionSourceElements();
  2820. if (strict && firstRestricted) {
  2821. throwError(firstRestricted, message);
  2822. }
  2823. if (strict && stricted) {
  2824. throwErrorTolerant(stricted, message);
  2825. }
  2826. strict = previousStrict;
  2827. return delegate.markEnd(delegate.createFunctionDeclaration(id, params, [], body), startToken);
  2828. }
  2829. function parseFunctionExpression() {
  2830. var token, id = null, stricted, firstRestricted, message, tmp, params = [], body, previousStrict, startToken;
  2831. startToken = lookahead;
  2832. expectKeyword('function');
  2833. if (!match('(')) {
  2834. token = lookahead;
  2835. id = parseVariableIdentifier();
  2836. if (strict) {
  2837. if (isRestrictedWord(token.value)) {
  2838. throwErrorTolerant(token, Messages.StrictFunctionName);
  2839. }
  2840. } else {
  2841. if (isRestrictedWord(token.value)) {
  2842. firstRestricted = token;
  2843. message = Messages.StrictFunctionName;
  2844. } else if (isStrictModeReservedWord(token.value)) {
  2845. firstRestricted = token;
  2846. message = Messages.StrictReservedWord;
  2847. }
  2848. }
  2849. }
  2850. tmp = parseParams(firstRestricted);
  2851. params = tmp.params;
  2852. stricted = tmp.stricted;
  2853. firstRestricted = tmp.firstRestricted;
  2854. if (tmp.message) {
  2855. message = tmp.message;
  2856. }
  2857. previousStrict = strict;
  2858. body = parseFunctionSourceElements();
  2859. if (strict && firstRestricted) {
  2860. throwError(firstRestricted, message);
  2861. }
  2862. if (strict && stricted) {
  2863. throwErrorTolerant(stricted, message);
  2864. }
  2865. strict = previousStrict;
  2866. return delegate.markEnd(delegate.createFunctionExpression(id, params, [], body), startToken);
  2867. }
  2868. // 14 Program
  2869. function parseSourceElement() {
  2870. if (lookahead.type === Token.Keyword) {
  2871. switch (lookahead.value) {
  2872. case 'const':
  2873. case 'let':
  2874. return parseConstLetDeclaration(lookahead.value);
  2875. case 'function':
  2876. return parseFunctionDeclaration();
  2877. default:
  2878. return parseStatement();
  2879. }
  2880. }
  2881. if (lookahead.type !== Token.EOF) {
  2882. return parseStatement();
  2883. }
  2884. }
  2885. function parseSourceElements() {
  2886. var sourceElement, sourceElements = [], token, directive, firstRestricted;
  2887. while (index < length) {
  2888. token = lookahead;
  2889. if (token.type !== Token.StringLiteral) {
  2890. break;
  2891. }
  2892. sourceElement = parseSourceElement();
  2893. sourceElements.push(sourceElement);
  2894. if (sourceElement.expression.type !== Syntax.Literal) {
  2895. // this is not directive
  2896. break;
  2897. }
  2898. directive = source.slice(token.start + 1, token.end - 1);
  2899. if (directive === 'use strict') {
  2900. strict = true;
  2901. if (firstRestricted) {
  2902. throwErrorTolerant(firstRestricted, Messages.StrictOctalLiteral);
  2903. }
  2904. } else {
  2905. if (!firstRestricted && token.octal) {
  2906. firstRestricted = token;
  2907. }
  2908. }
  2909. }
  2910. while (index < length) {
  2911. sourceElement = parseSourceElement();
  2912. /* istanbul ignore if */
  2913. if (typeof sourceElement === 'undefined') {
  2914. break;
  2915. }
  2916. sourceElements.push(sourceElement);
  2917. }
  2918. return sourceElements;
  2919. }
  2920. function parseProgram() {
  2921. var body, startToken;
  2922. skipComment();
  2923. peek();
  2924. startToken = lookahead;
  2925. strict = false;
  2926. body = parseSourceElements();
  2927. return delegate.markEnd(delegate.createProgram(body), startToken);
  2928. }
  2929. function filterTokenLocation() {
  2930. var i, entry, token, tokens = [];
  2931. for (i = 0; i < extra.tokens.length; ++i) {
  2932. entry = extra.tokens[i];
  2933. token = {
  2934. type: entry.type,
  2935. value: entry.value
  2936. };
  2937. if (extra.range) {
  2938. token.range = entry.range;
  2939. }
  2940. if (extra.loc) {
  2941. token.loc = entry.loc;
  2942. }
  2943. tokens.push(token);
  2944. }
  2945. extra.tokens = tokens;
  2946. }
  2947. function tokenize(code, options) {
  2948. var toString,
  2949. token,
  2950. tokens;
  2951. toString = String;
  2952. if (typeof code !== 'string' && !(code instanceof String)) {
  2953. code = toString(code);
  2954. }
  2955. delegate = SyntaxTreeDelegate;
  2956. source = code;
  2957. index = 0;
  2958. lineNumber = (source.length > 0) ? 1 : 0;
  2959. lineStart = 0;
  2960. length = source.length;
  2961. lookahead = null;
  2962. state = {
  2963. allowIn: true,
  2964. labelSet: {},
  2965. inFunctionBody: false,
  2966. inIteration: false,
  2967. inSwitch: false,
  2968. lastCommentStart: -1
  2969. };
  2970. extra = {};
  2971. // Options matching.
  2972. options = options || {};
  2973. // Of course we collect tokens here.
  2974. options.tokens = true;
  2975. extra.tokens = [];
  2976. extra.tokenize = true;
  2977. // The following two fields are necessary to compute the Regex tokens.
  2978. extra.openParenToken = -1;
  2979. extra.openCurlyToken = -1;
  2980. extra.range = (typeof options.range === 'boolean') && options.range;
  2981. extra.loc = (typeof options.loc === 'boolean') && options.loc;
  2982. if (typeof options.comment === 'boolean' && options.comment) {
  2983. extra.comments = [];
  2984. }
  2985. if (typeof options.tolerant === 'boolean' && options.tolerant) {
  2986. extra.errors = [];
  2987. }
  2988. try {
  2989. peek();
  2990. if (lookahead.type === Token.EOF) {
  2991. return extra.tokens;
  2992. }
  2993. token = lex();
  2994. while (lookahead.type !== Token.EOF) {
  2995. try {
  2996. token = lex();
  2997. } catch (lexError) {
  2998. token = lookahead;
  2999. if (extra.errors) {
  3000. extra.errors.push(lexError);
  3001. // We have to break on the first error
  3002. // to avoid infinite loops.
  3003. break;
  3004. } else {
  3005. throw lexError;
  3006. }
  3007. }
  3008. }
  3009. filterTokenLocation();
  3010. tokens = extra.tokens;
  3011. if (typeof extra.comments !== 'undefined') {
  3012. tokens.comments = extra.comments;
  3013. }
  3014. if (typeof extra.errors !== 'undefined') {
  3015. tokens.errors = extra.errors;
  3016. }
  3017. } catch (e) {
  3018. throw e;
  3019. } finally {
  3020. extra = {};
  3021. }
  3022. return tokens;
  3023. }
  3024. function parse(code, options) {
  3025. var program, toString;
  3026. toString = String;
  3027. if (typeof code !== 'string' && !(code instanceof String)) {
  3028. code = toString(code);
  3029. }
  3030. delegate = SyntaxTreeDelegate;
  3031. source = code;
  3032. index = 0;
  3033. lineNumber = (source.length > 0) ? 1 : 0;
  3034. lineStart = 0;
  3035. length = source.length;
  3036. lookahead = null;
  3037. state = {
  3038. allowIn: true,
  3039. labelSet: {},
  3040. inFunctionBody: false,
  3041. inIteration: false,
  3042. inSwitch: false,
  3043. lastCommentStart: -1
  3044. };
  3045. extra = {};
  3046. if (typeof options !== 'undefined') {
  3047. extra.range = (typeof options.range === 'boolean') && options.range;
  3048. extra.loc = (typeof options.loc === 'boolean') && options.loc;
  3049. extra.attachComment = (typeof options.attachComment === 'boolean') && options.attachComment;
  3050. if (extra.loc && options.source !== null && options.source !== undefined) {
  3051. extra.source = toString(options.source);
  3052. }
  3053. if (typeof options.tokens === 'boolean' && options.tokens) {
  3054. extra.tokens = [];
  3055. }
  3056. if (typeof options.comment === 'boolean' && options.comment) {
  3057. extra.comments = [];
  3058. }
  3059. if (typeof options.tolerant === 'boolean' && options.tolerant) {
  3060. extra.errors = [];
  3061. }
  3062. if (extra.attachComment) {
  3063. extra.range = true;
  3064. extra.comments = [];
  3065. extra.bottomRightStack = [];
  3066. extra.trailingComments = [];
  3067. extra.leadingComments = [];
  3068. }
  3069. }
  3070. try {
  3071. program = parseProgram();
  3072. if (typeof extra.comments !== 'undefined') {
  3073. program.comments = extra.comments;
  3074. }
  3075. if (typeof extra.tokens !== 'undefined') {
  3076. filterTokenLocation();
  3077. program.tokens = extra.tokens;
  3078. }
  3079. if (typeof extra.errors !== 'undefined') {
  3080. program.errors = extra.errors;
  3081. }
  3082. } catch (e) {
  3083. throw e;
  3084. } finally {
  3085. extra = {};
  3086. }
  3087. return program;
  3088. }
  3089. // Sync with *.json manifests.
  3090. exports.version = '1.2.2';
  3091. exports.tokenize = tokenize;
  3092. exports.parse = parse;
  3093. // Deep copy.
  3094. /* istanbul ignore next */
  3095. exports.Syntax = (function () {
  3096. var name, types = {};
  3097. if (typeof Object.create === 'function') {
  3098. types = Object.create(null);
  3099. }
  3100. for (name in Syntax) {
  3101. if (Syntax.hasOwnProperty(name)) {
  3102. types[name] = Syntax[name];
  3103. }
  3104. }
  3105. if (typeof Object.freeze === 'function') {
  3106. Object.freeze(types);
  3107. }
  3108. return types;
  3109. }());
  3110. }));
  3111. /* vim: set sw=4 ts=4 et tw=80 : */
  3112. })(null);
  3113. /*!
  3114. * falafel (c) James Halliday / MIT License
  3115. * https://github.com/substack/node-falafel
  3116. */
  3117. (function(require,module){
  3118. var parse = require('esprima').parse;
  3119. var objectKeys = Object.keys || function (obj) {
  3120. var keys = [];
  3121. for (var key in obj) keys.push(key);
  3122. return keys;
  3123. };
  3124. var forEach = function (xs, fn) {
  3125. if (xs.forEach) return xs.forEach(fn);
  3126. for (var i = 0; i < xs.length; i++) {
  3127. fn.call(xs, xs[i], i, xs);
  3128. }
  3129. };
  3130. var isArray = Array.isArray || function (xs) {
  3131. return Object.prototype.toString.call(xs) === '[object Array]';
  3132. };
  3133. module.exports = function (src, opts, fn) {
  3134. if (typeof opts === 'function') {
  3135. fn = opts;
  3136. opts = {};
  3137. }
  3138. if (typeof src === 'object') {
  3139. opts = src;
  3140. src = opts.source;
  3141. delete opts.source;
  3142. }
  3143. src = src === undefined ? opts.source : src;
  3144. opts.range = true;
  3145. if (typeof src !== 'string') src = String(src);
  3146. var ast = parse(src, opts);
  3147. var result = {
  3148. chunks : src.split(''),
  3149. toString : function () { return result.chunks.join('') },
  3150. inspect : function () { return result.toString() }
  3151. };
  3152. var index = 0;
  3153. (function walk (node, parent) {
  3154. insertHelpers(node, parent, result.chunks);
  3155. forEach(objectKeys(node), function (key) {
  3156. if (key === 'parent') return;
  3157. var child = node[key];
  3158. if (isArray(child)) {
  3159. forEach(child, function (c) {
  3160. if (c && typeof c.type === 'string') {
  3161. walk(c, node);
  3162. }
  3163. });
  3164. }
  3165. else if (child && typeof child.type === 'string') {
  3166. insertHelpers(child, node, result.chunks);
  3167. walk(child, node);
  3168. }
  3169. });
  3170. fn(node);
  3171. })(ast, undefined);
  3172. return result;
  3173. };
  3174. function insertHelpers (node, parent, chunks) {
  3175. if (!node.range) return;
  3176. node.parent = parent;
  3177. node.source = function () {
  3178. return chunks.slice(
  3179. node.range[0], node.range[1]
  3180. ).join('');
  3181. };
  3182. if (node.update && typeof node.update === 'object') {
  3183. var prev = node.update;
  3184. forEach(objectKeys(prev), function (key) {
  3185. update[key] = prev[key];
  3186. });
  3187. node.update = update;
  3188. }
  3189. else {
  3190. node.update = update;
  3191. }
  3192. function update (s) {
  3193. chunks[node.range[0]] = s;
  3194. for (var i = node.range[0] + 1; i < node.range[1]; i++) {
  3195. chunks[i] = '';
  3196. }
  3197. };
  3198. }
  3199. window.falafel = module.exports;})(function(){return {parse: esprima.parse};},{exports: {}});
  3200. var inBrowser = typeof window !== 'undefined' && this === window;
  3201. var parseAndModify = (inBrowser ? window.falafel : require("falafel"));
  3202. (inBrowser ? window : exports).blanket = (function(){
  3203. var linesToAddTracking = [
  3204. "ExpressionStatement",
  3205. "BreakStatement" ,
  3206. "ContinueStatement" ,
  3207. "VariableDeclaration",
  3208. "ReturnStatement" ,
  3209. "ThrowStatement" ,
  3210. "TryStatement" ,
  3211. "FunctionDeclaration" ,
  3212. "IfStatement" ,
  3213. "WhileStatement" ,
  3214. "DoWhileStatement" ,
  3215. "ForStatement" ,
  3216. "ForInStatement" ,
  3217. "SwitchStatement" ,
  3218. "WithStatement"
  3219. ],
  3220. linesToAddBrackets = [
  3221. "IfStatement" ,
  3222. "WhileStatement" ,
  3223. "DoWhileStatement" ,
  3224. "ForStatement" ,
  3225. "ForInStatement" ,
  3226. "WithStatement"
  3227. ],
  3228. __blanket,
  3229. copynumber = Math.floor(Math.random()*1000),
  3230. coverageInfo = {},options = {
  3231. reporter: null,
  3232. adapter:null,
  3233. filter: null,
  3234. customVariable: null,
  3235. loader: null,
  3236. ignoreScriptError: false,
  3237. existingRequireJS:false,
  3238. autoStart: false,
  3239. timeout: 180,
  3240. ignoreCors: false,
  3241. branchTracking: false,
  3242. sourceURL: false,
  3243. debug:false,
  3244. engineOnly:false,
  3245. testReadyCallback:null,
  3246. commonJS:false,
  3247. instrumentCache:false,
  3248. modulePattern: null
  3249. };
  3250. if (inBrowser && typeof window.blanket !== 'undefined'){
  3251. __blanket = window.blanket.noConflict();
  3252. }
  3253. _blanket = {
  3254. noConflict: function(){
  3255. if (__blanket){
  3256. return __blanket;
  3257. }
  3258. return _blanket;
  3259. },
  3260. _getCopyNumber: function(){
  3261. //internal method
  3262. //for differentiating between instances
  3263. return copynumber;
  3264. },
  3265. extend: function(obj) {
  3266. //borrowed from underscore
  3267. _blanket._extend(_blanket,obj);
  3268. },
  3269. _extend: function(dest,source){
  3270. if (source) {
  3271. for (var prop in source) {
  3272. if ( dest[prop] instanceof Object && typeof dest[prop] !== "function"){
  3273. _blanket._extend(dest[prop],source[prop]);
  3274. }else{
  3275. dest[prop] = source[prop];
  3276. }
  3277. }
  3278. }
  3279. },
  3280. getCovVar: function(){
  3281. var opt = _blanket.options("customVariable");
  3282. if (opt){
  3283. if (_blanket.options("debug")) {console.log("BLANKET-Using custom tracking variable:",opt);}
  3284. return inBrowser ? "window."+opt : opt;
  3285. }
  3286. return inBrowser ? "window._$blanket" : "_$jscoverage";
  3287. },
  3288. options: function(key,value){
  3289. if (typeof key !== "string"){
  3290. _blanket._extend(options,key);
  3291. }else if (typeof value === 'undefined'){
  3292. return options[key];
  3293. }else{
  3294. options[key]=value;
  3295. }
  3296. },
  3297. instrument: function(config, next){
  3298. //check instrumented hash table,
  3299. //return instrumented code if available.
  3300. var inFile = config.inputFile,
  3301. inFileName = config.inputFileName;
  3302. //check instrument cache
  3303. if (_blanket.options("instrumentCache") && sessionStorage && sessionStorage.getItem("blanket_instrument_store-"+inFileName)){
  3304. if (_blanket.options("debug")) {console.log("BLANKET-Reading instrumentation from cache: ",inFileName);}
  3305. next(sessionStorage.getItem("blanket_instrument_store-"+inFileName));
  3306. }else{
  3307. var sourceArray = _blanket._prepareSource(inFile);
  3308. _blanket._trackingArraySetup=[];
  3309. //remove shebang
  3310. inFile = inFile.replace(/^\#\!.*/, "");
  3311. var instrumented = parseAndModify(inFile,{loc:true,comment:true}, _blanket._addTracking(inFileName));
  3312. instrumented = _blanket._trackingSetup(inFileName,sourceArray)+instrumented;
  3313. if (_blanket.options("sourceURL")){
  3314. instrumented += "\n//@ sourceURL="+inFileName.replace("http://","");
  3315. }
  3316. if (_blanket.options("debug")) {console.log("BLANKET-Instrumented file: ",inFileName);}
  3317. if (_blanket.options("instrumentCache") && sessionStorage){
  3318. if (_blanket.options("debug")) {console.log("BLANKET-Saving instrumentation to cache: ",inFileName);}
  3319. sessionStorage.setItem("blanket_instrument_store-"+inFileName,instrumented);
  3320. }
  3321. next(instrumented);
  3322. }
  3323. },
  3324. _trackingArraySetup: [],
  3325. _branchingArraySetup: [],
  3326. _prepareSource: function(source){
  3327. return source.replace(/\\/g,"\\\\").replace(/'/g,"\\'").replace(/(\r\n|\n|\r)/gm,"\n").split('\n');
  3328. },
  3329. _trackingSetup: function(filename,sourceArray){
  3330. var branches = _blanket.options("branchTracking");
  3331. var sourceString = sourceArray.join("',\n'");
  3332. var intro = "";
  3333. var covVar = _blanket.getCovVar();
  3334. intro += "if (typeof "+covVar+" === 'undefined') "+covVar+" = {};\n";
  3335. if (branches){
  3336. intro += "var _$branchFcn=function(f,l,c,r){ ";
  3337. intro += "if (!!r) { ";
  3338. intro += covVar+"[f].branchData[l][c][0] = "+covVar+"[f].branchData[l][c][0] || [];";
  3339. intro += covVar+"[f].branchData[l][c][0].push(r); }";
  3340. intro += "else { ";
  3341. intro += covVar+"[f].branchData[l][c][1] = "+covVar+"[f].branchData[l][c][1] || [];";
  3342. intro += covVar+"[f].branchData[l][c][1].push(r); }";
  3343. intro += "return r;};\n";
  3344. }
  3345. intro += "if (typeof "+covVar+"['"+filename+"'] === 'undefined'){";
  3346. intro += covVar+"['"+filename+"']=[];\n";
  3347. if (branches){
  3348. intro += covVar+"['"+filename+"'].branchData=[];\n";
  3349. }
  3350. intro += covVar+"['"+filename+"'].source=['"+sourceString+"'];\n";
  3351. //initialize array values
  3352. _blanket._trackingArraySetup.sort(function(a,b){
  3353. return parseInt(a,10) > parseInt(b,10);
  3354. }).forEach(function(item){
  3355. intro += covVar+"['"+filename+"']["+item+"]=0;\n";
  3356. });
  3357. if (branches){
  3358. _blanket._branchingArraySetup.sort(function(a,b){
  3359. return a.line > b.line;
  3360. }).sort(function(a,b){
  3361. return a.column > b.column;
  3362. }).forEach(function(item){
  3363. if (item.file === filename){
  3364. intro += "if (typeof "+ covVar+"['"+filename+"'].branchData["+item.line+"] === 'undefined'){\n";
  3365. intro += covVar+"['"+filename+"'].branchData["+item.line+"]=[];\n";
  3366. intro += "}";
  3367. intro += covVar+"['"+filename+"'].branchData["+item.line+"]["+item.column+"] = [];\n";
  3368. intro += covVar+"['"+filename+"'].branchData["+item.line+"]["+item.column+"].consequent = "+JSON.stringify(item.consequent)+";\n";
  3369. intro += covVar+"['"+filename+"'].branchData["+item.line+"]["+item.column+"].alternate = "+JSON.stringify(item.alternate)+";\n";
  3370. }
  3371. });
  3372. }
  3373. intro += "}";
  3374. return intro;
  3375. },
  3376. _blockifyIf: function(node){
  3377. if (linesToAddBrackets.indexOf(node.type) > -1){
  3378. var bracketsExistObject = node.consequent || node.body;
  3379. var bracketsExistAlt = node.alternate;
  3380. if( bracketsExistAlt && bracketsExistAlt.type !== "BlockStatement") {
  3381. bracketsExistAlt.update("{\n"+bracketsExistAlt.source()+"}\n");
  3382. }
  3383. if( bracketsExistObject && bracketsExistObject.type !== "BlockStatement") {
  3384. bracketsExistObject.update("{\n"+bracketsExistObject.source()+"}\n");
  3385. }
  3386. }
  3387. },
  3388. _trackBranch: function(node,filename){
  3389. //recursive on consequent and alternative
  3390. var line = node.loc.start.line;
  3391. var col = node.loc.start.column;
  3392. _blanket._branchingArraySetup.push({
  3393. line: line,
  3394. column: col,
  3395. file:filename,
  3396. consequent: node.consequent.loc,
  3397. alternate: node.alternate.loc
  3398. });
  3399. var updated = "_$branchFcn"+
  3400. "('"+filename+"',"+line+","+col+","+node.test.source()+
  3401. ")?"+node.consequent.source()+":"+node.alternate.source();
  3402. node.update(updated);
  3403. },
  3404. _addTracking: function (filename) {
  3405. //falafel doesn't take a file name
  3406. //so we include the filename in a closure
  3407. //and return the function to falafel
  3408. var covVar = _blanket.getCovVar();
  3409. return function(node){
  3410. _blanket._blockifyIf(node);
  3411. if (linesToAddTracking.indexOf(node.type) > -1 && node.parent.type !== "LabeledStatement") {
  3412. _blanket._checkDefs(node,filename);
  3413. if (node.type === "VariableDeclaration" &&
  3414. (node.parent.type === "ForStatement" || node.parent.type === "ForInStatement")){
  3415. return;
  3416. }
  3417. if (node.loc && node.loc.start){
  3418. node.update(covVar+"['"+filename+"']["+node.loc.start.line+"]++;\n"+node.source());
  3419. _blanket._trackingArraySetup.push(node.loc.start.line);
  3420. }else{
  3421. //I don't think we can handle a node with no location
  3422. throw new Error("The instrumenter encountered a node with no location: "+Object.keys(node));
  3423. }
  3424. }else if (_blanket.options("branchTracking") && node.type === "ConditionalExpression"){
  3425. _blanket._trackBranch(node,filename);
  3426. }
  3427. };
  3428. },
  3429. _checkDefs: function(node,filename){
  3430. // Make sure developers don't redefine window. if they do, inform them it is wrong.
  3431. if (inBrowser){
  3432. if (node.type === "VariableDeclaration" && node.declarations) {
  3433. node.declarations.forEach(function(declaration) {
  3434. if (declaration.id.name === "window") {
  3435. throw new Error("Instrumentation error, you cannot redefine the 'window' variable in " + filename + ":" + node.loc.start.line);
  3436. }
  3437. });
  3438. }
  3439. if (node.type === "FunctionDeclaration" && node.params) {
  3440. node.params.forEach(function(param) {
  3441. if (param.name === "window") {
  3442. throw new Error("Instrumentation error, you cannot redefine the 'window' variable in " + filename + ":" + node.loc.start.line);
  3443. }
  3444. });
  3445. }
  3446. //Make sure developers don't redefine the coverage variable
  3447. if (node.type === "ExpressionStatement" &&
  3448. node.expression && node.expression.left &&
  3449. node.expression.left.object && node.expression.left.property &&
  3450. node.expression.left.object.name +
  3451. "." + node.expression.left.property.name === _blanket.getCovVar()) {
  3452. throw new Error("Instrumentation error, you cannot redefine the coverage variable in " + filename + ":" + node.loc.start.line);
  3453. }
  3454. }else{
  3455. //Make sure developers don't redefine the coverage variable in node
  3456. if (node.type === "ExpressionStatement" &&
  3457. node.expression && node.expression.left &&
  3458. !node.expression.left.object && !node.expression.left.property &&
  3459. node.expression.left.name === _blanket.getCovVar()) {
  3460. throw new Error("Instrumentation error, you cannot redefine the coverage variable in " + filename + ":" + node.loc.start.line);
  3461. }
  3462. }
  3463. },
  3464. setupCoverage: function(){
  3465. coverageInfo.instrumentation = "blanket";
  3466. coverageInfo.stats = {
  3467. "suites": 0,
  3468. "tests": 0,
  3469. "passes": 0,
  3470. "pending": 0,
  3471. "failures": 0,
  3472. "start": new Date()
  3473. };
  3474. },
  3475. _checkIfSetup: function(){
  3476. if (!coverageInfo.stats){
  3477. throw new Error("You must call blanket.setupCoverage() first.");
  3478. }
  3479. },
  3480. onTestStart: function(){
  3481. if (_blanket.options("debug")) {console.log("BLANKET-Test event started");}
  3482. this._checkIfSetup();
  3483. coverageInfo.stats.tests++;
  3484. coverageInfo.stats.pending++;
  3485. },
  3486. onTestDone: function(total,passed){
  3487. this._checkIfSetup();
  3488. if(passed === total){
  3489. coverageInfo.stats.passes++;
  3490. }else{
  3491. coverageInfo.stats.failures++;
  3492. }
  3493. coverageInfo.stats.pending--;
  3494. },
  3495. onModuleStart: function(){
  3496. this._checkIfSetup();
  3497. coverageInfo.stats.suites++;
  3498. },
  3499. onTestsDone: function(){
  3500. if (_blanket.options("debug")) {console.log("BLANKET-Test event done");}
  3501. this._checkIfSetup();
  3502. coverageInfo.stats.end = new Date();
  3503. if (inBrowser){
  3504. this.report(coverageInfo);
  3505. }else{
  3506. if (!_blanket.options("branchTracking")){
  3507. delete (inBrowser ? window : global)[_blanket.getCovVar()].branchFcn;
  3508. }
  3509. this.options("reporter").call(this,coverageInfo);
  3510. }
  3511. }
  3512. };
  3513. return _blanket;
  3514. })();
  3515. (function(_blanket){
  3516. var oldOptions = _blanket.options;
  3517. _blanket.extend({
  3518. outstandingRequireFiles:[],
  3519. options: function(key,value){
  3520. var newVal={};
  3521. if (typeof key !== "string"){
  3522. //key is key/value map
  3523. oldOptions(key);
  3524. newVal = key;
  3525. }else if (typeof value === 'undefined'){
  3526. //accessor
  3527. return oldOptions(key);
  3528. }else{
  3529. //setter
  3530. oldOptions(key,value);
  3531. newVal[key] = value;
  3532. }
  3533. if (newVal.adapter){
  3534. _blanket._loadFile(newVal.adapter);
  3535. }
  3536. if (newVal.loader){
  3537. _blanket._loadFile(newVal.loader);
  3538. }
  3539. },
  3540. requiringFile: function(filename,done){
  3541. if (typeof filename === "undefined"){
  3542. _blanket.outstandingRequireFiles=[];
  3543. }else if (typeof done === "undefined"){
  3544. _blanket.outstandingRequireFiles.push(filename);
  3545. }else{
  3546. _blanket.outstandingRequireFiles.splice(_blanket.outstandingRequireFiles.indexOf(filename),1);
  3547. }
  3548. },
  3549. requireFilesLoaded: function(){
  3550. return _blanket.outstandingRequireFiles.length === 0;
  3551. },
  3552. showManualLoader: function(){
  3553. if (document.getElementById("blanketLoaderDialog")){
  3554. return;
  3555. }
  3556. //copied from http://blog.avtex.com/2012/01/26/cross-browser-css-only-modal-box/
  3557. var loader = "<div class='blanketDialogOverlay'>";
  3558. loader += "&nbsp;</div>";
  3559. loader += "<div class='blanketDialogVerticalOffset'>";
  3560. loader += "<div class='blanketDialogBox'>";
  3561. loader += "<b>Error:</b> Blanket.js encountered a cross origin request error while instrumenting the source files. ";
  3562. loader += "<br><br>This is likely caused by the source files being referenced locally (using the file:// protocol). ";
  3563. 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).";
  3564. loader += "<br>";
  3565. if (typeof FileReader !== "undefined"){
  3566. loader += "<br>Or, try the experimental loader. When prompted, simply click on the directory containing all the source files you want covered.";
  3567. loader += "<a href='javascript:document.getElementById(\"fileInput\").click();'>Start Loader</a>";
  3568. 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'/>";
  3569. }
  3570. loader += "<br><span style='float:right;cursor:pointer;' onclick=document.getElementById('blanketLoaderDialog').style.display='none';>Close</span>";
  3571. loader += "<div style='clear:both'></div>";
  3572. loader += "</div></div>";
  3573. var css = ".blanketDialogWrapper {";
  3574. css += "display:block;";
  3575. css += "position:fixed;";
  3576. css += "z-index:40001; }";
  3577. css += ".blanketDialogOverlay {";
  3578. css += "position:fixed;";
  3579. css += "width:100%;";
  3580. css += "height:100%;";
  3581. css += "background-color:black;";
  3582. css += "opacity:.5; ";
  3583. css += "-ms-filter:'progid:DXImageTransform.Microsoft.Alpha(Opacity=50)'; ";
  3584. css += "filter:alpha(opacity=50); ";
  3585. css += "z-index:40001; }";
  3586. css += ".blanketDialogVerticalOffset { ";
  3587. css += "position:fixed;";
  3588. css += "top:30%;";
  3589. css += "width:100%;";
  3590. css += "z-index:40002; }";
  3591. css += ".blanketDialogBox { ";
  3592. css += "width:405px; ";
  3593. css += "position:relative;";
  3594. css += "margin:0 auto;";
  3595. css += "background-color:white;";
  3596. css += "padding:10px;";
  3597. css += "border:1px solid black; }";
  3598. var dom = document.createElement("style");
  3599. dom.innerHTML = css;
  3600. document.head.appendChild(dom);
  3601. var div = document.createElement("div");
  3602. div.id = "blanketLoaderDialog";
  3603. div.className = "blanketDialogWrapper";
  3604. div.innerHTML = loader;
  3605. document.body.insertBefore(div,document.body.firstChild);
  3606. },
  3607. manualFileLoader: function(files){
  3608. var toArray =Array.prototype.slice;
  3609. files = toArray.call(files).filter(function(item){
  3610. return item.type !== "";
  3611. });
  3612. var sessionLength = files.length-1;
  3613. var sessionIndx=0;
  3614. var sessionArray = {};
  3615. if (sessionStorage["blanketSessionLoader"]){
  3616. sessionArray = JSON.parse(sessionStorage["blanketSessionLoader"]);
  3617. }
  3618. var fileLoader = function(event){
  3619. var fileContent = event.currentTarget.result;
  3620. var file = files[sessionIndx];
  3621. var filename = file.webkitRelativePath && file.webkitRelativePath !== '' ? file.webkitRelativePath : file.name;
  3622. sessionArray[filename] = fileContent;
  3623. sessionIndx++;
  3624. if (sessionIndx === sessionLength){
  3625. sessionStorage.setItem("blanketSessionLoader", JSON.stringify(sessionArray));
  3626. document.location.reload();
  3627. }else{
  3628. readFile(files[sessionIndx]);
  3629. }
  3630. };
  3631. function readFile(file){
  3632. var reader = new FileReader();
  3633. reader.onload = fileLoader;
  3634. reader.readAsText(file);
  3635. }
  3636. readFile(files[sessionIndx]);
  3637. },
  3638. _loadFile: function(path){
  3639. if (typeof path !== "undefined"){
  3640. var request = new XMLHttpRequest();
  3641. request.open('GET', path, false);
  3642. request.send();
  3643. _blanket._addScript(request.responseText);
  3644. }
  3645. },
  3646. _addScript: function(data){
  3647. var script = document.createElement("script");
  3648. script.type = "text/javascript";
  3649. script.text = data;
  3650. (document.body || document.getElementsByTagName('head')[0]).appendChild(script);
  3651. },
  3652. hasAdapter: function(callback){
  3653. return _blanket.options("adapter") !== null;
  3654. },
  3655. report: function(coverage_data){
  3656. if (!document.getElementById("blanketLoaderDialog")){
  3657. //all found, clear it
  3658. _blanket.blanketSession = null;
  3659. }
  3660. coverage_data.files = window._$blanket;
  3661. var require = blanket.options("commonJS") ? blanket._commonjs.require : window.require;
  3662. // Check if we have any covered files that requires reporting
  3663. // otherwise just exit gracefully.
  3664. if (!coverage_data.files || !Object.keys(coverage_data.files).length) {
  3665. if (_blanket.options("debug")) {console.log("BLANKET-Reporting No files were instrumented.");}
  3666. return;
  3667. }
  3668. if (typeof coverage_data.files.branchFcn !== "undefined"){
  3669. delete coverage_data.files.branchFcn;
  3670. }
  3671. if (typeof _blanket.options("reporter") === "string"){
  3672. _blanket._loadFile(_blanket.options("reporter"));
  3673. _blanket.customReporter(coverage_data,_blanket.options("reporter_options"));
  3674. }else if (typeof _blanket.options("reporter") === "function"){
  3675. _blanket.options("reporter")(coverage_data,_blanket.options("reporter_options"));
  3676. }else if (typeof _blanket.defaultReporter === 'function'){
  3677. _blanket.defaultReporter(coverage_data,_blanket.options("reporter_options"));
  3678. }else{
  3679. throw new Error("no reporter defined.");
  3680. }
  3681. },
  3682. _bindStartTestRunner: function(bindEvent,startEvent){
  3683. if (bindEvent){
  3684. bindEvent(startEvent);
  3685. }else{
  3686. window.addEventListener("load",startEvent,false);
  3687. }
  3688. },
  3689. _loadSourceFiles: function(callback){
  3690. var require = blanket.options("commonJS") ? blanket._commonjs.require : window.require;
  3691. function copy(o){
  3692. var _copy = Object.create( Object.getPrototypeOf(o) );
  3693. var propNames = Object.getOwnPropertyNames(o);
  3694. propNames.forEach(function(name){
  3695. var desc = Object.getOwnPropertyDescriptor(o, name);
  3696. Object.defineProperty(_copy, name, desc);
  3697. });
  3698. return _copy;
  3699. }
  3700. if (_blanket.options("debug")) {console.log("BLANKET-Collecting page scripts");}
  3701. var scripts = _blanket.utils.collectPageScripts();
  3702. //_blanket.options("filter",scripts);
  3703. if (scripts.length === 0){
  3704. callback();
  3705. }else{
  3706. //check session state
  3707. if (sessionStorage["blanketSessionLoader"]){
  3708. _blanket.blanketSession = JSON.parse(sessionStorage["blanketSessionLoader"]);
  3709. }
  3710. scripts.forEach(function(file,indx){
  3711. _blanket.utils.cache[file]={
  3712. loaded:false
  3713. };
  3714. });
  3715. var currScript=-1;
  3716. _blanket.utils.loadAll(function(test){
  3717. if (test){
  3718. return typeof scripts[currScript+1] !== 'undefined';
  3719. }
  3720. currScript++;
  3721. if (currScript >= scripts.length){
  3722. return null;
  3723. }
  3724. return scripts[currScript];
  3725. },callback);
  3726. }
  3727. },
  3728. beforeStartTestRunner: function(opts){
  3729. opts = opts || {};
  3730. opts.checkRequirejs = typeof opts.checkRequirejs === "undefined" ? true : opts.checkRequirejs;
  3731. opts.callback = opts.callback || function() { };
  3732. opts.coverage = typeof opts.coverage === "undefined" ? true : opts.coverage;
  3733. if (opts.coverage) {
  3734. _blanket._bindStartTestRunner(opts.bindEvent,
  3735. function(){
  3736. _blanket._loadSourceFiles(function() {
  3737. var allLoaded = function(){
  3738. return opts.condition ? opts.condition() : _blanket.requireFilesLoaded();
  3739. };
  3740. var check = function() {
  3741. if (allLoaded()) {
  3742. if (_blanket.options("debug")) {console.log("BLANKET-All files loaded, init start test runner callback.");}
  3743. var cb = _blanket.options("testReadyCallback");
  3744. if (cb){
  3745. if (typeof cb === "function"){
  3746. cb(opts.callback);
  3747. }else if (typeof cb === "string"){
  3748. _blanket._addScript(cb);
  3749. opts.callback();
  3750. }
  3751. }else{
  3752. opts.callback();
  3753. }
  3754. } else {
  3755. setTimeout(check, 13);
  3756. }
  3757. };
  3758. check();
  3759. });
  3760. });
  3761. }else{
  3762. opts.callback();
  3763. }
  3764. },
  3765. utils: {
  3766. qualifyURL: function (url) {
  3767. //http://stackoverflow.com/questions/470832/getting-an-absolute-url-from-a-relative-one-ie6-issue
  3768. var a = document.createElement('a');
  3769. a.href = url;
  3770. return a.href;
  3771. }
  3772. }
  3773. });
  3774. })(blanket);
  3775. blanket.defaultReporter = function(coverage){
  3776. 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;}",
  3777. successRate = 60,
  3778. head = document.head,
  3779. fileNumber = 0,
  3780. body = document.body,
  3781. headerContent,
  3782. hasBranchTracking = Object.keys(coverage.files).some(function(elem){
  3783. return typeof coverage.files[elem].branchData !== 'undefined';
  3784. }),
  3785. 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>",
  3786. 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>";
  3787. 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>";
  3788. function blanket_toggleSource(id) {
  3789. var element = document.getElementById(id);
  3790. if(element.style.display === 'block') {
  3791. element.style.display = 'none';
  3792. } else {
  3793. element.style.display = 'block';
  3794. }
  3795. }
  3796. var script = document.createElement("script");
  3797. script.type = "text/javascript";
  3798. script.text = blanket_toggleSource.toString().replace('function ' + blanket_toggleSource.name, 'function blanket_toggleSource');
  3799. body.appendChild(script);
  3800. var percentage = function(number, total) {
  3801. return (Math.round(((number/total) * 100)*100)/100);
  3802. };
  3803. var appendTag = function (type, el, str) {
  3804. var dom = document.createElement(type);
  3805. dom.innerHTML = str;
  3806. el.appendChild(dom);
  3807. };
  3808. function escapeInvalidXmlChars(str) {
  3809. return str.replace(/\&/g, "&amp;")
  3810. .replace(/</g, "&lt;")
  3811. .replace(/\>/g, "&gt;")
  3812. .replace(/\"/g, "&quot;")
  3813. .replace(/\'/g, "&apos;");
  3814. }
  3815. function isBranchFollowed(data,bool){
  3816. var mode = bool ? 0 : 1;
  3817. if (typeof data === 'undefined' ||
  3818. typeof data === null ||
  3819. typeof data[mode] === 'undefined'){
  3820. return false;
  3821. }
  3822. return data[mode].length > 0;
  3823. }
  3824. var branchStack = [];
  3825. function branchReport(colsIndex,src,cols,offset,lineNum){
  3826. var newsrc="";
  3827. var postfix="";
  3828. if (branchStack.length > 0){
  3829. newsrc += "<span class='" + (isBranchFollowed(branchStack[0][1],branchStack[0][1].consequent === branchStack[0][0]) ? 'branchOkay' : 'branchWarning') + "'>";
  3830. if (branchStack[0][0].end.line === lineNum){
  3831. newsrc += escapeInvalidXmlChars(src.slice(0,branchStack[0][0].end.column)) + "</span>";
  3832. src = src.slice(branchStack[0][0].end.column);
  3833. branchStack.shift();
  3834. if (branchStack.length > 0){
  3835. newsrc += "<span class='" + (isBranchFollowed(branchStack[0][1],false) ? 'branchOkay' : 'branchWarning') + "'>";
  3836. if (branchStack[0][0].end.line === lineNum){
  3837. newsrc += escapeInvalidXmlChars(src.slice(0,branchStack[0][0].end.column)) + "</span>";
  3838. src = src.slice(branchStack[0][0].end.column);
  3839. branchStack.shift();
  3840. if (!cols){
  3841. return {src: newsrc + escapeInvalidXmlChars(src) ,cols:cols};
  3842. }
  3843. }
  3844. else if (!cols){
  3845. return {src: newsrc + escapeInvalidXmlChars(src) + "</span>",cols:cols};
  3846. }
  3847. else{
  3848. postfix = "</span>";
  3849. }
  3850. }else if (!cols){
  3851. return {src: newsrc + escapeInvalidXmlChars(src) ,cols:cols};
  3852. }
  3853. }else if(!cols){
  3854. return {src: newsrc + escapeInvalidXmlChars(src) + "</span>",cols:cols};
  3855. }else{
  3856. postfix = "</span>";
  3857. }
  3858. }
  3859. var thisline = cols[colsIndex];
  3860. //consequent
  3861. var cons = thisline.consequent;
  3862. if (cons.start.line > lineNum){
  3863. branchStack.unshift([thisline.alternate,thisline]);
  3864. branchStack.unshift([cons,thisline]);
  3865. src = escapeInvalidXmlChars(src);
  3866. }else{
  3867. var style = "<span class='" + (isBranchFollowed(thisline,true) ? 'branchOkay' : 'branchWarning') + "'>";
  3868. newsrc += escapeInvalidXmlChars(src.slice(0,cons.start.column-offset)) + style;
  3869. if (cols.length > colsIndex+1 &&
  3870. cols[colsIndex+1].consequent.start.line === lineNum &&
  3871. cols[colsIndex+1].consequent.start.column-offset < cols[colsIndex].consequent.end.column-offset)
  3872. {
  3873. var res = branchReport(colsIndex+1,src.slice(cons.start.column-offset,cons.end.column-offset),cols,cons.start.column-offset,lineNum);
  3874. newsrc += res.src;
  3875. cols = res.cols;
  3876. cols[colsIndex+1] = cols[colsIndex+2];
  3877. cols.length--;
  3878. }else{
  3879. newsrc += escapeInvalidXmlChars(src.slice(cons.start.column-offset,cons.end.column-offset));
  3880. }
  3881. newsrc += "</span>";
  3882. var alt = thisline.alternate;
  3883. if (alt.start.line > lineNum){
  3884. newsrc += escapeInvalidXmlChars(src.slice(cons.end.column-offset));
  3885. branchStack.unshift([alt,thisline]);
  3886. }else{
  3887. newsrc += escapeInvalidXmlChars(src.slice(cons.end.column-offset,alt.start.column-offset));
  3888. style = "<span class='" + (isBranchFollowed(thisline,false) ? 'branchOkay' : 'branchWarning') + "'>";
  3889. newsrc += style;
  3890. if (cols.length > colsIndex+1 &&
  3891. cols[colsIndex+1].consequent.start.line === lineNum &&
  3892. cols[colsIndex+1].consequent.start.column-offset < cols[colsIndex].alternate.end.column-offset)
  3893. {
  3894. var res2 = branchReport(colsIndex+1,src.slice(alt.start.column-offset,alt.end.column-offset),cols,alt.start.column-offset,lineNum);
  3895. newsrc += res2.src;
  3896. cols = res2.cols;
  3897. cols[colsIndex+1] = cols[colsIndex+2];
  3898. cols.length--;
  3899. }else{
  3900. newsrc += escapeInvalidXmlChars(src.slice(alt.start.column-offset,alt.end.column-offset));
  3901. }
  3902. newsrc += "</span>";
  3903. newsrc += escapeInvalidXmlChars(src.slice(alt.end.column-offset));
  3904. src = newsrc;
  3905. }
  3906. }
  3907. return {src:src+postfix, cols:cols};
  3908. }
  3909. var isUndefined = function(item){
  3910. return typeof item !== 'undefined';
  3911. };
  3912. var files = coverage.files;
  3913. var totals = {
  3914. totalSmts: 0,
  3915. numberOfFilesCovered: 0,
  3916. passedBranches: 0,
  3917. totalBranches: 0,
  3918. moduleTotalStatements : {},
  3919. moduleTotalCoveredStatements : {},
  3920. moduleTotalBranches : {},
  3921. moduleTotalCoveredBranches : {}
  3922. };
  3923. // check if a data-cover-modulepattern was provided for per-module coverage reporting
  3924. var modulePattern = _blanket.options("modulePattern");
  3925. var modulePatternRegex = ( modulePattern ? new RegExp(modulePattern) : null );
  3926. for(var file in files)
  3927. {
  3928. fileNumber++;
  3929. var statsForFile = files[file],
  3930. totalSmts = 0,
  3931. numberOfFilesCovered = 0,
  3932. code = [],
  3933. i;
  3934. var end = [];
  3935. for(i = 0; i < statsForFile.source.length; i +=1){
  3936. var src = statsForFile.source[i];
  3937. if (branchStack.length > 0 ||
  3938. typeof statsForFile.branchData !== 'undefined')
  3939. {
  3940. if (typeof statsForFile.branchData[i+1] !== 'undefined')
  3941. {
  3942. var cols = statsForFile.branchData[i+1].filter(isUndefined);
  3943. var colsIndex=0;
  3944. src = branchReport(colsIndex,src,cols,0,i+1).src;
  3945. }else if (branchStack.length){
  3946. src = branchReport(0,src,null,0,i+1).src;
  3947. }else{
  3948. src = escapeInvalidXmlChars(src);
  3949. }
  3950. }else{
  3951. src = escapeInvalidXmlChars(src);
  3952. }
  3953. var lineClass="";
  3954. if(statsForFile[i+1]) {
  3955. numberOfFilesCovered += 1;
  3956. totalSmts += 1;
  3957. lineClass = 'hit';
  3958. }else{
  3959. if(statsForFile[i+1] === 0){
  3960. totalSmts++;
  3961. lineClass = 'miss';
  3962. }
  3963. }
  3964. code[i + 1] = "<div class='"+lineClass+"'><span class=''>"+(i + 1)+"</span>"+src+"</div>";
  3965. }
  3966. totals.totalSmts += totalSmts;
  3967. totals.numberOfFilesCovered += numberOfFilesCovered;
  3968. var totalBranches=0;
  3969. var passedBranches=0;
  3970. if (typeof statsForFile.branchData !== 'undefined'){
  3971. for(var j=0;j<statsForFile.branchData.length;j++){
  3972. if (typeof statsForFile.branchData[j] !== 'undefined'){
  3973. for(var k=0;k<statsForFile.branchData[j].length;k++){
  3974. if (typeof statsForFile.branchData[j][k] !== 'undefined'){
  3975. totalBranches++;
  3976. if (typeof statsForFile.branchData[j][k][0] !== 'undefined' &&
  3977. statsForFile.branchData[j][k][0].length > 0 &&
  3978. typeof statsForFile.branchData[j][k][1] !== 'undefined' &&
  3979. statsForFile.branchData[j][k][1].length > 0){
  3980. passedBranches++;
  3981. }
  3982. }
  3983. }
  3984. }
  3985. }
  3986. }
  3987. totals.passedBranches += passedBranches;
  3988. totals.totalBranches += totalBranches;
  3989. // if "data-cover-modulepattern" was provided,
  3990. // track totals per module name as well as globally
  3991. if (modulePatternRegex) {
  3992. var moduleName = file.match(modulePatternRegex)[1];
  3993. if(!totals.moduleTotalStatements.hasOwnProperty(moduleName)) {
  3994. totals.moduleTotalStatements[moduleName] = 0;
  3995. totals.moduleTotalCoveredStatements[moduleName] = 0;
  3996. }
  3997. totals.moduleTotalStatements[moduleName] += totalSmts;
  3998. totals.moduleTotalCoveredStatements[moduleName] += numberOfFilesCovered;
  3999. if(!totals.moduleTotalBranches.hasOwnProperty(moduleName)) {
  4000. totals.moduleTotalBranches[moduleName] = 0;
  4001. totals.moduleTotalCoveredBranches[moduleName] = 0;
  4002. }
  4003. totals.moduleTotalBranches[moduleName] += totalBranches;
  4004. totals.moduleTotalCoveredBranches[moduleName] += passedBranches;
  4005. }
  4006. var result = percentage(numberOfFilesCovered, totalSmts);
  4007. var output = fileTemplate.replace("{{file}}", file)
  4008. .replace("{{percentage}}",result)
  4009. .replace("{{numberCovered}}", numberOfFilesCovered)
  4010. .replace(/\{\{fileNumber\}\}/g, fileNumber)
  4011. .replace("{{totalSmts}}", totalSmts)
  4012. .replace("{{totalBranches}}", totalBranches)
  4013. .replace("{{passedBranches}}", passedBranches)
  4014. .replace("{{source}}", code.join(" "));
  4015. if(result < successRate)
  4016. {
  4017. output = output.replace("{{statusclass}}", "bl-error");
  4018. } else {
  4019. output = output.replace("{{statusclass}}", "bl-success");
  4020. }
  4021. bodyContent += output;
  4022. }
  4023. // create temporary function for use by the global totals reporter,
  4024. // as well as the per-module totals reporter
  4025. var createAggregateTotal = function(numSt, numCov, numBranch, numCovBr, moduleName) {
  4026. var totalPercent = percentage(numCov, numSt);
  4027. var statusClass = totalPercent < successRate ? "bl-error" : "bl-success";
  4028. var rowTitle = ( moduleName ? "Total for module: " + moduleName : "Global total" );
  4029. var totalsOutput = grandTotalTemplate.replace("{{rowTitle}}", rowTitle)
  4030. .replace("{{percentage}}", totalPercent)
  4031. .replace("{{numberCovered}}", numCov)
  4032. .replace("{{totalSmts}}", numSt)
  4033. .replace("{{passedBranches}}", numCovBr)
  4034. .replace("{{totalBranches}}", numBranch)
  4035. .replace("{{statusclass}}", statusClass);
  4036. bodyContent += totalsOutput;
  4037. };
  4038. // if "data-cover-modulepattern" was provided,
  4039. // output the per-module totals alongside the global totals
  4040. if (modulePatternRegex) {
  4041. for (var thisModuleName in totals.moduleTotalStatements) {
  4042. if (totals.moduleTotalStatements.hasOwnProperty(thisModuleName)) {
  4043. var moduleTotalSt = totals.moduleTotalStatements[thisModuleName];
  4044. var moduleTotalCovSt = totals.moduleTotalCoveredStatements[thisModuleName];
  4045. var moduleTotalBr = totals.moduleTotalBranches[thisModuleName];
  4046. var moduleTotalCovBr = totals.moduleTotalCoveredBranches[thisModuleName];
  4047. createAggregateTotal(moduleTotalSt, moduleTotalCovSt, moduleTotalBr, moduleTotalCovBr, thisModuleName);
  4048. }
  4049. }
  4050. }
  4051. createAggregateTotal(totals.totalSmts, totals.numberOfFilesCovered, totals.totalBranches, totals.passedBranches, null);
  4052. bodyContent += "</div>"; //closing main
  4053. appendTag('style', head, cssSytle);
  4054. //appendStyle(body, headerContent);
  4055. if (document.getElementById("blanket-main")){
  4056. document.getElementById("blanket-main").innerHTML=
  4057. bodyContent.slice(23,-6);
  4058. }else{
  4059. appendTag('div', body, bodyContent);
  4060. }
  4061. //appendHtml(body, '</div>');
  4062. };
  4063. (function(){
  4064. var newOptions={};
  4065. //http://stackoverflow.com/a/2954896
  4066. var toArray =Array.prototype.slice;
  4067. var scripts = toArray.call(document.scripts);
  4068. toArray.call(scripts[scripts.length - 1].attributes)
  4069. .forEach(function(es){
  4070. if(es.nodeName === "data-cover-only"){
  4071. newOptions.filter = es.nodeValue;
  4072. }
  4073. if(es.nodeName === "data-cover-never"){
  4074. newOptions.antifilter = es.nodeValue;
  4075. }
  4076. if(es.nodeName === "data-cover-reporter"){
  4077. newOptions.reporter = es.nodeValue;
  4078. }
  4079. if (es.nodeName === "data-cover-adapter"){
  4080. newOptions.adapter = es.nodeValue;
  4081. }
  4082. if (es.nodeName === "data-cover-loader"){
  4083. newOptions.loader = es.nodeValue;
  4084. }
  4085. if (es.nodeName === "data-cover-timeout"){
  4086. newOptions.timeout = es.nodeValue;
  4087. }
  4088. if (es.nodeName === "data-cover-modulepattern") {
  4089. newOptions.modulePattern = es.nodeValue;
  4090. }
  4091. if (es.nodeName === "data-cover-reporter-options"){
  4092. try{
  4093. newOptions.reporter_options = JSON.parse(es.nodeValue);
  4094. }catch(e){
  4095. if (blanket.options("debug")){
  4096. throw new Error("Invalid reporter options. Must be a valid stringified JSON object.");
  4097. }
  4098. }
  4099. }
  4100. if (es.nodeName === "data-cover-testReadyCallback"){
  4101. newOptions.testReadyCallback = es.nodeValue;
  4102. }
  4103. if (es.nodeName === "data-cover-customVariable"){
  4104. newOptions.customVariable = es.nodeValue;
  4105. }
  4106. if (es.nodeName === "data-cover-flags"){
  4107. var flags = " "+es.nodeValue+" ";
  4108. if (flags.indexOf(" ignoreError ") > -1){
  4109. newOptions.ignoreScriptError = true;
  4110. }
  4111. if (flags.indexOf(" autoStart ") > -1){
  4112. newOptions.autoStart = true;
  4113. }
  4114. if (flags.indexOf(" ignoreCors ") > -1){
  4115. newOptions.ignoreCors = true;
  4116. }
  4117. if (flags.indexOf(" branchTracking ") > -1){
  4118. newOptions.branchTracking = true;
  4119. }
  4120. if (flags.indexOf(" sourceURL ") > -1){
  4121. newOptions.sourceURL = true;
  4122. }
  4123. if (flags.indexOf(" debug ") > -1){
  4124. newOptions.debug = true;
  4125. }
  4126. if (flags.indexOf(" engineOnly ") > -1){
  4127. newOptions.engineOnly = true;
  4128. }
  4129. if (flags.indexOf(" commonJS ") > -1){
  4130. newOptions.commonJS = true;
  4131. }
  4132. if (flags.indexOf(" instrumentCache ") > -1){
  4133. newOptions.instrumentCache = true;
  4134. }
  4135. }
  4136. });
  4137. blanket.options(newOptions);
  4138. if (typeof requirejs !== 'undefined'){
  4139. blanket.options("existingRequireJS",true);
  4140. }
  4141. /* setup requirejs loader, if needed */
  4142. if (blanket.options("commonJS")){
  4143. blanket._commonjs = {};
  4144. }
  4145. })();
  4146. (function(_blanket){
  4147. _blanket.extend({
  4148. utils: {
  4149. normalizeBackslashes: function(str) {
  4150. return str.replace(/\\/g, '/');
  4151. },
  4152. matchPatternAttribute: function(filename,pattern){
  4153. if (typeof pattern === 'string'){
  4154. if (pattern.indexOf("[") === 0){
  4155. //treat as array
  4156. var pattenArr = pattern.slice(1,pattern.length-1).split(",");
  4157. return pattenArr.some(function(elem){
  4158. return _blanket.utils.matchPatternAttribute(filename,_blanket.utils.normalizeBackslashes(elem.slice(1,-1)));
  4159. //return filename.indexOf(_blanket.utils.normalizeBackslashes(elem.slice(1,-1))) > -1;
  4160. });
  4161. }else if ( pattern.indexOf("//") === 0){
  4162. var ex = pattern.slice(2,pattern.lastIndexOf('/'));
  4163. var mods = pattern.slice(pattern.lastIndexOf('/')+1);
  4164. var regex = new RegExp(ex,mods);
  4165. return regex.test(filename);
  4166. }else if (pattern.indexOf("#") === 0){
  4167. return window[pattern.slice(1)].call(window,filename);
  4168. }else{
  4169. return filename.indexOf(_blanket.utils.normalizeBackslashes(pattern)) > -1;
  4170. }
  4171. }else if ( pattern instanceof Array ){
  4172. return pattern.some(function(elem){
  4173. return _blanket.utils.matchPatternAttribute(filename,elem);
  4174. });
  4175. }else if (pattern instanceof RegExp){
  4176. return pattern.test(filename);
  4177. }else if (typeof pattern === "function"){
  4178. return pattern.call(window,filename);
  4179. }
  4180. },
  4181. blanketEval: function(data){
  4182. _blanket._addScript(data);
  4183. },
  4184. collectPageScripts: function(){
  4185. var toArray = Array.prototype.slice;
  4186. var scripts = toArray.call(document.scripts);
  4187. var selectedScripts=[],scriptNames=[];
  4188. var filter = _blanket.options("filter");
  4189. if(filter != null){
  4190. //global filter in place, data-cover-only
  4191. var antimatch = _blanket.options("antifilter");
  4192. selectedScripts = toArray.call(document.scripts)
  4193. .filter(function(s){
  4194. return toArray.call(s.attributes).filter(function(sn){
  4195. return sn.nodeName === "src" && _blanket.utils.matchPatternAttribute(sn.nodeValue,filter) &&
  4196. (typeof antimatch === "undefined" || !_blanket.utils.matchPatternAttribute(sn.nodeValue,antimatch));
  4197. }).length === 1;
  4198. });
  4199. }else{
  4200. selectedScripts = toArray.call(document.querySelectorAll("script[data-cover]"));
  4201. }
  4202. scriptNames = selectedScripts.map(function(s){
  4203. return _blanket.utils.qualifyURL(
  4204. toArray.call(s.attributes).filter(
  4205. function(sn){
  4206. return sn.nodeName === "src";
  4207. })[0].nodeValue);
  4208. });
  4209. if (!filter){
  4210. _blanket.options("filter","['"+scriptNames.join("','")+"']");
  4211. }
  4212. return scriptNames;
  4213. },
  4214. loadAll: function(nextScript,cb,preprocessor){
  4215. /**
  4216. * load dependencies
  4217. * @param {nextScript} factory for priority level
  4218. * @param {cb} the done callback
  4219. */
  4220. var currScript=nextScript();
  4221. var isLoaded = _blanket.utils.scriptIsLoaded(
  4222. currScript,
  4223. _blanket.utils.ifOrdered,
  4224. nextScript,
  4225. cb
  4226. );
  4227. if (!(_blanket.utils.cache[currScript] && _blanket.utils.cache[currScript].loaded)){
  4228. var attach = function(){
  4229. if (_blanket.options("debug")) {console.log("BLANKET-Mark script:"+currScript+", as loaded and move to next script.");}
  4230. isLoaded();
  4231. };
  4232. var whenDone = function(result){
  4233. if (_blanket.options("debug")) {console.log("BLANKET-File loading finished");}
  4234. if (typeof result !== 'undefined'){
  4235. if (_blanket.options("debug")) {console.log("BLANKET-Add file to DOM.");}
  4236. _blanket._addScript(result);
  4237. }
  4238. attach();
  4239. };
  4240. _blanket.utils.attachScript(
  4241. {
  4242. url: currScript
  4243. },
  4244. function (content){
  4245. _blanket.utils.processFile(
  4246. content,
  4247. currScript,
  4248. whenDone,
  4249. whenDone
  4250. );
  4251. }
  4252. );
  4253. }else{
  4254. isLoaded();
  4255. }
  4256. },
  4257. attachScript: function(options,cb){
  4258. var timeout = _blanket.options("timeout") || 3000;
  4259. setTimeout(function(){
  4260. if (!_blanket.utils.cache[options.url].loaded){
  4261. throw new Error("error loading source script");
  4262. }
  4263. },timeout);
  4264. _blanket.utils.getFile(
  4265. options.url,
  4266. cb,
  4267. function(){ throw new Error("error loading source script");}
  4268. );
  4269. },
  4270. ifOrdered: function(nextScript,cb){
  4271. /**
  4272. * ordered loading callback
  4273. * @param {nextScript} factory for priority level
  4274. * @param {cb} the done callback
  4275. */
  4276. var currScript = nextScript(true);
  4277. if (currScript){
  4278. _blanket.utils.loadAll(nextScript,cb);
  4279. }else{
  4280. cb(new Error("Error in loading chain."));
  4281. }
  4282. },
  4283. scriptIsLoaded: function(url,orderedCb,nextScript,cb){
  4284. /**
  4285. * returns a callback that checks a loading list to see if a script is loaded.
  4286. * @param {orderedCb} callback if ordered loading is being done
  4287. * @param {nextScript} factory for next priority level
  4288. * @param {cb} the done callback
  4289. */
  4290. if (_blanket.options("debug")) {console.log("BLANKET-Returning function");}
  4291. return function(){
  4292. if (_blanket.options("debug")) {console.log("BLANKET-Marking file as loaded: "+url);}
  4293. _blanket.utils.cache[url].loaded=true;
  4294. if (_blanket.utils.allLoaded()){
  4295. if (_blanket.options("debug")) {console.log("BLANKET-All files loaded");}
  4296. cb();
  4297. }else if (orderedCb){
  4298. //if it's ordered we need to
  4299. //traverse down to the next
  4300. //priority level
  4301. if (_blanket.options("debug")) {console.log("BLANKET-Load next file.");}
  4302. orderedCb(nextScript,cb);
  4303. }
  4304. };
  4305. },
  4306. cache: {},
  4307. allLoaded: function (){
  4308. /**
  4309. * check if depdencies are loaded in cache
  4310. */
  4311. var cached = Object.keys(_blanket.utils.cache);
  4312. for (var i=0;i<cached.length;i++){
  4313. if (!_blanket.utils.cache[cached[i]].loaded){
  4314. return false;
  4315. }
  4316. }
  4317. return true;
  4318. },
  4319. processFile: function (content,url,cb,oldCb) {
  4320. var match = _blanket.options("filter");
  4321. //we check the never matches first
  4322. var antimatch = _blanket.options("antifilter");
  4323. if (typeof antimatch !== "undefined" &&
  4324. _blanket.utils.matchPatternAttribute(url,antimatch)
  4325. ){
  4326. oldCb(content);
  4327. if (_blanket.options("debug")) {console.log("BLANKET-File will never be instrumented:"+url);}
  4328. _blanket.requiringFile(url,true);
  4329. }else if (_blanket.utils.matchPatternAttribute(url,match)){
  4330. if (_blanket.options("debug")) {console.log("BLANKET-Attempting instrument of:"+url);}
  4331. _blanket.instrument({
  4332. inputFile: content,
  4333. inputFileName: url
  4334. },function(instrumented){
  4335. try{
  4336. if (_blanket.options("debug")) {console.log("BLANKET-instrument of:"+url+" was successfull.");}
  4337. _blanket.utils.blanketEval(instrumented);
  4338. cb();
  4339. _blanket.requiringFile(url,true);
  4340. }
  4341. catch(err){
  4342. if (_blanket.options("ignoreScriptError")){
  4343. //we can continue like normal if
  4344. //we're ignoring script errors,
  4345. //but otherwise we don't want
  4346. //to completeLoad or the error might be
  4347. //missed.
  4348. if (_blanket.options("debug")) { console.log("BLANKET-There was an error loading the file:"+url); }
  4349. cb(content);
  4350. _blanket.requiringFile(url,true);
  4351. }else{
  4352. throw new Error("Error parsing instrumented code: "+err);
  4353. }
  4354. }
  4355. });
  4356. }else{
  4357. if (_blanket.options("debug")) { console.log("BLANKET-Loading (without instrumenting) the file:"+url);}
  4358. oldCb(content);
  4359. _blanket.requiringFile(url,true);
  4360. }
  4361. },
  4362. cacheXhrConstructor: function(){
  4363. var Constructor, createXhr, i, progId;
  4364. if (typeof XMLHttpRequest !== "undefined") {
  4365. Constructor = XMLHttpRequest;
  4366. this.createXhr = function() { return new Constructor(); };
  4367. } else if (typeof ActiveXObject !== "undefined") {
  4368. Constructor = ActiveXObject;
  4369. for (i = 0; i < 3; i += 1) {
  4370. progId = progIds[i];
  4371. try {
  4372. new ActiveXObject(progId);
  4373. break;
  4374. } catch (e) {}
  4375. }
  4376. this.createXhr = function() { return new Constructor(progId); };
  4377. }
  4378. },
  4379. craeteXhr: function () {
  4380. throw new Error("cacheXhrConstructor is supposed to overwrite this function.");
  4381. },
  4382. getFile: function(url, callback, errback, onXhr){
  4383. var foundInSession = false;
  4384. if (_blanket.blanketSession){
  4385. var files = Object.keys(_blanket.blanketSession);
  4386. for (var i=0; i<files.length;i++ ){
  4387. var key = files[i];
  4388. if (url.indexOf(key) > -1){
  4389. callback(_blanket.blanketSession[key]);
  4390. foundInSession=true;
  4391. return;
  4392. }
  4393. }
  4394. }
  4395. if (!foundInSession){
  4396. var xhr = _blanket.utils.createXhr();
  4397. xhr.open('GET', url, true);
  4398. //Allow overrides specified in config
  4399. if (onXhr) {
  4400. onXhr(xhr, url);
  4401. }
  4402. xhr.onreadystatechange = function (evt) {
  4403. var status, err;
  4404. //Do not explicitly handle errors, those should be
  4405. //visible via console output in the browser.
  4406. if (xhr.readyState === 4) {
  4407. status = xhr.status;
  4408. if ((status > 399 && status < 600) /*||
  4409. (status === 0 &&
  4410. navigator.userAgent.toLowerCase().indexOf('firefox') > -1)
  4411. */ ) {
  4412. //An http 4xx or 5xx error. Signal an error.
  4413. err = new Error(url + ' HTTP status: ' + status);
  4414. err.xhr = xhr;
  4415. errback(err);
  4416. } else {
  4417. callback(xhr.responseText);
  4418. }
  4419. }
  4420. };
  4421. try{
  4422. xhr.send(null);
  4423. }catch(e){
  4424. if (e.code && (e.code === 101 || e.code === 1012) && _blanket.options("ignoreCors") === false){
  4425. //running locally and getting error from browser
  4426. _blanket.showManualLoader();
  4427. } else {
  4428. throw e;
  4429. }
  4430. }
  4431. }
  4432. }
  4433. }
  4434. });
  4435. (function(){
  4436. var require = blanket.options("commonJS") ? blanket._commonjs.require : window.require;
  4437. var requirejs = blanket.options("commonJS") ? blanket._commonjs.requirejs : window.requirejs;
  4438. if (!_blanket.options("engineOnly") && _blanket.options("existingRequireJS")){
  4439. _blanket.utils.oldloader = requirejs.load;
  4440. requirejs.load = function (context, moduleName, url) {
  4441. _blanket.requiringFile(url);
  4442. _blanket.utils.getFile(url,
  4443. function(content){
  4444. _blanket.utils.processFile(
  4445. content,
  4446. url,
  4447. function newLoader(){
  4448. context.completeLoad(moduleName);
  4449. },
  4450. function oldLoader(){
  4451. _blanket.utils.oldloader(context, moduleName, url);
  4452. }
  4453. );
  4454. }, function (err) {
  4455. _blanket.requiringFile();
  4456. throw err;
  4457. });
  4458. };
  4459. }
  4460. // Save the XHR constructor, just in case frameworks like Sinon would sandbox it.
  4461. _blanket.utils.cacheXhrConstructor();
  4462. })();
  4463. })(blanket);
  4464. (function() {
  4465. if(!mocha) {
  4466. throw new Exception("mocha library does not exist in global namespace!");
  4467. }
  4468. /*
  4469. * Mocha Events:
  4470. *
  4471. * - `start` execution started
  4472. * - `end` execution complete
  4473. * - `suite` (suite) test suite execution started
  4474. * - `suite end` (suite) all tests (and sub-suites) have finished
  4475. * - `test` (test) test execution started
  4476. * - `test end` (test) test completed
  4477. * - `hook` (hook) hook execution started
  4478. * - `hook end` (hook) hook complete
  4479. * - `pass` (test) test passed
  4480. * - `fail` (test, err) test failed
  4481. *
  4482. */
  4483. var OriginalReporter = mocha._reporter;
  4484. var BlanketReporter = function(runner) {
  4485. runner.on('start', function() {
  4486. blanket.setupCoverage();
  4487. });
  4488. runner.on('end', function() {
  4489. blanket.onTestsDone();
  4490. });
  4491. runner.on('suite', function() {
  4492. blanket.onModuleStart();
  4493. });
  4494. runner.on('test', function() {
  4495. blanket.onTestStart();
  4496. });
  4497. runner.on('test end', function(test) {
  4498. blanket.onTestDone(test.parent.tests.length, test.state === 'passed');
  4499. });
  4500. // NOTE: this is an instance of BlanketReporter
  4501. new OriginalReporter(runner);
  4502. };
  4503. BlanketReporter.prototype = OriginalReporter.prototype;
  4504. mocha.reporter(BlanketReporter);
  4505. var oldRun = mocha.run,
  4506. oldCallback = null;
  4507. mocha.run = function (finishCallback) {
  4508. oldCallback = finishCallback;
  4509. console.log("waiting for blanket...");
  4510. };
  4511. blanket.beforeStartTestRunner({
  4512. callback: function(){
  4513. if (!blanket.options("existingRequireJS")){
  4514. oldRun(oldCallback);
  4515. }
  4516. mocha.run = oldRun;
  4517. }
  4518. });
  4519. })();