tokenizer.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566
  1. /*jshint node:true */
  2. /*
  3. The MIT License (MIT)
  4. Copyright (c) 2007-2018 Einar Lielmanis, Liam Newman, and contributors.
  5. Permission is hereby granted, free of charge, to any person
  6. obtaining a copy of this software and associated documentation files
  7. (the "Software"), to deal in the Software without restriction,
  8. including without limitation the rights to use, copy, modify, merge,
  9. publish, distribute, sublicense, and/or sell copies of the Software,
  10. and to permit persons to whom the Software is furnished to do so,
  11. subject to the following conditions:
  12. The above copyright notice and this permission notice shall be
  13. included in all copies or substantial portions of the Software.
  14. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  15. EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  16. MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  17. NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
  18. BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
  19. ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
  20. CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  21. SOFTWARE.
  22. */
  23. 'use strict';
  24. var InputScanner = require('../core/inputscanner').InputScanner;
  25. var BaseTokenizer = require('../core/tokenizer').Tokenizer;
  26. var BASETOKEN = require('../core/tokenizer').TOKEN;
  27. var Directives = require('../core/directives').Directives;
  28. var acorn = require('./acorn');
  29. var Pattern = require('../core/pattern').Pattern;
  30. var TemplatablePattern = require('../core/templatablepattern').TemplatablePattern;
  31. function in_array(what, arr) {
  32. return arr.indexOf(what) !== -1;
  33. }
  34. var TOKEN = {
  35. START_EXPR: 'TK_START_EXPR',
  36. END_EXPR: 'TK_END_EXPR',
  37. START_BLOCK: 'TK_START_BLOCK',
  38. END_BLOCK: 'TK_END_BLOCK',
  39. WORD: 'TK_WORD',
  40. RESERVED: 'TK_RESERVED',
  41. SEMICOLON: 'TK_SEMICOLON',
  42. STRING: 'TK_STRING',
  43. EQUALS: 'TK_EQUALS',
  44. OPERATOR: 'TK_OPERATOR',
  45. COMMA: 'TK_COMMA',
  46. BLOCK_COMMENT: 'TK_BLOCK_COMMENT',
  47. COMMENT: 'TK_COMMENT',
  48. DOT: 'TK_DOT',
  49. UNKNOWN: 'TK_UNKNOWN',
  50. START: BASETOKEN.START,
  51. RAW: BASETOKEN.RAW,
  52. EOF: BASETOKEN.EOF
  53. };
  54. var directives_core = new Directives(/\/\*/, /\*\//);
  55. var number_pattern = /0[xX][0123456789abcdefABCDEF]*|0[oO][01234567]*|0[bB][01]*|\d+n|(?:\.\d+|\d+\.?\d*)(?:[eE][+-]?\d+)?/;
  56. var digit = /[0-9]/;
  57. // Dot "." must be distinguished from "..." and decimal
  58. var dot_pattern = /[^\d\.]/;
  59. var positionable_operators = (
  60. ">>> === !== " +
  61. "<< && >= ** != == <= >> || ?? |> " +
  62. "< / - + > : & % ? ^ | *").split(' ');
  63. // IMPORTANT: this must be sorted longest to shortest or tokenizing many not work.
  64. // Also, you must update possitionable operators separately from punct
  65. var punct =
  66. ">>>= " +
  67. "... >>= <<= === >>> !== **= " +
  68. "=> ^= :: /= << <= == && -= >= >> != -- += ** || ?? ++ %= &= *= |= |> " +
  69. "= ! ? > < : / ^ - + * & % ~ |";
  70. punct = punct.replace(/[-[\]{}()*+?.,\\^$|#]/g, "\\$&");
  71. // ?. but not if followed by a number
  72. punct = '\\?\\.(?!\\d) ' + punct;
  73. punct = punct.replace(/ /g, '|');
  74. var punct_pattern = new RegExp(punct);
  75. // words which should always start on new line.
  76. var line_starters = 'continue,try,throw,return,var,let,const,if,switch,case,default,for,while,break,function,import,export'.split(',');
  77. var reserved_words = line_starters.concat(['do', 'in', 'of', 'else', 'get', 'set', 'new', 'catch', 'finally', 'typeof', 'yield', 'async', 'await', 'from', 'as']);
  78. var reserved_word_pattern = new RegExp('^(?:' + reserved_words.join('|') + ')$');
  79. // var template_pattern = /(?:(?:<\?php|<\?=)[\s\S]*?\?>)|(?:<%[\s\S]*?%>)/g;
  80. var in_html_comment;
  81. var Tokenizer = function(input_string, options) {
  82. BaseTokenizer.call(this, input_string, options);
  83. this._patterns.whitespace = this._patterns.whitespace.matching(
  84. /\u00A0\u1680\u180e\u2000-\u200a\u202f\u205f\u3000\ufeff/.source,
  85. /\u2028\u2029/.source);
  86. var pattern_reader = new Pattern(this._input);
  87. var templatable = new TemplatablePattern(this._input)
  88. .read_options(this._options);
  89. this.__patterns = {
  90. template: templatable,
  91. identifier: templatable.starting_with(acorn.identifier).matching(acorn.identifierMatch),
  92. number: pattern_reader.matching(number_pattern),
  93. punct: pattern_reader.matching(punct_pattern),
  94. // comment ends just before nearest linefeed or end of file
  95. comment: pattern_reader.starting_with(/\/\//).until(/[\n\r\u2028\u2029]/),
  96. // /* ... */ comment ends with nearest */ or end of file
  97. block_comment: pattern_reader.starting_with(/\/\*/).until_after(/\*\//),
  98. html_comment_start: pattern_reader.matching(/<!--/),
  99. html_comment_end: pattern_reader.matching(/-->/),
  100. include: pattern_reader.starting_with(/#include/).until_after(acorn.lineBreak),
  101. shebang: pattern_reader.starting_with(/#!/).until_after(acorn.lineBreak),
  102. xml: pattern_reader.matching(/[\s\S]*?<(\/?)([-a-zA-Z:0-9_.]+|{[\s\S]+?}|!\[CDATA\[[\s\S]*?\]\])(\s+{[\s\S]+?}|\s+[-a-zA-Z:0-9_.]+|\s+[-a-zA-Z:0-9_.]+\s*=\s*('[^']*'|"[^"]*"|{[\s\S]+?}))*\s*(\/?)\s*>/),
  103. single_quote: templatable.until(/['\\\n\r\u2028\u2029]/),
  104. double_quote: templatable.until(/["\\\n\r\u2028\u2029]/),
  105. template_text: templatable.until(/[`\\$]/),
  106. template_expression: templatable.until(/[`}\\]/)
  107. };
  108. };
  109. Tokenizer.prototype = new BaseTokenizer();
  110. Tokenizer.prototype._is_comment = function(current_token) {
  111. return current_token.type === TOKEN.COMMENT || current_token.type === TOKEN.BLOCK_COMMENT || current_token.type === TOKEN.UNKNOWN;
  112. };
  113. Tokenizer.prototype._is_opening = function(current_token) {
  114. return current_token.type === TOKEN.START_BLOCK || current_token.type === TOKEN.START_EXPR;
  115. };
  116. Tokenizer.prototype._is_closing = function(current_token, open_token) {
  117. return (current_token.type === TOKEN.END_BLOCK || current_token.type === TOKEN.END_EXPR) &&
  118. (open_token && (
  119. (current_token.text === ']' && open_token.text === '[') ||
  120. (current_token.text === ')' && open_token.text === '(') ||
  121. (current_token.text === '}' && open_token.text === '{')));
  122. };
  123. Tokenizer.prototype._reset = function() {
  124. in_html_comment = false;
  125. };
  126. Tokenizer.prototype._get_next_token = function(previous_token, open_token) { // jshint unused:false
  127. var token = null;
  128. this._readWhitespace();
  129. var c = this._input.peek();
  130. if (c === null) {
  131. return this._create_token(TOKEN.EOF, '');
  132. }
  133. token = token || this._read_non_javascript(c);
  134. token = token || this._read_string(c);
  135. token = token || this._read_word(previous_token);
  136. token = token || this._read_singles(c);
  137. token = token || this._read_comment(c);
  138. token = token || this._read_regexp(c, previous_token);
  139. token = token || this._read_xml(c, previous_token);
  140. token = token || this._read_punctuation();
  141. token = token || this._create_token(TOKEN.UNKNOWN, this._input.next());
  142. return token;
  143. };
  144. Tokenizer.prototype._read_word = function(previous_token) {
  145. var resulting_string;
  146. resulting_string = this.__patterns.identifier.read();
  147. if (resulting_string !== '') {
  148. resulting_string = resulting_string.replace(acorn.allLineBreaks, '\n');
  149. if (!(previous_token.type === TOKEN.DOT ||
  150. (previous_token.type === TOKEN.RESERVED && (previous_token.text === 'set' || previous_token.text === 'get'))) &&
  151. reserved_word_pattern.test(resulting_string)) {
  152. if (resulting_string === 'in' || resulting_string === 'of') { // hack for 'in' and 'of' operators
  153. return this._create_token(TOKEN.OPERATOR, resulting_string);
  154. }
  155. return this._create_token(TOKEN.RESERVED, resulting_string);
  156. }
  157. return this._create_token(TOKEN.WORD, resulting_string);
  158. }
  159. resulting_string = this.__patterns.number.read();
  160. if (resulting_string !== '') {
  161. return this._create_token(TOKEN.WORD, resulting_string);
  162. }
  163. };
  164. Tokenizer.prototype._read_singles = function(c) {
  165. var token = null;
  166. if (c === '(' || c === '[') {
  167. token = this._create_token(TOKEN.START_EXPR, c);
  168. } else if (c === ')' || c === ']') {
  169. token = this._create_token(TOKEN.END_EXPR, c);
  170. } else if (c === '{') {
  171. token = this._create_token(TOKEN.START_BLOCK, c);
  172. } else if (c === '}') {
  173. token = this._create_token(TOKEN.END_BLOCK, c);
  174. } else if (c === ';') {
  175. token = this._create_token(TOKEN.SEMICOLON, c);
  176. } else if (c === '.' && dot_pattern.test(this._input.peek(1))) {
  177. token = this._create_token(TOKEN.DOT, c);
  178. } else if (c === ',') {
  179. token = this._create_token(TOKEN.COMMA, c);
  180. }
  181. if (token) {
  182. this._input.next();
  183. }
  184. return token;
  185. };
  186. Tokenizer.prototype._read_punctuation = function() {
  187. var resulting_string = this.__patterns.punct.read();
  188. if (resulting_string !== '') {
  189. if (resulting_string === '=') {
  190. return this._create_token(TOKEN.EQUALS, resulting_string);
  191. } else if (resulting_string === '?.') {
  192. return this._create_token(TOKEN.DOT, resulting_string);
  193. } else {
  194. return this._create_token(TOKEN.OPERATOR, resulting_string);
  195. }
  196. }
  197. };
  198. Tokenizer.prototype._read_non_javascript = function(c) {
  199. var resulting_string = '';
  200. if (c === '#') {
  201. if (this._is_first_token()) {
  202. resulting_string = this.__patterns.shebang.read();
  203. if (resulting_string) {
  204. return this._create_token(TOKEN.UNKNOWN, resulting_string.trim() + '\n');
  205. }
  206. }
  207. // handles extendscript #includes
  208. resulting_string = this.__patterns.include.read();
  209. if (resulting_string) {
  210. return this._create_token(TOKEN.UNKNOWN, resulting_string.trim() + '\n');
  211. }
  212. c = this._input.next();
  213. // Spidermonkey-specific sharp variables for circular references. Considered obsolete.
  214. var sharp = '#';
  215. if (this._input.hasNext() && this._input.testChar(digit)) {
  216. do {
  217. c = this._input.next();
  218. sharp += c;
  219. } while (this._input.hasNext() && c !== '#' && c !== '=');
  220. if (c === '#') {
  221. //
  222. } else if (this._input.peek() === '[' && this._input.peek(1) === ']') {
  223. sharp += '[]';
  224. this._input.next();
  225. this._input.next();
  226. } else if (this._input.peek() === '{' && this._input.peek(1) === '}') {
  227. sharp += '{}';
  228. this._input.next();
  229. this._input.next();
  230. }
  231. return this._create_token(TOKEN.WORD, sharp);
  232. }
  233. this._input.back();
  234. } else if (c === '<' && this._is_first_token()) {
  235. resulting_string = this.__patterns.html_comment_start.read();
  236. if (resulting_string) {
  237. while (this._input.hasNext() && !this._input.testChar(acorn.newline)) {
  238. resulting_string += this._input.next();
  239. }
  240. in_html_comment = true;
  241. return this._create_token(TOKEN.COMMENT, resulting_string);
  242. }
  243. } else if (in_html_comment && c === '-') {
  244. resulting_string = this.__patterns.html_comment_end.read();
  245. if (resulting_string) {
  246. in_html_comment = false;
  247. return this._create_token(TOKEN.COMMENT, resulting_string);
  248. }
  249. }
  250. return null;
  251. };
  252. Tokenizer.prototype._read_comment = function(c) {
  253. var token = null;
  254. if (c === '/') {
  255. var comment = '';
  256. if (this._input.peek(1) === '*') {
  257. // peek for comment /* ... */
  258. comment = this.__patterns.block_comment.read();
  259. var directives = directives_core.get_directives(comment);
  260. if (directives && directives.ignore === 'start') {
  261. comment += directives_core.readIgnored(this._input);
  262. }
  263. comment = comment.replace(acorn.allLineBreaks, '\n');
  264. token = this._create_token(TOKEN.BLOCK_COMMENT, comment);
  265. token.directives = directives;
  266. } else if (this._input.peek(1) === '/') {
  267. // peek for comment // ...
  268. comment = this.__patterns.comment.read();
  269. token = this._create_token(TOKEN.COMMENT, comment);
  270. }
  271. }
  272. return token;
  273. };
  274. Tokenizer.prototype._read_string = function(c) {
  275. if (c === '`' || c === "'" || c === '"') {
  276. var resulting_string = this._input.next();
  277. this.has_char_escapes = false;
  278. if (c === '`') {
  279. resulting_string += this._read_string_recursive('`', true, '${');
  280. } else {
  281. resulting_string += this._read_string_recursive(c);
  282. }
  283. if (this.has_char_escapes && this._options.unescape_strings) {
  284. resulting_string = unescape_string(resulting_string);
  285. }
  286. if (this._input.peek() === c) {
  287. resulting_string += this._input.next();
  288. }
  289. resulting_string = resulting_string.replace(acorn.allLineBreaks, '\n');
  290. return this._create_token(TOKEN.STRING, resulting_string);
  291. }
  292. return null;
  293. };
  294. Tokenizer.prototype._allow_regexp_or_xml = function(previous_token) {
  295. // regex and xml can only appear in specific locations during parsing
  296. return (previous_token.type === TOKEN.RESERVED && in_array(previous_token.text, ['return', 'case', 'throw', 'else', 'do', 'typeof', 'yield'])) ||
  297. (previous_token.type === TOKEN.END_EXPR && previous_token.text === ')' &&
  298. previous_token.opened.previous.type === TOKEN.RESERVED && in_array(previous_token.opened.previous.text, ['if', 'while', 'for'])) ||
  299. (in_array(previous_token.type, [TOKEN.COMMENT, TOKEN.START_EXPR, TOKEN.START_BLOCK, TOKEN.START,
  300. TOKEN.END_BLOCK, TOKEN.OPERATOR, TOKEN.EQUALS, TOKEN.EOF, TOKEN.SEMICOLON, TOKEN.COMMA
  301. ]));
  302. };
  303. Tokenizer.prototype._read_regexp = function(c, previous_token) {
  304. if (c === '/' && this._allow_regexp_or_xml(previous_token)) {
  305. // handle regexp
  306. //
  307. var resulting_string = this._input.next();
  308. var esc = false;
  309. var in_char_class = false;
  310. while (this._input.hasNext() &&
  311. ((esc || in_char_class || this._input.peek() !== c) &&
  312. !this._input.testChar(acorn.newline))) {
  313. resulting_string += this._input.peek();
  314. if (!esc) {
  315. esc = this._input.peek() === '\\';
  316. if (this._input.peek() === '[') {
  317. in_char_class = true;
  318. } else if (this._input.peek() === ']') {
  319. in_char_class = false;
  320. }
  321. } else {
  322. esc = false;
  323. }
  324. this._input.next();
  325. }
  326. if (this._input.peek() === c) {
  327. resulting_string += this._input.next();
  328. // regexps may have modifiers /regexp/MOD , so fetch those, too
  329. // Only [gim] are valid, but if the user puts in garbage, do what we can to take it.
  330. resulting_string += this._input.read(acorn.identifier);
  331. }
  332. return this._create_token(TOKEN.STRING, resulting_string);
  333. }
  334. return null;
  335. };
  336. Tokenizer.prototype._read_xml = function(c, previous_token) {
  337. if (this._options.e4x && c === "<" && this._allow_regexp_or_xml(previous_token)) {
  338. var xmlStr = '';
  339. var match = this.__patterns.xml.read_match();
  340. // handle e4x xml literals
  341. //
  342. if (match) {
  343. // Trim root tag to attempt to
  344. var rootTag = match[2].replace(/^{\s+/, '{').replace(/\s+}$/, '}');
  345. var isCurlyRoot = rootTag.indexOf('{') === 0;
  346. var depth = 0;
  347. while (match) {
  348. var isEndTag = !!match[1];
  349. var tagName = match[2];
  350. var isSingletonTag = (!!match[match.length - 1]) || (tagName.slice(0, 8) === "![CDATA[");
  351. if (!isSingletonTag &&
  352. (tagName === rootTag || (isCurlyRoot && tagName.replace(/^{\s+/, '{').replace(/\s+}$/, '}')))) {
  353. if (isEndTag) {
  354. --depth;
  355. } else {
  356. ++depth;
  357. }
  358. }
  359. xmlStr += match[0];
  360. if (depth <= 0) {
  361. break;
  362. }
  363. match = this.__patterns.xml.read_match();
  364. }
  365. // if we didn't close correctly, keep unformatted.
  366. if (!match) {
  367. xmlStr += this._input.match(/[\s\S]*/g)[0];
  368. }
  369. xmlStr = xmlStr.replace(acorn.allLineBreaks, '\n');
  370. return this._create_token(TOKEN.STRING, xmlStr);
  371. }
  372. }
  373. return null;
  374. };
  375. function unescape_string(s) {
  376. // You think that a regex would work for this
  377. // return s.replace(/\\x([0-9a-f]{2})/gi, function(match, val) {
  378. // return String.fromCharCode(parseInt(val, 16));
  379. // })
  380. // However, dealing with '\xff', '\\xff', '\\\xff' makes this more fun.
  381. var out = '',
  382. escaped = 0;
  383. var input_scan = new InputScanner(s);
  384. var matched = null;
  385. while (input_scan.hasNext()) {
  386. // Keep any whitespace, non-slash characters
  387. // also keep slash pairs.
  388. matched = input_scan.match(/([\s]|[^\\]|\\\\)+/g);
  389. if (matched) {
  390. out += matched[0];
  391. }
  392. if (input_scan.peek() === '\\') {
  393. input_scan.next();
  394. if (input_scan.peek() === 'x') {
  395. matched = input_scan.match(/x([0-9A-Fa-f]{2})/g);
  396. } else if (input_scan.peek() === 'u') {
  397. matched = input_scan.match(/u([0-9A-Fa-f]{4})/g);
  398. } else {
  399. out += '\\';
  400. if (input_scan.hasNext()) {
  401. out += input_scan.next();
  402. }
  403. continue;
  404. }
  405. // If there's some error decoding, return the original string
  406. if (!matched) {
  407. return s;
  408. }
  409. escaped = parseInt(matched[1], 16);
  410. if (escaped > 0x7e && escaped <= 0xff && matched[0].indexOf('x') === 0) {
  411. // we bail out on \x7f..\xff,
  412. // leaving whole string escaped,
  413. // as it's probably completely binary
  414. return s;
  415. } else if (escaped >= 0x00 && escaped < 0x20) {
  416. // leave 0x00...0x1f escaped
  417. out += '\\' + matched[0];
  418. continue;
  419. } else if (escaped === 0x22 || escaped === 0x27 || escaped === 0x5c) {
  420. // single-quote, apostrophe, backslash - escape these
  421. out += '\\' + String.fromCharCode(escaped);
  422. } else {
  423. out += String.fromCharCode(escaped);
  424. }
  425. }
  426. }
  427. return out;
  428. }
  429. // handle string
  430. //
  431. Tokenizer.prototype._read_string_recursive = function(delimiter, allow_unescaped_newlines, start_sub) {
  432. var current_char;
  433. var pattern;
  434. if (delimiter === '\'') {
  435. pattern = this.__patterns.single_quote;
  436. } else if (delimiter === '"') {
  437. pattern = this.__patterns.double_quote;
  438. } else if (delimiter === '`') {
  439. pattern = this.__patterns.template_text;
  440. } else if (delimiter === '}') {
  441. pattern = this.__patterns.template_expression;
  442. }
  443. var resulting_string = pattern.read();
  444. var next = '';
  445. while (this._input.hasNext()) {
  446. next = this._input.next();
  447. if (next === delimiter ||
  448. (!allow_unescaped_newlines && acorn.newline.test(next))) {
  449. this._input.back();
  450. break;
  451. } else if (next === '\\' && this._input.hasNext()) {
  452. current_char = this._input.peek();
  453. if (current_char === 'x' || current_char === 'u') {
  454. this.has_char_escapes = true;
  455. } else if (current_char === '\r' && this._input.peek(1) === '\n') {
  456. this._input.next();
  457. }
  458. next += this._input.next();
  459. } else if (start_sub) {
  460. if (start_sub === '${' && next === '$' && this._input.peek() === '{') {
  461. next += this._input.next();
  462. }
  463. if (start_sub === next) {
  464. if (delimiter === '`') {
  465. next += this._read_string_recursive('}', allow_unescaped_newlines, '`');
  466. } else {
  467. next += this._read_string_recursive('`', allow_unescaped_newlines, '${');
  468. }
  469. if (this._input.hasNext()) {
  470. next += this._input.next();
  471. }
  472. }
  473. }
  474. next += pattern.read();
  475. resulting_string += next;
  476. }
  477. return resulting_string;
  478. };
  479. module.exports.Tokenizer = Tokenizer;
  480. module.exports.TOKEN = TOKEN;
  481. module.exports.positionable_operators = positionable_operators.slice();
  482. module.exports.line_starters = line_starters.slice();